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": "t information\n .setValue '#user\\\\.email', 'test2@checkouttests.xyz'\n .setValue '#user\\\\.name', 'checkout test",
"end": 1491,
"score": 0.9999250173568726,
"start": 1468,
"tag": "EMAIL",
"value": "test2@checkouttests.xyz"
},
{
"context": "s.xyz'\n .setValue '#user\\\\.name', 'checkout test2'\n .setValue '#payment\\\\.account\\\\.number',",
"end": 1542,
"score": 0.9117809534072876,
"start": 1537,
"tag": "USERNAME",
"value": "test2"
}
] | test/test.coffee | verus-io/crowdstart-checkout | 14 | assert = require 'assert'
should = require('chai').should()
{getBrowser, TIMEOUT} = require './util'
parsePrice = (str) ->
parseFloat str.match /[\d.]+/
describe "Checkout (#{process.env.BROWSER})", ->
testPage = "http://localhost:#{process.env.PORT ? 3333}/widget.html"
openWidget = (browser) ->
browser
.url testPage
.waitForExist 'modal', TIMEOUT
# Click the Buy button
.click 'a.btn'
.waitForExist '.crowdstart-active', TIMEOUT
.waitForExist 'lineitem', TIMEOUT
.waitForVisible 'lineitem:nth-of-type(2) .select2', TIMEOUT
describe 'Changing the quantity of a line item', ->
it 'should update line item cost', (done) ->
unitPrice = 0
openWidget getBrowser()
# Select 2 for 'Such T-shirt
.selectByValue('.crowdstart-items > lineitem:nth-of-type(2) select', '2')
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-price'
.then (text) ->
console.log text
unitPrice = parsePrice text
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-total-price'
.then (text) ->
console.log text
lineItemPrice = parsePrice text
assert.strictEqual lineItemPrice, unitPrice * 2
.end done
describe 'Completing the form', ->
it 'should work', (done) ->
openWidget getBrowser()
# Payment information
.setValue '#user\\.email', 'test2@checkouttests.xyz'
.setValue '#user\\.name', 'checkout test2'
.setValue '#payment\\.account\\.number', '4242424242424242'
.setValue '#payment\\.account\\.expiry', '1122'
.setValue '#payment\\.account\\.cvc', '424'
.click 'label[for=agreed]'
.click 'confirm .crowdstart-button'
# Billing information
.waitForVisible 'shipping', TIMEOUT
.setValue '#order\\.shippingAddress\\.line1', '1234 fake street'
.setValue '#order\\.shippingAddress\\.city', 'fake city'
.setValue '#order\\.shippingAddress\\.state', 'fake state'
.setValue '#order\\.shippingAddress\\.postalCode', '55555'
.click 'confirm .crowdstart-button'
.waitForExist '.crowdstart-loader', TIMEOUT
.waitForExist '.crowdstart-loader', TIMEOUT, true
.waitForVisible 'thankyou', TIMEOUT
.getHTML 'thankyou h1'
.then (text) ->
assert.strictEqual text, '<h1>Thank You!</h1>'
.end done
| 162662 | assert = require 'assert'
should = require('chai').should()
{getBrowser, TIMEOUT} = require './util'
parsePrice = (str) ->
parseFloat str.match /[\d.]+/
describe "Checkout (#{process.env.BROWSER})", ->
testPage = "http://localhost:#{process.env.PORT ? 3333}/widget.html"
openWidget = (browser) ->
browser
.url testPage
.waitForExist 'modal', TIMEOUT
# Click the Buy button
.click 'a.btn'
.waitForExist '.crowdstart-active', TIMEOUT
.waitForExist 'lineitem', TIMEOUT
.waitForVisible 'lineitem:nth-of-type(2) .select2', TIMEOUT
describe 'Changing the quantity of a line item', ->
it 'should update line item cost', (done) ->
unitPrice = 0
openWidget getBrowser()
# Select 2 for 'Such T-shirt
.selectByValue('.crowdstart-items > lineitem:nth-of-type(2) select', '2')
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-price'
.then (text) ->
console.log text
unitPrice = parsePrice text
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-total-price'
.then (text) ->
console.log text
lineItemPrice = parsePrice text
assert.strictEqual lineItemPrice, unitPrice * 2
.end done
describe 'Completing the form', ->
it 'should work', (done) ->
openWidget getBrowser()
# Payment information
.setValue '#user\\.email', '<EMAIL>'
.setValue '#user\\.name', 'checkout test2'
.setValue '#payment\\.account\\.number', '4242424242424242'
.setValue '#payment\\.account\\.expiry', '1122'
.setValue '#payment\\.account\\.cvc', '424'
.click 'label[for=agreed]'
.click 'confirm .crowdstart-button'
# Billing information
.waitForVisible 'shipping', TIMEOUT
.setValue '#order\\.shippingAddress\\.line1', '1234 fake street'
.setValue '#order\\.shippingAddress\\.city', 'fake city'
.setValue '#order\\.shippingAddress\\.state', 'fake state'
.setValue '#order\\.shippingAddress\\.postalCode', '55555'
.click 'confirm .crowdstart-button'
.waitForExist '.crowdstart-loader', TIMEOUT
.waitForExist '.crowdstart-loader', TIMEOUT, true
.waitForVisible 'thankyou', TIMEOUT
.getHTML 'thankyou h1'
.then (text) ->
assert.strictEqual text, '<h1>Thank You!</h1>'
.end done
| true | assert = require 'assert'
should = require('chai').should()
{getBrowser, TIMEOUT} = require './util'
parsePrice = (str) ->
parseFloat str.match /[\d.]+/
describe "Checkout (#{process.env.BROWSER})", ->
testPage = "http://localhost:#{process.env.PORT ? 3333}/widget.html"
openWidget = (browser) ->
browser
.url testPage
.waitForExist 'modal', TIMEOUT
# Click the Buy button
.click 'a.btn'
.waitForExist '.crowdstart-active', TIMEOUT
.waitForExist 'lineitem', TIMEOUT
.waitForVisible 'lineitem:nth-of-type(2) .select2', TIMEOUT
describe 'Changing the quantity of a line item', ->
it 'should update line item cost', (done) ->
unitPrice = 0
openWidget getBrowser()
# Select 2 for 'Such T-shirt
.selectByValue('.crowdstart-items > lineitem:nth-of-type(2) select', '2')
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-price'
.then (text) ->
console.log text
unitPrice = parsePrice text
.getText '.crowdstart-items > lineitem:nth-of-type(2) .crowdstart-item-total-price'
.then (text) ->
console.log text
lineItemPrice = parsePrice text
assert.strictEqual lineItemPrice, unitPrice * 2
.end done
describe 'Completing the form', ->
it 'should work', (done) ->
openWidget getBrowser()
# Payment information
.setValue '#user\\.email', 'PI:EMAIL:<EMAIL>END_PI'
.setValue '#user\\.name', 'checkout test2'
.setValue '#payment\\.account\\.number', '4242424242424242'
.setValue '#payment\\.account\\.expiry', '1122'
.setValue '#payment\\.account\\.cvc', '424'
.click 'label[for=agreed]'
.click 'confirm .crowdstart-button'
# Billing information
.waitForVisible 'shipping', TIMEOUT
.setValue '#order\\.shippingAddress\\.line1', '1234 fake street'
.setValue '#order\\.shippingAddress\\.city', 'fake city'
.setValue '#order\\.shippingAddress\\.state', 'fake state'
.setValue '#order\\.shippingAddress\\.postalCode', '55555'
.click 'confirm .crowdstart-button'
.waitForExist '.crowdstart-loader', TIMEOUT
.waitForExist '.crowdstart-loader', TIMEOUT, true
.waitForVisible 'thankyou', TIMEOUT
.getHTML 'thankyou h1'
.then (text) ->
assert.strictEqual text, '<h1>Thank You!</h1>'
.end done
|
[
{
"context": "rview Rule to check for implicit objects\n# @author Julian Rosse\n###\n\n'use strict'\n\n#-----------------------------",
"end": 78,
"score": 0.9998735189437866,
"start": 66,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/rules/implicit-object.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to check for implicit objects
# @author Julian Rosse
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'forbid implicit objects'
category: 'Stylistic Issues'
recommended: no
# url: 'https://eslint.org/docs/rules/max-len'
schema: [
type: 'string'
enum: ['never']
,
type: 'object'
properties:
allowOwnLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{allowOwnLine} = context.options[1] ? {}
sourceCode = context.getSourceCode()
startsLine = (node) ->
prevToken = sourceCode.getTokenBefore node
return yes unless prevToken
node.loc.start.line isnt prevToken.loc.start.line
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
ObjectExpression: (node) ->
return unless node.implicit
return if node.parent?.parent?.type is 'ClassBody'
return if allowOwnLine and startsLine node
context.report {
node
message: 'Use explicit curly braces around objects'
}
| 28470 | ###*
# @fileoverview Rule to check for implicit objects
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'forbid implicit objects'
category: 'Stylistic Issues'
recommended: no
# url: 'https://eslint.org/docs/rules/max-len'
schema: [
type: 'string'
enum: ['never']
,
type: 'object'
properties:
allowOwnLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{allowOwnLine} = context.options[1] ? {}
sourceCode = context.getSourceCode()
startsLine = (node) ->
prevToken = sourceCode.getTokenBefore node
return yes unless prevToken
node.loc.start.line isnt prevToken.loc.start.line
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
ObjectExpression: (node) ->
return unless node.implicit
return if node.parent?.parent?.type is 'ClassBody'
return if allowOwnLine and startsLine node
context.report {
node
message: 'Use explicit curly braces around objects'
}
| true | ###*
# @fileoverview Rule to check for implicit objects
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'forbid implicit objects'
category: 'Stylistic Issues'
recommended: no
# url: 'https://eslint.org/docs/rules/max-len'
schema: [
type: 'string'
enum: ['never']
,
type: 'object'
properties:
allowOwnLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{allowOwnLine} = context.options[1] ? {}
sourceCode = context.getSourceCode()
startsLine = (node) ->
prevToken = sourceCode.getTokenBefore node
return yes unless prevToken
node.loc.start.line isnt prevToken.loc.start.line
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
ObjectExpression: (node) ->
return unless node.implicit
return if node.parent?.parent?.type is 'ClassBody'
return if allowOwnLine and startsLine node
context.report {
node
message: 'Use explicit curly braces around objects'
}
|
[
{
"context": "s @coursesAvailable()\n title = \"That\\'s all, folks!\"\n text = \"This concludes the mini-course ",
"end": 4844,
"score": 0.8267454504966736,
"start": 4839,
"tag": "NAME",
"value": "folks"
}
] | app/lib/mini-course.coffee | zooniverse/Planet-Hunters-2 | 1 | BaseController = require 'zooniverse/controllers/base-controller'
User = require 'zooniverse/models/user'
Api = require 'zooniverse/lib/api'
loginDialog = require 'zooniverse/controllers/login-dialog'
signupDialog = require 'zooniverse/controllers/signup-dialog'
miniCourseContent = require '../lib/mini-course-content'
require '../lib/en-us'
$ = window.jQuery
class MiniCourse extends BaseController
className: 'mini-course'
template: require '../views/mini-course'
@transitionTime = 1000
constructor: ->
super
@prompt_el = $(classifier.el).find("#course-prompt")
@course_el = $(classifier.el).find("#course-container")
@subject_el = $(classifier.el).find("#subject-container")
@prompt_el.hide()
@course_el.hide()
@idx_curr = 0
@ADMIN_MODE = false
# get content
@content = miniCourseContent # TODO: remove (unnecessary?)
User.on 'change', =>
if User.current?
if @prompt_el.hasClass 'show-login-prompt'
@hidePrompt()
# if User.current?
# @prompt_el.addClass 'signed-in'
# @prompt_el.find('.course-button').show()
# @prompt_el.find('#course-yes-container').show()
# @prompt_el.find('#course-message').html 'Mini-course available! Learn more about planet hunting. Interested?'
# else
# console.log 'PLEASE LOGIN!'
# @prompt_el.removeClass 'signed-in'
# @prompt_el.find('.course-button').hide()
# @prompt_el.find('#course-yes-container').hide()
# @prompt_el.find('#course-message').html 'Please <button style="text-decoration: underline" class="sign-in">sign in</button> or <button style="text-decoration: underline" class="sign-up">sign up</button> to receive credit for your discoveries and to participate in the Planet Hunters mini-course.'
# event callbacks
@prompt_el.on "click", "#course-yes", (e) => @onClickCourseYes()
@prompt_el.on "click", "#course-no", (e) => @onClickCourseNo()
@prompt_el.on "click", "#course-never", (e) => @onClickCourseNever()
@prompt_el.on "click", "#course-prompt-close", (e) => @hidePrompt()
@course_el.on "click", ".course-close", (e) => @hideCourse()
$(classifier.el).on "click", ".sign-in", (e) => loginDialog.show()
$(classifier.el).on "click", ".sign-up", (e) => signupDialog.show()
onClickCourseYes: ->
unless User.current is null
User.current.setPreference 'course', 'yes'
$('.course-button').removeClass('selected')
$('#course-yes').addClass('selected')
@prompt_el.fadeOut(0)
# @displayLatest() # THIS NEEDS TO CHANGE
onClickCourseNo: ->
unless User.current is null
User.current.setPreference 'course', 'no'
$('.course-button').removeClass('selected')
$('#course-no').addClass('selected')
@hidePrompt()
onClickCourseNever: ->
unless User.current is null
User.current.setPreference 'course', 'never'
$('.course-button').removeClass('selected')
$('#course-never').addClass('selected')
@hidePrompt()
incrementCount: ->
return unless User.current?
@count = @count + 1
User.current.setPreference 'count', @count
setRate: (rate) ->
@rate = rate
$('#course-interval').val(@rate)
coursesAvailable: ->
if @idx_last >= @content.length
return false
else
return true
launch: ->
# console.log "idx_curr: ", @idx_curr
# console.log "idx_last: ", @idx_last
return unless User.current?
return unless @coursesAvailable()
@idx_curr = @idx_last
@display(@idx_last)
@toggleInterface()
@unlockNext()
toggleInterface: ->
@course_el.fadeIn(@transitionTime)
@subject_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
display: (index) ->
prevBtn = $('.arrow.left')
nextBtn = $('.arrow.right')
if index > @idx_last
# console.log "You cannot view this course yet!"
unless @ADMIN_MODE
nextBtn.hide()
return
else
@idx_curr = +index
unless @ADMIN_MODE
# hide arrows at ends
if index is 0
prevBtn.hide() # already at first course
else
prevBtn.show()
if index >= @idx_last
nextBtn.hide()
else
nextBtn.show()
@loadContent(@idx_curr)
unlockNext: ->
return unless @coursesAvailable()
return unless User.current?
@idx_curr = @idx_last
@idx_last = @idx_last + 1
User.current.setPreference 'curr_course_id', @idx_last
console.log 'NEXT MINI-COURSE WILL BE: ', @idx_last
loadContent: (index) ->
console.log "LOADING CONTENT FOR LESSON: ", index
# if typeof index is undefined
# index = @idx_last # default to latest
unless @coursesAvailable()
title = "That\'s all, folks!"
text = "This concludes the mini-course series. Thanks for tuning in!"
figure = ""
# TODO: maybe set preference to "never" after this?
else
title = @content[index].material.title
text = @content[index].material.text
figure = @content[index].material.figure
video = @content[index].material.video
figure_credits = @content[index].material.figure_credits
@course_el.find("#course-title").html title
@course_el.find(".course-text").html text
if video?
@course_el.find("#course-figure").hide()
@course_el.find("#course-video").show()
@course_el.find("#course-video").html video
else
@course_el.find("#course-figure").show()
@course_el.find("#course-video").hide()
@course_el.find("#course-figure").attr 'src', figure
@course_el.find(".course-figure-credits").html figure_credits
hideCourse: ->
@subject_el.fadeIn(@transitionTime)
@course_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
showPrompt: ->
@prompt_el.fadeIn(@transitionTime)
hidePrompt: (delay) ->
@prompt_el.fadeOut(delay)
getPref: ->
return unless User.current?
@pref = User.current?.preferences?.planet_hunter?.course
return @pref
resetCourse: ->
return unless User.current?
console.log 'initializing mini-course...'
# User.current.setPreference 'course', 'yes'
User.current.setPreference 'count', 0
User.current.setPreference 'curr_course_id', 0
# User.current.setPreference 'supplemental_option', true
@count = 0
@idx_last = +0
@idx_curr = +0
console.log """
idx_curr = #{@idx_curr}
idx_last = #{@idx_last}
"""
module.exports = MiniCourse
| 94251 | BaseController = require 'zooniverse/controllers/base-controller'
User = require 'zooniverse/models/user'
Api = require 'zooniverse/lib/api'
loginDialog = require 'zooniverse/controllers/login-dialog'
signupDialog = require 'zooniverse/controllers/signup-dialog'
miniCourseContent = require '../lib/mini-course-content'
require '../lib/en-us'
$ = window.jQuery
class MiniCourse extends BaseController
className: 'mini-course'
template: require '../views/mini-course'
@transitionTime = 1000
constructor: ->
super
@prompt_el = $(classifier.el).find("#course-prompt")
@course_el = $(classifier.el).find("#course-container")
@subject_el = $(classifier.el).find("#subject-container")
@prompt_el.hide()
@course_el.hide()
@idx_curr = 0
@ADMIN_MODE = false
# get content
@content = miniCourseContent # TODO: remove (unnecessary?)
User.on 'change', =>
if User.current?
if @prompt_el.hasClass 'show-login-prompt'
@hidePrompt()
# if User.current?
# @prompt_el.addClass 'signed-in'
# @prompt_el.find('.course-button').show()
# @prompt_el.find('#course-yes-container').show()
# @prompt_el.find('#course-message').html 'Mini-course available! Learn more about planet hunting. Interested?'
# else
# console.log 'PLEASE LOGIN!'
# @prompt_el.removeClass 'signed-in'
# @prompt_el.find('.course-button').hide()
# @prompt_el.find('#course-yes-container').hide()
# @prompt_el.find('#course-message').html 'Please <button style="text-decoration: underline" class="sign-in">sign in</button> or <button style="text-decoration: underline" class="sign-up">sign up</button> to receive credit for your discoveries and to participate in the Planet Hunters mini-course.'
# event callbacks
@prompt_el.on "click", "#course-yes", (e) => @onClickCourseYes()
@prompt_el.on "click", "#course-no", (e) => @onClickCourseNo()
@prompt_el.on "click", "#course-never", (e) => @onClickCourseNever()
@prompt_el.on "click", "#course-prompt-close", (e) => @hidePrompt()
@course_el.on "click", ".course-close", (e) => @hideCourse()
$(classifier.el).on "click", ".sign-in", (e) => loginDialog.show()
$(classifier.el).on "click", ".sign-up", (e) => signupDialog.show()
onClickCourseYes: ->
unless User.current is null
User.current.setPreference 'course', 'yes'
$('.course-button').removeClass('selected')
$('#course-yes').addClass('selected')
@prompt_el.fadeOut(0)
# @displayLatest() # THIS NEEDS TO CHANGE
onClickCourseNo: ->
unless User.current is null
User.current.setPreference 'course', 'no'
$('.course-button').removeClass('selected')
$('#course-no').addClass('selected')
@hidePrompt()
onClickCourseNever: ->
unless User.current is null
User.current.setPreference 'course', 'never'
$('.course-button').removeClass('selected')
$('#course-never').addClass('selected')
@hidePrompt()
incrementCount: ->
return unless User.current?
@count = @count + 1
User.current.setPreference 'count', @count
setRate: (rate) ->
@rate = rate
$('#course-interval').val(@rate)
coursesAvailable: ->
if @idx_last >= @content.length
return false
else
return true
launch: ->
# console.log "idx_curr: ", @idx_curr
# console.log "idx_last: ", @idx_last
return unless User.current?
return unless @coursesAvailable()
@idx_curr = @idx_last
@display(@idx_last)
@toggleInterface()
@unlockNext()
toggleInterface: ->
@course_el.fadeIn(@transitionTime)
@subject_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
display: (index) ->
prevBtn = $('.arrow.left')
nextBtn = $('.arrow.right')
if index > @idx_last
# console.log "You cannot view this course yet!"
unless @ADMIN_MODE
nextBtn.hide()
return
else
@idx_curr = +index
unless @ADMIN_MODE
# hide arrows at ends
if index is 0
prevBtn.hide() # already at first course
else
prevBtn.show()
if index >= @idx_last
nextBtn.hide()
else
nextBtn.show()
@loadContent(@idx_curr)
unlockNext: ->
return unless @coursesAvailable()
return unless User.current?
@idx_curr = @idx_last
@idx_last = @idx_last + 1
User.current.setPreference 'curr_course_id', @idx_last
console.log 'NEXT MINI-COURSE WILL BE: ', @idx_last
loadContent: (index) ->
console.log "LOADING CONTENT FOR LESSON: ", index
# if typeof index is undefined
# index = @idx_last # default to latest
unless @coursesAvailable()
title = "That\'s all, <NAME>!"
text = "This concludes the mini-course series. Thanks for tuning in!"
figure = ""
# TODO: maybe set preference to "never" after this?
else
title = @content[index].material.title
text = @content[index].material.text
figure = @content[index].material.figure
video = @content[index].material.video
figure_credits = @content[index].material.figure_credits
@course_el.find("#course-title").html title
@course_el.find(".course-text").html text
if video?
@course_el.find("#course-figure").hide()
@course_el.find("#course-video").show()
@course_el.find("#course-video").html video
else
@course_el.find("#course-figure").show()
@course_el.find("#course-video").hide()
@course_el.find("#course-figure").attr 'src', figure
@course_el.find(".course-figure-credits").html figure_credits
hideCourse: ->
@subject_el.fadeIn(@transitionTime)
@course_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
showPrompt: ->
@prompt_el.fadeIn(@transitionTime)
hidePrompt: (delay) ->
@prompt_el.fadeOut(delay)
getPref: ->
return unless User.current?
@pref = User.current?.preferences?.planet_hunter?.course
return @pref
resetCourse: ->
return unless User.current?
console.log 'initializing mini-course...'
# User.current.setPreference 'course', 'yes'
User.current.setPreference 'count', 0
User.current.setPreference 'curr_course_id', 0
# User.current.setPreference 'supplemental_option', true
@count = 0
@idx_last = +0
@idx_curr = +0
console.log """
idx_curr = #{@idx_curr}
idx_last = #{@idx_last}
"""
module.exports = MiniCourse
| true | BaseController = require 'zooniverse/controllers/base-controller'
User = require 'zooniverse/models/user'
Api = require 'zooniverse/lib/api'
loginDialog = require 'zooniverse/controllers/login-dialog'
signupDialog = require 'zooniverse/controllers/signup-dialog'
miniCourseContent = require '../lib/mini-course-content'
require '../lib/en-us'
$ = window.jQuery
class MiniCourse extends BaseController
className: 'mini-course'
template: require '../views/mini-course'
@transitionTime = 1000
constructor: ->
super
@prompt_el = $(classifier.el).find("#course-prompt")
@course_el = $(classifier.el).find("#course-container")
@subject_el = $(classifier.el).find("#subject-container")
@prompt_el.hide()
@course_el.hide()
@idx_curr = 0
@ADMIN_MODE = false
# get content
@content = miniCourseContent # TODO: remove (unnecessary?)
User.on 'change', =>
if User.current?
if @prompt_el.hasClass 'show-login-prompt'
@hidePrompt()
# if User.current?
# @prompt_el.addClass 'signed-in'
# @prompt_el.find('.course-button').show()
# @prompt_el.find('#course-yes-container').show()
# @prompt_el.find('#course-message').html 'Mini-course available! Learn more about planet hunting. Interested?'
# else
# console.log 'PLEASE LOGIN!'
# @prompt_el.removeClass 'signed-in'
# @prompt_el.find('.course-button').hide()
# @prompt_el.find('#course-yes-container').hide()
# @prompt_el.find('#course-message').html 'Please <button style="text-decoration: underline" class="sign-in">sign in</button> or <button style="text-decoration: underline" class="sign-up">sign up</button> to receive credit for your discoveries and to participate in the Planet Hunters mini-course.'
# event callbacks
@prompt_el.on "click", "#course-yes", (e) => @onClickCourseYes()
@prompt_el.on "click", "#course-no", (e) => @onClickCourseNo()
@prompt_el.on "click", "#course-never", (e) => @onClickCourseNever()
@prompt_el.on "click", "#course-prompt-close", (e) => @hidePrompt()
@course_el.on "click", ".course-close", (e) => @hideCourse()
$(classifier.el).on "click", ".sign-in", (e) => loginDialog.show()
$(classifier.el).on "click", ".sign-up", (e) => signupDialog.show()
onClickCourseYes: ->
unless User.current is null
User.current.setPreference 'course', 'yes'
$('.course-button').removeClass('selected')
$('#course-yes').addClass('selected')
@prompt_el.fadeOut(0)
# @displayLatest() # THIS NEEDS TO CHANGE
onClickCourseNo: ->
unless User.current is null
User.current.setPreference 'course', 'no'
$('.course-button').removeClass('selected')
$('#course-no').addClass('selected')
@hidePrompt()
onClickCourseNever: ->
unless User.current is null
User.current.setPreference 'course', 'never'
$('.course-button').removeClass('selected')
$('#course-never').addClass('selected')
@hidePrompt()
incrementCount: ->
return unless User.current?
@count = @count + 1
User.current.setPreference 'count', @count
setRate: (rate) ->
@rate = rate
$('#course-interval').val(@rate)
coursesAvailable: ->
if @idx_last >= @content.length
return false
else
return true
launch: ->
# console.log "idx_curr: ", @idx_curr
# console.log "idx_last: ", @idx_last
return unless User.current?
return unless @coursesAvailable()
@idx_curr = @idx_last
@display(@idx_last)
@toggleInterface()
@unlockNext()
toggleInterface: ->
@course_el.fadeIn(@transitionTime)
@subject_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
display: (index) ->
prevBtn = $('.arrow.left')
nextBtn = $('.arrow.right')
if index > @idx_last
# console.log "You cannot view this course yet!"
unless @ADMIN_MODE
nextBtn.hide()
return
else
@idx_curr = +index
unless @ADMIN_MODE
# hide arrows at ends
if index is 0
prevBtn.hide() # already at first course
else
prevBtn.show()
if index >= @idx_last
nextBtn.hide()
else
nextBtn.show()
@loadContent(@idx_curr)
unlockNext: ->
return unless @coursesAvailable()
return unless User.current?
@idx_curr = @idx_last
@idx_last = @idx_last + 1
User.current.setPreference 'curr_course_id', @idx_last
console.log 'NEXT MINI-COURSE WILL BE: ', @idx_last
loadContent: (index) ->
console.log "LOADING CONTENT FOR LESSON: ", index
# if typeof index is undefined
# index = @idx_last # default to latest
unless @coursesAvailable()
title = "That\'s all, PI:NAME:<NAME>END_PI!"
text = "This concludes the mini-course series. Thanks for tuning in!"
figure = ""
# TODO: maybe set preference to "never" after this?
else
title = @content[index].material.title
text = @content[index].material.text
figure = @content[index].material.figure
video = @content[index].material.video
figure_credits = @content[index].material.figure_credits
@course_el.find("#course-title").html title
@course_el.find(".course-text").html text
if video?
@course_el.find("#course-figure").hide()
@course_el.find("#course-video").show()
@course_el.find("#course-video").html video
else
@course_el.find("#course-figure").show()
@course_el.find("#course-video").hide()
@course_el.find("#course-figure").attr 'src', figure
@course_el.find(".course-figure-credits").html figure_credits
hideCourse: ->
@subject_el.fadeIn(@transitionTime)
@course_el.fadeOut(@transitionTime)
@subject_el.toggleClass("hidden")
@course_el.toggleClass("visible")
showPrompt: ->
@prompt_el.fadeIn(@transitionTime)
hidePrompt: (delay) ->
@prompt_el.fadeOut(delay)
getPref: ->
return unless User.current?
@pref = User.current?.preferences?.planet_hunter?.course
return @pref
resetCourse: ->
return unless User.current?
console.log 'initializing mini-course...'
# User.current.setPreference 'course', 'yes'
User.current.setPreference 'count', 0
User.current.setPreference 'curr_course_id', 0
# User.current.setPreference 'supplemental_option', true
@count = 0
@idx_last = +0
@idx_curr = +0
console.log """
idx_curr = #{@idx_curr}
idx_last = #{@idx_last}
"""
module.exports = MiniCourse
|
[
{
"context": "red = \n name: 'red',\n symbol: 'O',\n homePoint: 25,\n homeQuadrant:",
"end": 19,
"score": 0.9981755614280701,
"start": 16,
"tag": "NAME",
"value": "red"
},
{
"context": "homeQuadrant: 3,\n direction: 1\nblack = \n name: 'black',\n symbol: 'X',\n homePoint: 0,\n homeQuadrant: ",
"end": 111,
"score": 0.9955675005912781,
"start": 106,
"tag": "NAME",
"value": "black"
}
] | lib/teams.coffee | rabidaudio/backgammon | 0 | red =
name: 'red',
symbol: 'O',
homePoint: 25,
homeQuadrant: 3,
direction: 1
black =
name: 'black',
symbol: 'X',
homePoint: 0,
homeQuadrant: 0,
direction: -1
[red.otherTeam, black.otherTeam] = [black, red]
module.exports =
red: red,
black: black | 44617 | red =
name: '<NAME>',
symbol: 'O',
homePoint: 25,
homeQuadrant: 3,
direction: 1
black =
name: '<NAME>',
symbol: 'X',
homePoint: 0,
homeQuadrant: 0,
direction: -1
[red.otherTeam, black.otherTeam] = [black, red]
module.exports =
red: red,
black: black | true | red =
name: 'PI:NAME:<NAME>END_PI',
symbol: 'O',
homePoint: 25,
homeQuadrant: 3,
direction: 1
black =
name: 'PI:NAME:<NAME>END_PI',
symbol: 'X',
homePoint: 0,
homeQuadrant: 0,
direction: -1
[red.otherTeam, black.otherTeam] = [black, red]
module.exports =
red: red,
black: black |
[
{
"context": "t.deepEqual [{\"id\":\"1\"}], result\n done()\n\n # Kai Sellgren's original demo example\n it \"can create table, i",
"end": 635,
"score": 0.9603199362754822,
"start": 623,
"tag": "NAME",
"value": "Kai Sellgren"
},
{
"context": "ext\":\"the second item\"}], result\n done()\n\n # Gurjeet Singh's demo example\n it \"can bulk insert, select wher",
"end": 1145,
"score": 0.8479382991790771,
"start": 1132,
"tag": "NAME",
"value": "Gurjeet Singh"
},
{
"context": " integer);\n\n INSERT INTO employees VALUES (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4);\n INSERT",
"end": 1598,
"score": 0.9996635317802429,
"start": 1591,
"tag": "NAME",
"value": "JOHNSON"
},
{
"context": ";\n\n INSERT INTO employees VALUES (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4);\n INSERT INTO em",
"end": 1606,
"score": 0.9994136095046997,
"start": 1601,
"tag": "NAME",
"value": "ADMIN"
},
{
"context": "000,NULL,4);\n INSERT INTO employees VALUES (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3);\n INSER",
"end": 1682,
"score": 0.9997528791427612,
"start": 1675,
"tag": "NAME",
"value": "HARDING"
},
{
"context": ");\n INSERT INTO employees VALUES (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3);\n INSERT INTO emp",
"end": 1692,
"score": 0.890765368938446,
"start": 1685,
"tag": "NAME",
"value": "MANAGER"
},
{
"context": "2000,300,3);\n INSERT INTO employees VALUES (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3);\n INSER",
"end": 1764,
"score": 0.9955673217773438,
"start": 1760,
"tag": "NAME",
"value": "TAFT"
},
{
"context": "5000,500,3);\n INSERT INTO employees VALUES (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3);\n INSE",
"end": 1848,
"score": 0.9998409748077393,
"start": 1842,
"tag": "NAME",
"value": "HOOVER"
},
{
"context": "3);\n INSERT INTO employees VALUES (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3);\n INSERT INTO em",
"end": 1858,
"score": 0.9986841082572937,
"start": 1851,
"tag": "NAME",
"value": "SALES I"
},
{
"context": "000,NULL,3);\n INSERT INTO employees VALUES (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4);\n INSERT ",
"end": 1934,
"score": 0.9998614192008972,
"start": 1927,
"tag": "NAME",
"value": "LINCOLN"
},
{
"context": "500,1400,4);\n INSERT INTO employees VALUES (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4);\n INSE",
"end": 2018,
"score": 0.9998576045036316,
"start": 2010,
"tag": "NAME",
"value": "GARFIELD"
},
{
"context": "000,NULL,4);\n INSERT INTO employees VALUES (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4);\n INSERT ",
"end": 2101,
"score": 0.9998397827148438,
"start": 2097,
"tag": "NAME",
"value": "POLK"
},
{
"context": "000,NULL,4);\n INSERT INTO employees VALUES (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2);\n IN",
"end": 2182,
"score": 0.9998788833618164,
"start": 2177,
"tag": "NAME",
"value": "GRANT"
},
{
"context": " INSERT INTO employees VALUES (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2);\n INSERT INTO e",
"end": 2193,
"score": 0.8326153755187988,
"start": 2191,
"tag": "NAME",
"value": "ER"
},
{
"context": "000,NULL,2);\n INSERT INTO employees VALUES (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4);\n INSER",
"end": 2270,
"score": 0.9997524619102478,
"start": 2263,
"tag": "NAME",
"value": "JACKSON"
},
{
"context": ");\n INSERT INTO employees VALUES (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4);\n INSERT INTO",
"end": 2276,
"score": 0.9995611906051636,
"start": 2273,
"tag": "NAME",
"value": "CEO"
},
{
"context": "00,NULL,4);\n INSERT INTO employees VALUES (10,'FILLMORE','MANAGER',9,'08-09-1994',56000,NULL,2);\n INSE",
"end": 2357,
"score": 0.9998451471328735,
"start": 2349,
"tag": "NAME",
"value": "FILLMORE"
},
{
"context": "00,NULL,2);\n INSERT INTO employees VALUES (11,'ADAMS','ENGINEER',10,'03-15-1996',34000,NULL,2);\n IN",
"end": 2442,
"score": 0.9998214244842529,
"start": 2437,
"tag": "NAME",
"value": "ADAMS"
},
{
"context": "00,NULL,2);\n INSERT INTO employees VALUES (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4);\n INSERT",
"end": 2534,
"score": 0.9998559355735779,
"start": 2524,
"tag": "NAME",
"value": "WASHINGTON"
},
{
"context": " INSERT INTO employees VALUES (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4);\n INSERT INTO em",
"end": 2542,
"score": 0.5901871919631958,
"start": 2537,
"tag": "NAME",
"value": "ADMIN"
},
{
"context": "00,NULL,4);\n INSERT INTO employees VALUES (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2);\n IN",
"end": 2618,
"score": 0.9998580813407898,
"start": 2612,
"tag": "NAME",
"value": "MONROE"
},
{
"context": "00,NULL,2);\n INSERT INTO employees VALUES (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1);\n '''\n\n ",
"end": 2709,
"score": 0.9998493194580078,
"start": 2700,
"tag": "NAME",
"value": "ROOSEVELT"
},
{
"context": "lts) ->\n assert.deepEqual [{\"id\":\"9\",\"name\":\"JACKSON\",\"designation\":\"CEO\",\"manager\":null,\"hired_on\":\"0",
"end": 2889,
"score": 0.9995914101600647,
"start": 2882,
"tag": "NAME",
"value": "JACKSON"
}
] | test/test.coffee | davgit/sql.js | 1 | assert = require('chai').assert
Sql = require '../js/node-sqlite-purejs.js'
path = require 'path'
fs = require 'fs'
db_file = path.join __dirname, 'fixtures', 'db', 'development.sqlite'
describe 'Node SQLite', ->
db = `undefined`
beforeEach (done) ->
if fs.existsSync db_file
fs.unlinkSync db_file
Sql.open db_file, {
manual_load: true
manual_save: true
parse_multiple: true
}, (err, _db) ->
throw err if err
db = _db
done()
it "can select", (done) ->
db.exec 'SELECT 1 `id`;', (err, result) ->
assert.deepEqual [{"id":"1"}], result
done()
# Kai Sellgren's original demo example
it "can create table, insert, and select, returning last result in multi-query", (done) ->
db.exec '''
CREATE TABLE my_table(key INTEGER, value INTEGER, text VARCHAR(100));
INSERT INTO my_table VALUES(1, 25, 'the first item');
INSERT INTO my_table VALUES(2, 987, 'the second item');
SELECT key, text FROM my_table WHERE value == 987;
''', (err, result) ->
assert.deepEqual [{"key":"2","text":"the second item"}], result
done()
# Gurjeet Singh's demo example
it "can bulk insert, select where, select aggregation functions, and group by", (done) ->
db.exec '''
/* Demo DB */
CREATE TABLE employees( id integer, name text,
designation text, manager integer,
hired_on date, salary integer,
commission float, dept integer);
INSERT INTO employees VALUES (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4);
INSERT INTO employees VALUES (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3);
INSERT INTO employees VALUES (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3);
INSERT INTO employees VALUES (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3);
INSERT INTO employees VALUES (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4);
INSERT INTO employees VALUES (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4);
INSERT INTO employees VALUES (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4);
INSERT INTO employees VALUES (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2);
INSERT INTO employees VALUES (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4);
INSERT INTO employees VALUES (10,'FILLMORE','MANAGER',9,'08-09-1994',56000,NULL,2);
INSERT INTO employees VALUES (11,'ADAMS','ENGINEER',10,'03-15-1996',34000,NULL,2);
INSERT INTO employees VALUES (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4);
INSERT INTO employees VALUES (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2);
INSERT INTO employees VALUES (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1);
'''
db.exec "SELECT * FROM employees WHERE designation = 'CEO';", (err, results) ->
assert.deepEqual [{"id":"9","name":"JACKSON","designation":"CEO","manager":null,"hired_on":"01-01-1990","salary":"75000","commission":null,"dept":"4"}], results
db.exec "SELECT MAX(salary) AS 'Highest Salary' FROM employees;", (err, results) ->
assert.deepEqual [{"Highest Salary":"75000"}], results
db.exec """
SELECT dept, MAX(salary) As 'Highest Salary in department'
FROM employees
GROUP BY dept;
""", (err, results) ->
assert.deepEqual [{"dept":"1","Highest Salary in department":"35000"},{"dept":"2","Highest Salary in department":"56000"},{"dept":"3","Highest Salary in department":"52000"},{"dept":"4","Highest Salary in department":"75000"}], results
done()
it "can write database to disk", (done) ->
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
""", (err) ->
throw err if err
db.save (err) ->
throw err if err
assert.ok fs.existsSync db_file
done()
it "can read database from disk", (done) ->
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
INSERT INTO cars (color) VALUES ('red');
INSERT INTO cars (color) VALUES ('blue');
INSERT INTO cars (color) VALUES ('green');
""", (err, result) ->
throw err if err
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec 'SELECT * FROM cars;', (err, result) ->
assert.deepEqual [{"id":"1","color":"red"},{"id":"2","color":"blue"},{"id":"3","color":"green"}], result
done()
| 58622 | assert = require('chai').assert
Sql = require '../js/node-sqlite-purejs.js'
path = require 'path'
fs = require 'fs'
db_file = path.join __dirname, 'fixtures', 'db', 'development.sqlite'
describe 'Node SQLite', ->
db = `undefined`
beforeEach (done) ->
if fs.existsSync db_file
fs.unlinkSync db_file
Sql.open db_file, {
manual_load: true
manual_save: true
parse_multiple: true
}, (err, _db) ->
throw err if err
db = _db
done()
it "can select", (done) ->
db.exec 'SELECT 1 `id`;', (err, result) ->
assert.deepEqual [{"id":"1"}], result
done()
# <NAME>'s original demo example
it "can create table, insert, and select, returning last result in multi-query", (done) ->
db.exec '''
CREATE TABLE my_table(key INTEGER, value INTEGER, text VARCHAR(100));
INSERT INTO my_table VALUES(1, 25, 'the first item');
INSERT INTO my_table VALUES(2, 987, 'the second item');
SELECT key, text FROM my_table WHERE value == 987;
''', (err, result) ->
assert.deepEqual [{"key":"2","text":"the second item"}], result
done()
# <NAME>'s demo example
it "can bulk insert, select where, select aggregation functions, and group by", (done) ->
db.exec '''
/* Demo DB */
CREATE TABLE employees( id integer, name text,
designation text, manager integer,
hired_on date, salary integer,
commission float, dept integer);
INSERT INTO employees VALUES (1,'<NAME>','<NAME>',6,'12-17-1990',18000,NULL,4);
INSERT INTO employees VALUES (2,'<NAME>','<NAME>',9,'02-02-1998',52000,300,3);
INSERT INTO employees VALUES (3,'<NAME>','SALES I',2,'01-02-1996',25000,500,3);
INSERT INTO employees VALUES (4,'<NAME>','<NAME>',2,'04-02-1990',27000,NULL,3);
INSERT INTO employees VALUES (5,'<NAME>','TECH',6,'06-23-1994',22500,1400,4);
INSERT INTO employees VALUES (6,'<NAME>','MANAGER',9,'05-01-1993',54000,NULL,4);
INSERT INTO employees VALUES (7,'<NAME>','TECH',6,'09-22-1997',25000,NULL,4);
INSERT INTO employees VALUES (8,'<NAME>','ENGINE<NAME>',10,'03-30-1997',32000,NULL,2);
INSERT INTO employees VALUES (9,'<NAME>','<NAME>',NULL,'01-01-1990',75000,NULL,4);
INSERT INTO employees VALUES (10,'<NAME>','MANAGER',9,'08-09-1994',56000,NULL,2);
INSERT INTO employees VALUES (11,'<NAME>','ENGINEER',10,'03-15-1996',34000,NULL,2);
INSERT INTO employees VALUES (12,'<NAME>','<NAME>',6,'04-16-1998',18000,NULL,4);
INSERT INTO employees VALUES (13,'<NAME>','ENGINEER',10,'12-03-2000',30000,NULL,2);
INSERT INTO employees VALUES (14,'<NAME>','CPA',9,'10-12-1995',35000,NULL,1);
'''
db.exec "SELECT * FROM employees WHERE designation = 'CEO';", (err, results) ->
assert.deepEqual [{"id":"9","name":"<NAME>","designation":"CEO","manager":null,"hired_on":"01-01-1990","salary":"75000","commission":null,"dept":"4"}], results
db.exec "SELECT MAX(salary) AS 'Highest Salary' FROM employees;", (err, results) ->
assert.deepEqual [{"Highest Salary":"75000"}], results
db.exec """
SELECT dept, MAX(salary) As 'Highest Salary in department'
FROM employees
GROUP BY dept;
""", (err, results) ->
assert.deepEqual [{"dept":"1","Highest Salary in department":"35000"},{"dept":"2","Highest Salary in department":"56000"},{"dept":"3","Highest Salary in department":"52000"},{"dept":"4","Highest Salary in department":"75000"}], results
done()
it "can write database to disk", (done) ->
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
""", (err) ->
throw err if err
db.save (err) ->
throw err if err
assert.ok fs.existsSync db_file
done()
it "can read database from disk", (done) ->
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
INSERT INTO cars (color) VALUES ('red');
INSERT INTO cars (color) VALUES ('blue');
INSERT INTO cars (color) VALUES ('green');
""", (err, result) ->
throw err if err
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec 'SELECT * FROM cars;', (err, result) ->
assert.deepEqual [{"id":"1","color":"red"},{"id":"2","color":"blue"},{"id":"3","color":"green"}], result
done()
| true | assert = require('chai').assert
Sql = require '../js/node-sqlite-purejs.js'
path = require 'path'
fs = require 'fs'
db_file = path.join __dirname, 'fixtures', 'db', 'development.sqlite'
describe 'Node SQLite', ->
db = `undefined`
beforeEach (done) ->
if fs.existsSync db_file
fs.unlinkSync db_file
Sql.open db_file, {
manual_load: true
manual_save: true
parse_multiple: true
}, (err, _db) ->
throw err if err
db = _db
done()
it "can select", (done) ->
db.exec 'SELECT 1 `id`;', (err, result) ->
assert.deepEqual [{"id":"1"}], result
done()
# PI:NAME:<NAME>END_PI's original demo example
it "can create table, insert, and select, returning last result in multi-query", (done) ->
db.exec '''
CREATE TABLE my_table(key INTEGER, value INTEGER, text VARCHAR(100));
INSERT INTO my_table VALUES(1, 25, 'the first item');
INSERT INTO my_table VALUES(2, 987, 'the second item');
SELECT key, text FROM my_table WHERE value == 987;
''', (err, result) ->
assert.deepEqual [{"key":"2","text":"the second item"}], result
done()
# PI:NAME:<NAME>END_PI's demo example
it "can bulk insert, select where, select aggregation functions, and group by", (done) ->
db.exec '''
/* Demo DB */
CREATE TABLE employees( id integer, name text,
designation text, manager integer,
hired_on date, salary integer,
commission float, dept integer);
INSERT INTO employees VALUES (1,'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI',6,'12-17-1990',18000,NULL,4);
INSERT INTO employees VALUES (2,'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI',9,'02-02-1998',52000,300,3);
INSERT INTO employees VALUES (3,'PI:NAME:<NAME>END_PI','SALES I',2,'01-02-1996',25000,500,3);
INSERT INTO employees VALUES (4,'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI',2,'04-02-1990',27000,NULL,3);
INSERT INTO employees VALUES (5,'PI:NAME:<NAME>END_PI','TECH',6,'06-23-1994',22500,1400,4);
INSERT INTO employees VALUES (6,'PI:NAME:<NAME>END_PI','MANAGER',9,'05-01-1993',54000,NULL,4);
INSERT INTO employees VALUES (7,'PI:NAME:<NAME>END_PI','TECH',6,'09-22-1997',25000,NULL,4);
INSERT INTO employees VALUES (8,'PI:NAME:<NAME>END_PI','ENGINEPI:NAME:<NAME>END_PI',10,'03-30-1997',32000,NULL,2);
INSERT INTO employees VALUES (9,'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI',NULL,'01-01-1990',75000,NULL,4);
INSERT INTO employees VALUES (10,'PI:NAME:<NAME>END_PI','MANAGER',9,'08-09-1994',56000,NULL,2);
INSERT INTO employees VALUES (11,'PI:NAME:<NAME>END_PI','ENGINEER',10,'03-15-1996',34000,NULL,2);
INSERT INTO employees VALUES (12,'PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI',6,'04-16-1998',18000,NULL,4);
INSERT INTO employees VALUES (13,'PI:NAME:<NAME>END_PI','ENGINEER',10,'12-03-2000',30000,NULL,2);
INSERT INTO employees VALUES (14,'PI:NAME:<NAME>END_PI','CPA',9,'10-12-1995',35000,NULL,1);
'''
db.exec "SELECT * FROM employees WHERE designation = 'CEO';", (err, results) ->
assert.deepEqual [{"id":"9","name":"PI:NAME:<NAME>END_PI","designation":"CEO","manager":null,"hired_on":"01-01-1990","salary":"75000","commission":null,"dept":"4"}], results
db.exec "SELECT MAX(salary) AS 'Highest Salary' FROM employees;", (err, results) ->
assert.deepEqual [{"Highest Salary":"75000"}], results
db.exec """
SELECT dept, MAX(salary) As 'Highest Salary in department'
FROM employees
GROUP BY dept;
""", (err, results) ->
assert.deepEqual [{"dept":"1","Highest Salary in department":"35000"},{"dept":"2","Highest Salary in department":"56000"},{"dept":"3","Highest Salary in department":"52000"},{"dept":"4","Highest Salary in department":"75000"}], results
done()
it "can write database to disk", (done) ->
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
""", (err) ->
throw err if err
db.save (err) ->
throw err if err
assert.ok fs.existsSync db_file
done()
it "can read database from disk", (done) ->
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec """
CREATE TABLE cars (
id INTEGER PRIMARY KEY ASC,
color varchar(25)
);
INSERT INTO cars (color) VALUES ('red');
INSERT INTO cars (color) VALUES ('blue');
INSERT INTO cars (color) VALUES ('green');
""", (err, result) ->
throw err if err
Sql.open db_file, {}, (err, db) ->
throw err if err
db.exec 'SELECT * FROM cars;', (err, result) ->
assert.deepEqual [{"id":"1","color":"red"},{"id":"2","color":"blue"},{"id":"3","color":"green"}], result
done()
|
[
{
"context": " message'\r\n time: new Date().getTime()\r\n name: 'bob'\r\n\r\nmessages = [sampleMessage]\r\n\r\nMessageManager ",
"end": 88,
"score": 0.8447889089584351,
"start": 85,
"tag": "NAME",
"value": "bob"
}
] | server/messages.coffee | royaldark/node-chat-demo | 2 | sampleMessage =
message: 'sample message'
time: new Date().getTime()
name: 'bob'
messages = [sampleMessage]
MessageManager =
add: (message) ->
messages.push message
lastMessages: (n) ->
start = Math.max 0, MessageManager.messageCount() - n
messages[start..]
messageCount: ->
messages.length
module.exports = MessageManager
| 37746 | sampleMessage =
message: 'sample message'
time: new Date().getTime()
name: '<NAME>'
messages = [sampleMessage]
MessageManager =
add: (message) ->
messages.push message
lastMessages: (n) ->
start = Math.max 0, MessageManager.messageCount() - n
messages[start..]
messageCount: ->
messages.length
module.exports = MessageManager
| true | sampleMessage =
message: 'sample message'
time: new Date().getTime()
name: 'PI:NAME:<NAME>END_PI'
messages = [sampleMessage]
MessageManager =
add: (message) ->
messages.push message
lastMessages: (n) ->
start = Math.max 0, MessageManager.messageCount() - n
messages[start..]
messageCount: ->
messages.length
module.exports = MessageManager
|
[
{
"context": "\n\t\t\t\tauth:\n\t\t\t\t\tuser: testData.auth1[0]\n\t\t\t\t\tpass: testData.auth1[1]\n\t\t\t\tqs:\n\t\t\t\t\ttestData.test5\n\t\t\t\n\t\t\thrr opts, (",
"end": 4191,
"score": 0.97548508644104,
"start": 4177,
"tag": "PASSWORD",
"value": "testData.auth1"
},
{
"context": "\n\t\t\t\tjson: testData.test4\n\t\t\t\tauth:\n\t\t\t\t\tusername: testData.auth1[0]\n\t\t\t\t\tpassword: testData.auth1[1]\n\t\t\t\tqs:\n\t\t\t\t\t",
"end": 4682,
"score": 0.7541563510894775,
"start": 4668,
"tag": "USERNAME",
"value": "testData.auth1"
},
{
"context": "h:\n\t\t\t\t\tusername: testData.auth1[0]\n\t\t\t\t\tpassword: testData.auth1[1]\n\t\t\t\tqs:\n\t\t\t\t\ttestData.test5\n\t\t\t\n\t\t\thrr opts, (",
"end": 4715,
"score": 0.997967004776001,
"start": 4701,
"tag": "PASSWORD",
"value": "testData.auth1"
}
] | _src/test/main.coffee | mpneuried/hyperrequest | 4 | should = require('should')
hrr = require( "../." )
testData = require( "./data" )
_moduleInst = null
testServer = require( "./server" )
PORT = testServer.address().port
# TODO spin up a express server and test the module
describe "----- hyperrequest TESTS -----", ->
before ( done )->
# _moduleInst = new Module()
#
# testServer = exec 'node test/server.js'
#
# testServer.stderr.on "data", ( data )->
# console.log "TEST-SERVER-ERROR", data
# return
#
# testServer.on "exit", ( data )->
# console.log "\t###\n\nTEST SERVER EXIT.\n\tEventually already running\n\t###\n\n", data
# done()
# return
#
setTimeout( done, 500 )
return
after ( done )->
done()
return
describe 'Main Tests', ->
# Implement tests cases here
it "get", ( done )->
opts =
uri: "http://localhost:#{PORT}/test1"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
# Implement tests cases here
it "get with large response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test2"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( testData.test2 )
done()
return
return
it "get with large json response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test3"
headers:
"Content-type": "application/json"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test3 )
done()
return
return
it "post large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test4"
method: "POST"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "get with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test5/"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "put large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test6"
method: "Put"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "delete with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test7"
method: "delete"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with large url-query and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test8"
method: "Post"
json: testData.test4
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
user: testData.auth1[0]
pass: testData.auth1[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body but different auth syntax", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
username: testData.auth1[0]
password: testData.auth1[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with empty response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test10"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 204 )
should.not.exist resp.body
done()
return
return
it "post with defect header response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test11"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
should.not.exist resp.body
done()
return
return
return
return
| 77467 | should = require('should')
hrr = require( "../." )
testData = require( "./data" )
_moduleInst = null
testServer = require( "./server" )
PORT = testServer.address().port
# TODO spin up a express server and test the module
describe "----- hyperrequest TESTS -----", ->
before ( done )->
# _moduleInst = new Module()
#
# testServer = exec 'node test/server.js'
#
# testServer.stderr.on "data", ( data )->
# console.log "TEST-SERVER-ERROR", data
# return
#
# testServer.on "exit", ( data )->
# console.log "\t###\n\nTEST SERVER EXIT.\n\tEventually already running\n\t###\n\n", data
# done()
# return
#
setTimeout( done, 500 )
return
after ( done )->
done()
return
describe 'Main Tests', ->
# Implement tests cases here
it "get", ( done )->
opts =
uri: "http://localhost:#{PORT}/test1"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
# Implement tests cases here
it "get with large response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test2"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( testData.test2 )
done()
return
return
it "get with large json response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test3"
headers:
"Content-type": "application/json"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test3 )
done()
return
return
it "post large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test4"
method: "POST"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "get with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test5/"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "put large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test6"
method: "Put"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "delete with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test7"
method: "delete"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with large url-query and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test8"
method: "Post"
json: testData.test4
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
user: testData.auth1[0]
pass: <PASSWORD>[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body but different auth syntax", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
username: testData.auth1[0]
password: <PASSWORD>[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with empty response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test10"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 204 )
should.not.exist resp.body
done()
return
return
it "post with defect header response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test11"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
should.not.exist resp.body
done()
return
return
return
return
| true | should = require('should')
hrr = require( "../." )
testData = require( "./data" )
_moduleInst = null
testServer = require( "./server" )
PORT = testServer.address().port
# TODO spin up a express server and test the module
describe "----- hyperrequest TESTS -----", ->
before ( done )->
# _moduleInst = new Module()
#
# testServer = exec 'node test/server.js'
#
# testServer.stderr.on "data", ( data )->
# console.log "TEST-SERVER-ERROR", data
# return
#
# testServer.on "exit", ( data )->
# console.log "\t###\n\nTEST SERVER EXIT.\n\tEventually already running\n\t###\n\n", data
# done()
# return
#
setTimeout( done, 500 )
return
after ( done )->
done()
return
describe 'Main Tests', ->
# Implement tests cases here
it "get", ( done )->
opts =
uri: "http://localhost:#{PORT}/test1"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
# Implement tests cases here
it "get with large response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test2"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( testData.test2 )
done()
return
return
it "get with large json response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test3"
headers:
"Content-type": "application/json"
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test3 )
done()
return
return
it "post large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test4"
method: "POST"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "get with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test5/"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "put large json data", ( done )->
opts =
uri: "http://localhost:#{PORT}/test6"
method: "Put"
headers:
"Content-type": "application/json"
json: testData.test4
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.equal( "OK" )
done()
return
return
it "delete with large url-query", ( done )->
opts =
uri: "http://localhost:#{PORT}/test7"
method: "delete"
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with large url-query and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test8"
method: "Post"
json: testData.test4
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
user: testData.auth1[0]
pass: PI:PASSWORD:<PASSWORD>END_PI[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with auth and body but different auth syntax", ( done )->
opts =
uri: "http://localhost:#{PORT}/test9"
method: "Post"
json: testData.test4
auth:
username: testData.auth1[0]
password: PI:PASSWORD:<PASSWORD>END_PI[1]
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
resp.should.have.property( "body" )
resp.body.should.eql( testData.test5 )
done()
return
return
it "post with empty response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test10"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 204 )
should.not.exist resp.body
done()
return
return
it "post with defect header response", ( done )->
opts =
uri: "http://localhost:#{PORT}/test11"
method: "Post"
json: testData.test6
qs:
testData.test5
hrr opts, ( err, resp )->
throw err if err
resp.should.have.property( "statusCode" )
resp.statusCode.should.eql( 200 )
should.not.exist resp.body
done()
return
return
return
return
|
[
{
"context": "ot has been requested by a founder. Please contact help@sv.co if you wish to cancel this session.'\n trigger:",
"end": 1711,
"score": 0.999923050403595,
"start": 1701,
"tag": "EMAIL",
"value": "help@sv.co"
}
] | app/assets/javascripts/faculty/weekly_slots.coffee | vtamara/pupilfirst | 495 | slotsClickHandler = ->
$('.weekly-slots__connect-slot').click (event) ->
slot = $(event.target)
day = slot.data('day')
return if slot.hasClass('weekly-slots__connect-slot--requested')
# Mark (or unmark) selected class.
slot.toggleClass('weekly-slots__connect-slot--selected')
slotValue = { time: parseFloat(slot.data('time')), requested: false }
if $('#list_of_slots').val().length > 0
currentSlots = JSON.parse($('#list_of_slots').val())
else
currentSlots = {}
if slot.hasClass('weekly-slots__connect-slot--selected')
currentSlots[day] ||= []
currentSlots[day].push(slotValue)
else
index = findSlot(currentSlots[day], slotValue)
if index > -1
currentSlots[day].splice(index, 1);
$('#list_of_slots').val(JSON.stringify(currentSlots))
findSlot = (list, slotValue) ->
i = 0
while i < list.length
if list[i].time == slotValue.time
return i
i++
-1
markPresentSlots = ->
listOfSlots = $('#list_of_slots')
if listOfSlots.length and listOfSlots.val().length > 0
currentSlots = JSON.parse(listOfSlots.val())
for day, slots of currentSlots
for slot in slots
slotClasses = 'weekly-slots__connect-slot--selected'
slotClasses += ' weekly-slots__connect-slot--requested' if slot.requested
time = slot.time
$(".weekly-slots__connect-slot[data-day='" + day + "'][data-time='" + time.toFixed(1) + "']").addClass(slotClasses)
addTooltipsToRequestedSlots()
addTooltipsToRequestedSlots = ->
$('.weekly-slots__connect-slot--requested').popover
title: 'Cannot modify'
content: 'This slot has been requested by a founder. Please contact help@sv.co if you wish to cancel this session.'
trigger: 'hover'
placement: 'bottom'
$(window).on 'load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
$(document).on 'turbolinks:load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
slotsClickHandler()
| 161603 | slotsClickHandler = ->
$('.weekly-slots__connect-slot').click (event) ->
slot = $(event.target)
day = slot.data('day')
return if slot.hasClass('weekly-slots__connect-slot--requested')
# Mark (or unmark) selected class.
slot.toggleClass('weekly-slots__connect-slot--selected')
slotValue = { time: parseFloat(slot.data('time')), requested: false }
if $('#list_of_slots').val().length > 0
currentSlots = JSON.parse($('#list_of_slots').val())
else
currentSlots = {}
if slot.hasClass('weekly-slots__connect-slot--selected')
currentSlots[day] ||= []
currentSlots[day].push(slotValue)
else
index = findSlot(currentSlots[day], slotValue)
if index > -1
currentSlots[day].splice(index, 1);
$('#list_of_slots').val(JSON.stringify(currentSlots))
findSlot = (list, slotValue) ->
i = 0
while i < list.length
if list[i].time == slotValue.time
return i
i++
-1
markPresentSlots = ->
listOfSlots = $('#list_of_slots')
if listOfSlots.length and listOfSlots.val().length > 0
currentSlots = JSON.parse(listOfSlots.val())
for day, slots of currentSlots
for slot in slots
slotClasses = 'weekly-slots__connect-slot--selected'
slotClasses += ' weekly-slots__connect-slot--requested' if slot.requested
time = slot.time
$(".weekly-slots__connect-slot[data-day='" + day + "'][data-time='" + time.toFixed(1) + "']").addClass(slotClasses)
addTooltipsToRequestedSlots()
addTooltipsToRequestedSlots = ->
$('.weekly-slots__connect-slot--requested').popover
title: 'Cannot modify'
content: 'This slot has been requested by a founder. Please contact <EMAIL> if you wish to cancel this session.'
trigger: 'hover'
placement: 'bottom'
$(window).on 'load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
$(document).on 'turbolinks:load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
slotsClickHandler()
| true | slotsClickHandler = ->
$('.weekly-slots__connect-slot').click (event) ->
slot = $(event.target)
day = slot.data('day')
return if slot.hasClass('weekly-slots__connect-slot--requested')
# Mark (or unmark) selected class.
slot.toggleClass('weekly-slots__connect-slot--selected')
slotValue = { time: parseFloat(slot.data('time')), requested: false }
if $('#list_of_slots').val().length > 0
currentSlots = JSON.parse($('#list_of_slots').val())
else
currentSlots = {}
if slot.hasClass('weekly-slots__connect-slot--selected')
currentSlots[day] ||= []
currentSlots[day].push(slotValue)
else
index = findSlot(currentSlots[day], slotValue)
if index > -1
currentSlots[day].splice(index, 1);
$('#list_of_slots').val(JSON.stringify(currentSlots))
findSlot = (list, slotValue) ->
i = 0
while i < list.length
if list[i].time == slotValue.time
return i
i++
-1
markPresentSlots = ->
listOfSlots = $('#list_of_slots')
if listOfSlots.length and listOfSlots.val().length > 0
currentSlots = JSON.parse(listOfSlots.val())
for day, slots of currentSlots
for slot in slots
slotClasses = 'weekly-slots__connect-slot--selected'
slotClasses += ' weekly-slots__connect-slot--requested' if slot.requested
time = slot.time
$(".weekly-slots__connect-slot[data-day='" + day + "'][data-time='" + time.toFixed(1) + "']").addClass(slotClasses)
addTooltipsToRequestedSlots()
addTooltipsToRequestedSlots = ->
$('.weekly-slots__connect-slot--requested').popover
title: 'Cannot modify'
content: 'This slot has been requested by a founder. Please contact PI:EMAIL:<EMAIL>END_PI if you wish to cancel this session.'
trigger: 'hover'
placement: 'bottom'
$(window).on 'load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
$(document).on 'turbolinks:load', ->
if $('#faculty-weekly-slots').length
markPresentSlots()
slotsClickHandler()
|
[
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ",
"end": 404,
"score": 0.8982555270195007,
"start": 400,
"tag": "NAME",
"value": "Test"
},
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ",
"end": 1203,
"score": 0.8609147071838379,
"start": 1199,
"tag": "NAME",
"value": "Test"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 1838,
"score": 0.9993752837181091,
"start": 1831,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"Foo\",\n \"context\" : \"Patient\",\n ",
"end": 2194,
"score": 0.999578595161438,
"start": 2191,
"tag": "NAME",
"value": "Foo"
},
{
"context": " \"expression\" : {\n \"name\" : \"FooP\",\n \"type\" : \"ParameterRef\"\n ",
"end": 2290,
"score": 0.9623849391937256,
"start": 2286,
"tag": "NAME",
"value": "FooP"
}
] | Src/coffeescript/cql-execution/test/elm/parameters/data.coffee | esteban-aliverti/clinical_quality_language | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasureYear",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2012",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo = FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "FooP",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "Foo",
"context" : "Patient",
"expression" : {
"name" : "FooP",
"type" : "ParameterRef"
}
} ]
}
}
}
| 94057 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasureYear",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2012",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo = FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "FooP",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasureYear",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2012",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo = FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "FooP",
"default" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
|
[
{
"context": "xtra\n#\n# Extra Math need in many project\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nclass M\n\n\tconstruc",
"end": 71,
"score": 0.9998535513877869,
"start": 60,
"tag": "NAME",
"value": "David Ronai"
},
{
"context": "ath need in many project\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nclass M\n\n\tconstructor:()->\n\t\tthrow ",
"end": 88,
"score": 0.5851292014122009,
"start": 75,
"tag": "EMAIL",
"value": "akiopolis.com"
},
{
"context": "y project\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nclass M\n\n\tconstructor:()->\n\t\tthrow new Error('",
"end": 99,
"score": 0.9995934963226318,
"start": 91,
"tag": "USERNAME",
"value": "@Makio64"
}
] | src/coffee/makio/math/M.coffee | Makio64/pizzaparty_vj | 1 | #
# MathExtra
#
# Extra Math need in many project
# @author David Ronai / Makiopolis.com / @Makio64
#
class M
constructor:()->
throw new Error('you cant instanciate M')
return
@nextPowerTwo:(value)->
power = 0
while(value > Math.pow(2,power))
power++
return Math.pow(2,power)
@smoothstep:(min, max, value)->
x = Math.max(0, Math.min(1,(value-min)/(max-min)))
return x*x*(3 - 2*x)
@distance:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
return dx*dx+dy*dy
@distanceSqrt:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
if(p.z)
dz = p.z-p2.z
return Math.sqrt(dx*dx+dy*dy+dz*dz)
return Math.sqrt(dx*dx+dy*dy)
@orbitPosition:( phi, theta, radius)->
return new THREE.Vector3(
radius * Math.sin( phi ) * Math.cos( theta ),
radius * Math.cos( phi ),
radius * Math.sin( phi ) * Math.sin( theta )
)
@mix:(value1,value2,percent)->
return value1*(1-percent)+value2*percent
@remap:(value, low1, high1, low2, high2, clamp = true) ->
n = low2 + (high2 - low2) * (value - low1) / (high1 - low1)
if clamp
if low2 < high2
return Math.min(Math.max(n, low2), high2)
else
return Math.max(Math.min(n, low2), high2)
else
return n
@lineIntersect:(startX1, startY1, endX1, endY1, startX2, startY2, endX2, endY2)->
denominator = ((endY2 - startY2) * (endX1 - startX1)) - ((endX2 - startX2) * (endY1 - startY1))
if (denominator == 0)
return null
a = startY1 - startY2
b = startX1 - startX2
numerator1 = ((endX2 - startX2) * a) - ((endY2 - startY2) * b)
numerator2 = ((endX1 - startX1) * a) - ((endY1 - startY1) * b)
a = numerator1 / denominator
b = numerator2 / denominator
x = startX1 + (a * (endX1 - startX1))
y = startY1 + (a * (endY1 - startY1))
return {x:x,y:y}
module.exports = M
| 154979 | #
# MathExtra
#
# Extra Math need in many project
# @author <NAME> / M<EMAIL> / @Makio64
#
class M
constructor:()->
throw new Error('you cant instanciate M')
return
@nextPowerTwo:(value)->
power = 0
while(value > Math.pow(2,power))
power++
return Math.pow(2,power)
@smoothstep:(min, max, value)->
x = Math.max(0, Math.min(1,(value-min)/(max-min)))
return x*x*(3 - 2*x)
@distance:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
return dx*dx+dy*dy
@distanceSqrt:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
if(p.z)
dz = p.z-p2.z
return Math.sqrt(dx*dx+dy*dy+dz*dz)
return Math.sqrt(dx*dx+dy*dy)
@orbitPosition:( phi, theta, radius)->
return new THREE.Vector3(
radius * Math.sin( phi ) * Math.cos( theta ),
radius * Math.cos( phi ),
radius * Math.sin( phi ) * Math.sin( theta )
)
@mix:(value1,value2,percent)->
return value1*(1-percent)+value2*percent
@remap:(value, low1, high1, low2, high2, clamp = true) ->
n = low2 + (high2 - low2) * (value - low1) / (high1 - low1)
if clamp
if low2 < high2
return Math.min(Math.max(n, low2), high2)
else
return Math.max(Math.min(n, low2), high2)
else
return n
@lineIntersect:(startX1, startY1, endX1, endY1, startX2, startY2, endX2, endY2)->
denominator = ((endY2 - startY2) * (endX1 - startX1)) - ((endX2 - startX2) * (endY1 - startY1))
if (denominator == 0)
return null
a = startY1 - startY2
b = startX1 - startX2
numerator1 = ((endX2 - startX2) * a) - ((endY2 - startY2) * b)
numerator2 = ((endX1 - startX1) * a) - ((endY1 - startY1) * b)
a = numerator1 / denominator
b = numerator2 / denominator
x = startX1 + (a * (endX1 - startX1))
y = startY1 + (a * (endY1 - startY1))
return {x:x,y:y}
module.exports = M
| true | #
# MathExtra
#
# Extra Math need in many project
# @author PI:NAME:<NAME>END_PI / MPI:EMAIL:<EMAIL>END_PI / @Makio64
#
class M
constructor:()->
throw new Error('you cant instanciate M')
return
@nextPowerTwo:(value)->
power = 0
while(value > Math.pow(2,power))
power++
return Math.pow(2,power)
@smoothstep:(min, max, value)->
x = Math.max(0, Math.min(1,(value-min)/(max-min)))
return x*x*(3 - 2*x)
@distance:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
return dx*dx+dy*dy
@distanceSqrt:(p,p2)->
dx = p.x-p2.x
dy = p.y-p2.y
if(p.z)
dz = p.z-p2.z
return Math.sqrt(dx*dx+dy*dy+dz*dz)
return Math.sqrt(dx*dx+dy*dy)
@orbitPosition:( phi, theta, radius)->
return new THREE.Vector3(
radius * Math.sin( phi ) * Math.cos( theta ),
radius * Math.cos( phi ),
radius * Math.sin( phi ) * Math.sin( theta )
)
@mix:(value1,value2,percent)->
return value1*(1-percent)+value2*percent
@remap:(value, low1, high1, low2, high2, clamp = true) ->
n = low2 + (high2 - low2) * (value - low1) / (high1 - low1)
if clamp
if low2 < high2
return Math.min(Math.max(n, low2), high2)
else
return Math.max(Math.min(n, low2), high2)
else
return n
@lineIntersect:(startX1, startY1, endX1, endY1, startX2, startY2, endX2, endY2)->
denominator = ((endY2 - startY2) * (endX1 - startX1)) - ((endX2 - startX2) * (endY1 - startY1))
if (denominator == 0)
return null
a = startY1 - startY2
b = startX1 - startX2
numerator1 = ((endX2 - startX2) * a) - ((endY2 - startY2) * b)
numerator2 = ((endX1 - startX1) * a) - ((endY1 - startY1) * b)
a = numerator1 / denominator
b = numerator2 / denominator
x = startX1 + (a * (endX1 - startX1))
y = startY1 + (a * (endY1 - startY1))
return {x:x,y:y}
module.exports = M
|
[
{
"context": "le is part of the Mooch package.\n\nCopyright © 2014 Erin Millard\n\nFor the full copyright and license information, ",
"end": 74,
"score": 0.9997770190238953,
"start": 62,
"tag": "NAME",
"value": "Erin Millard"
}
] | src/Logger.coffee | vanwars/twitter-proxy-cors | 19 | ###
This file is part of the Mooch package.
Copyright © 2014 Erin Millard
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
util = require 'util'
module.exports = class Logger
constructor: (moment = (require 'moment'), output = console) ->
@_moment = moment
@_output = output
log: (category, message, messageArguments...) ->
@_output.log '[%s] [%s] %s', @_moment().format(), category, util.format(message, messageArguments...)
error: (message, messageArguments...) ->
@_output.error '[%s] [error] %s', @_moment().format(), util.format(message, messageArguments...)
| 80693 | ###
This file is part of the Mooch package.
Copyright © 2014 <NAME>
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
util = require 'util'
module.exports = class Logger
constructor: (moment = (require 'moment'), output = console) ->
@_moment = moment
@_output = output
log: (category, message, messageArguments...) ->
@_output.log '[%s] [%s] %s', @_moment().format(), category, util.format(message, messageArguments...)
error: (message, messageArguments...) ->
@_output.error '[%s] [error] %s', @_moment().format(), util.format(message, messageArguments...)
| true | ###
This file is part of the Mooch package.
Copyright © 2014 PI:NAME:<NAME>END_PI
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
util = require 'util'
module.exports = class Logger
constructor: (moment = (require 'moment'), output = console) ->
@_moment = moment
@_output = output
log: (category, message, messageArguments...) ->
@_output.log '[%s] [%s] %s', @_moment().format(), category, util.format(message, messageArguments...)
error: (message, messageArguments...) ->
@_output.error '[%s] [error] %s', @_moment().format(), util.format(message, messageArguments...)
|
[
{
"context": "ames/#{@appId}/users.json\",\n {'access_token': accessToken, 'api_key': @udid},\n (jqXHR) =>\n resp",
"end": 2547,
"score": 0.37612107396125793,
"start": 2536,
"tag": "KEY",
"value": "accessToken"
},
{
"context": "/requests/#{requestId}/clicks\", {clicking_user_id: @udid, sig: \"s\"},\n (jqXHR) =>\n response = $",
"end": 8043,
"score": 0.9917570948600769,
"start": 8038,
"tag": "USERNAME",
"value": "@udid"
},
{
"context": ", callback) ->\n url_params = {\n 'api_key': @udid,\n 'game_id': @appId,\n 'request_date': M",
"end": 10230,
"score": 0.9419463276863098,
"start": 10225,
"tag": "KEY",
"value": "@udid"
}
] | src/Carrot.coffee | GoCarrot/carrot-js | 0 | # Carrot -- Copyright (C) 2012 Carrot 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.
# Requires from http://code.google.com/p/crypto-js/
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js
class Carrot
@Status =
NotAuthorized: 'Carrot user has not authorized application.'
NotCreated: 'Carrot user does not exist.'
Unknown: 'Carrot user status unknown.'
ReadOnly: 'Carrot user has not granted \'publish_actions\' permission.'
Authorized: 'Carrot user authorized.'
Ok: 'Operation successful.'
Error: 'Operation unsuccessful.'
@trackLoad: (appId, signedRequest) ->
img = new Image()
img.src = 'https://gocarrot.com/tracking?app_id=' + appId + '&signed_request=' + signedRequest
constructor: (appId, udid, appSecret, hostname) ->
try
@request = require('request')
catch err
@request = null
@appId = appId
@udid = udid
@appSecret = appSecret
@status = Carrot.Status.Unknown
@hostname = hostname or "gocarrot.com"
@scheme = ("http" if hostname?.match(/^localhost/)) or "https"
ajaxGet: (url, callback) ->
if @request
@request(url, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
ajaxPost: (url, data, callback) ->
if @request
@request.post(url, {'form':data}, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
type: 'POST'
data: data
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
validateUser: (accessToken, callback) ->
@ajaxPost("#{@scheme}://#{@hostname}/games/#{@appId}/users.json",
{'access_token': accessToken, 'api_key': @udid},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText);
switch jqXHR.status
when 201
@status = Carrot.Status.Authorized
@userId = response.facebook_id
when 401
@status = Carrot.Status.ReadOnly
@userId = response.facebook_id
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
callback(@status) if callback
)
callbackHandler: (callback) ->
return (jqXHR) =>
ret = Carrot.Status.Error
switch jqXHR.status
when 200
ret = Carrot.Status.Ok
when 201
ret = Carrot.Status.Ok
when 401
@status = Carrot.Status.ReadOnly
when 404
# No change to status, resource not found
@status = @status
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
if callback
return callback(ret)
else
return ret
postAchievement: (achievementId, callback) ->
@postSignedRequest("/me/achievements.json",
{'achievement_id': achievementId}, @callbackHandler(callback))
postHighScore: (score, callback) ->
@postSignedRequest("/me/scores.json",
{'value': score}, @callbackHandler(callback))
postAction: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/actions.json", params, @callbackHandler(callback))
canMakeFeedPost: (objectInstanceId, callback) ->
params = {
'object_instance_id': objectInstanceId
}
@postSignedRequest("/me/can_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
callback(carrotResponse.code == 200) if callback
)
popupFeedPost: (objectInstanceId, objectProperties, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if postMethod?
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/feed_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
if carrotResponse.code == 200
postMethod(carrotResponse.fb_data,
(fbResponse) =>
if fbResponse and fbResponse.post_id
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/feed_dialog_post", {platform_id: carrotResponse.post_id})
callback(carrotResponse, fbResponse) if callback
)
else
callback(carrotResponse) if callback
)
reportNotificationClick: (notifId, callback) ->
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/notification_click", {user_id: @udid, platform_id: notifId})
reportFeedClick: (postId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/#{postId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
# Available opts: object_type, object_id, object_properties, filters, suggestions, exclude_ids, max_recipients, data
sendRequest: (requestId, opts, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if !opts
opts = {}
if postMethod?
params = {
'request_id' : requestId
'object_properties' : JSON.stringify(opts['object_properties'] || {})
}
if opts['object_type'] && opts['object_id']
params['object_type'] = opts['object_type']
params['object_instance_id'] = opts['object_id']
@postSignedRequest("/me/request.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
fb_data = $.extend({}, opts, carrotResponse.fb_data)
postMethod(fb_data,
(fbResponse) =>
if fbResponse && fbResponse.request
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{carrotResponse.request_id}/ids", {platform_id: fbResponse.request})
if fbResponse && fbResponse.to
for receivingUser in fbResponse.to
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/request_send", {platform_id: carrotResponse.request_id, posting_user_id: @udid, user_id: receivingUser})
callback(carrotResponse, fbResponse) if callback
)
)
acceptRequest: (requestId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{requestId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
getTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@getSignedRequest("/me/template_post.json", params, (jqXHR) -> callback($.parseJSON(jqXHR.responseText)) if callback)
showTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
@getTweet actionId, objectInstanceId, actionProperties, objectProperties, (reply) ->
callback(reply) if callback
if reply
width = 512
height = 258
leftPosition = (window.screen.width / 2) - ((width / 2))
topPosition = (window.screen.height / 2) - ((height / 2))
url = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(reply.tweet.contents) + "&url=" + encodeURIComponent(reply.tweet.short_url)
window.open(url, "Twitter", "status=no,height=" + height + ",width=" + width + ",resizable=no,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=yes,directories=no,dialog=yes")
getSignedRequest: (endpoint, query_params, callback) ->
query_params['_method'] = "GET"
@doSignedRequest(endpoint, query_params, callback)
postSignedRequest: (endpoint, query_params, callback) ->
@doSignedRequest(endpoint, query_params, callback)
doSignedRequest: (endpoint, query_params, callback) ->
url_params = {
'api_key': @udid,
'game_id': @appId,
'request_date': Math.round((new Date()).getTime() / 1000),
'request_id': @GUID()
}
for k, v of query_params
url_params[k] = v
keys = (k for k, v of url_params)
keys.sort()
url_string = ""
for k in keys
url_string = url_string + "#{k}=#{url_params[k]}&"
url_string = url_string.slice(0, url_string.length - 1);
sign_string = "POST\n#{@hostname.split(':')[0]}\n#{endpoint}\n#{url_string}"
digest = CryptoJS.HmacSHA256(sign_string, @appSecret).toString(CryptoJS.enc.Base64)
url_params.sig = digest
@ajaxPost("#{@scheme}://#{@hostname}#{endpoint}", url_params, callback)
GUID: ->
S4 = () => return Math.floor(Math.random() * 0x10000).toString(16)
return (
S4() + S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + S4() + S4()
);
(exports ? this).Carrot = Carrot
| 224278 | # Carrot -- Copyright (C) 2012 Carrot 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.
# Requires from http://code.google.com/p/crypto-js/
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js
class Carrot
@Status =
NotAuthorized: 'Carrot user has not authorized application.'
NotCreated: 'Carrot user does not exist.'
Unknown: 'Carrot user status unknown.'
ReadOnly: 'Carrot user has not granted \'publish_actions\' permission.'
Authorized: 'Carrot user authorized.'
Ok: 'Operation successful.'
Error: 'Operation unsuccessful.'
@trackLoad: (appId, signedRequest) ->
img = new Image()
img.src = 'https://gocarrot.com/tracking?app_id=' + appId + '&signed_request=' + signedRequest
constructor: (appId, udid, appSecret, hostname) ->
try
@request = require('request')
catch err
@request = null
@appId = appId
@udid = udid
@appSecret = appSecret
@status = Carrot.Status.Unknown
@hostname = hostname or "gocarrot.com"
@scheme = ("http" if hostname?.match(/^localhost/)) or "https"
ajaxGet: (url, callback) ->
if @request
@request(url, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
ajaxPost: (url, data, callback) ->
if @request
@request.post(url, {'form':data}, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
type: 'POST'
data: data
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
validateUser: (accessToken, callback) ->
@ajaxPost("#{@scheme}://#{@hostname}/games/#{@appId}/users.json",
{'access_token': <KEY>, 'api_key': @udid},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText);
switch jqXHR.status
when 201
@status = Carrot.Status.Authorized
@userId = response.facebook_id
when 401
@status = Carrot.Status.ReadOnly
@userId = response.facebook_id
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
callback(@status) if callback
)
callbackHandler: (callback) ->
return (jqXHR) =>
ret = Carrot.Status.Error
switch jqXHR.status
when 200
ret = Carrot.Status.Ok
when 201
ret = Carrot.Status.Ok
when 401
@status = Carrot.Status.ReadOnly
when 404
# No change to status, resource not found
@status = @status
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
if callback
return callback(ret)
else
return ret
postAchievement: (achievementId, callback) ->
@postSignedRequest("/me/achievements.json",
{'achievement_id': achievementId}, @callbackHandler(callback))
postHighScore: (score, callback) ->
@postSignedRequest("/me/scores.json",
{'value': score}, @callbackHandler(callback))
postAction: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/actions.json", params, @callbackHandler(callback))
canMakeFeedPost: (objectInstanceId, callback) ->
params = {
'object_instance_id': objectInstanceId
}
@postSignedRequest("/me/can_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
callback(carrotResponse.code == 200) if callback
)
popupFeedPost: (objectInstanceId, objectProperties, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if postMethod?
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/feed_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
if carrotResponse.code == 200
postMethod(carrotResponse.fb_data,
(fbResponse) =>
if fbResponse and fbResponse.post_id
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/feed_dialog_post", {platform_id: carrotResponse.post_id})
callback(carrotResponse, fbResponse) if callback
)
else
callback(carrotResponse) if callback
)
reportNotificationClick: (notifId, callback) ->
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/notification_click", {user_id: @udid, platform_id: notifId})
reportFeedClick: (postId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/#{postId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
# Available opts: object_type, object_id, object_properties, filters, suggestions, exclude_ids, max_recipients, data
sendRequest: (requestId, opts, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if !opts
opts = {}
if postMethod?
params = {
'request_id' : requestId
'object_properties' : JSON.stringify(opts['object_properties'] || {})
}
if opts['object_type'] && opts['object_id']
params['object_type'] = opts['object_type']
params['object_instance_id'] = opts['object_id']
@postSignedRequest("/me/request.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
fb_data = $.extend({}, opts, carrotResponse.fb_data)
postMethod(fb_data,
(fbResponse) =>
if fbResponse && fbResponse.request
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{carrotResponse.request_id}/ids", {platform_id: fbResponse.request})
if fbResponse && fbResponse.to
for receivingUser in fbResponse.to
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/request_send", {platform_id: carrotResponse.request_id, posting_user_id: @udid, user_id: receivingUser})
callback(carrotResponse, fbResponse) if callback
)
)
acceptRequest: (requestId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{requestId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
getTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@getSignedRequest("/me/template_post.json", params, (jqXHR) -> callback($.parseJSON(jqXHR.responseText)) if callback)
showTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
@getTweet actionId, objectInstanceId, actionProperties, objectProperties, (reply) ->
callback(reply) if callback
if reply
width = 512
height = 258
leftPosition = (window.screen.width / 2) - ((width / 2))
topPosition = (window.screen.height / 2) - ((height / 2))
url = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(reply.tweet.contents) + "&url=" + encodeURIComponent(reply.tweet.short_url)
window.open(url, "Twitter", "status=no,height=" + height + ",width=" + width + ",resizable=no,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=yes,directories=no,dialog=yes")
getSignedRequest: (endpoint, query_params, callback) ->
query_params['_method'] = "GET"
@doSignedRequest(endpoint, query_params, callback)
postSignedRequest: (endpoint, query_params, callback) ->
@doSignedRequest(endpoint, query_params, callback)
doSignedRequest: (endpoint, query_params, callback) ->
url_params = {
'api_key': <KEY>,
'game_id': @appId,
'request_date': Math.round((new Date()).getTime() / 1000),
'request_id': @GUID()
}
for k, v of query_params
url_params[k] = v
keys = (k for k, v of url_params)
keys.sort()
url_string = ""
for k in keys
url_string = url_string + "#{k}=#{url_params[k]}&"
url_string = url_string.slice(0, url_string.length - 1);
sign_string = "POST\n#{@hostname.split(':')[0]}\n#{endpoint}\n#{url_string}"
digest = CryptoJS.HmacSHA256(sign_string, @appSecret).toString(CryptoJS.enc.Base64)
url_params.sig = digest
@ajaxPost("#{@scheme}://#{@hostname}#{endpoint}", url_params, callback)
GUID: ->
S4 = () => return Math.floor(Math.random() * 0x10000).toString(16)
return (
S4() + S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + S4() + S4()
);
(exports ? this).Carrot = Carrot
| true | # Carrot -- Copyright (C) 2012 Carrot 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.
# Requires from http://code.google.com/p/crypto-js/
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js
# http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js
class Carrot
@Status =
NotAuthorized: 'Carrot user has not authorized application.'
NotCreated: 'Carrot user does not exist.'
Unknown: 'Carrot user status unknown.'
ReadOnly: 'Carrot user has not granted \'publish_actions\' permission.'
Authorized: 'Carrot user authorized.'
Ok: 'Operation successful.'
Error: 'Operation unsuccessful.'
@trackLoad: (appId, signedRequest) ->
img = new Image()
img.src = 'https://gocarrot.com/tracking?app_id=' + appId + '&signed_request=' + signedRequest
constructor: (appId, udid, appSecret, hostname) ->
try
@request = require('request')
catch err
@request = null
@appId = appId
@udid = udid
@appSecret = appSecret
@status = Carrot.Status.Unknown
@hostname = hostname or "gocarrot.com"
@scheme = ("http" if hostname?.match(/^localhost/)) or "https"
ajaxGet: (url, callback) ->
if @request
@request(url, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
ajaxPost: (url, data, callback) ->
if @request
@request.post(url, {'form':data}, (error, response, body) =>
callback(response.statusCode) if callback
response.end
)
else
$.ajax
async: true
type: 'POST'
data: data
url: url
complete: (jqXHR, textStatus) =>
callback(jqXHR) if callback
true
validateUser: (accessToken, callback) ->
@ajaxPost("#{@scheme}://#{@hostname}/games/#{@appId}/users.json",
{'access_token': PI:KEY:<KEY>END_PI, 'api_key': @udid},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText);
switch jqXHR.status
when 201
@status = Carrot.Status.Authorized
@userId = response.facebook_id
when 401
@status = Carrot.Status.ReadOnly
@userId = response.facebook_id
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
callback(@status) if callback
)
callbackHandler: (callback) ->
return (jqXHR) =>
ret = Carrot.Status.Error
switch jqXHR.status
when 200
ret = Carrot.Status.Ok
when 201
ret = Carrot.Status.Ok
when 401
@status = Carrot.Status.ReadOnly
when 404
# No change to status, resource not found
@status = @status
when 405
@status = Carrot.Status.NotAuthorized
else
@status = Carrot.Status.Unknown
if callback
return callback(ret)
else
return ret
postAchievement: (achievementId, callback) ->
@postSignedRequest("/me/achievements.json",
{'achievement_id': achievementId}, @callbackHandler(callback))
postHighScore: (score, callback) ->
@postSignedRequest("/me/scores.json",
{'value': score}, @callbackHandler(callback))
postAction: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/actions.json", params, @callbackHandler(callback))
canMakeFeedPost: (objectInstanceId, callback) ->
params = {
'object_instance_id': objectInstanceId
}
@postSignedRequest("/me/can_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
callback(carrotResponse.code == 200) if callback
)
popupFeedPost: (objectInstanceId, objectProperties, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if postMethod?
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@postSignedRequest("/me/feed_post.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
if carrotResponse.code == 200
postMethod(carrotResponse.fb_data,
(fbResponse) =>
if fbResponse and fbResponse.post_id
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/feed_dialog_post", {platform_id: carrotResponse.post_id})
callback(carrotResponse, fbResponse) if callback
)
else
callback(carrotResponse) if callback
)
reportNotificationClick: (notifId, callback) ->
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/notification_click", {user_id: @udid, platform_id: notifId})
reportFeedClick: (postId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/#{postId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
# Available opts: object_type, object_id, object_properties, filters, suggestions, exclude_ids, max_recipients, data
sendRequest: (requestId, opts, callback, postMethod) ->
if !postMethod? && FB?
postMethod = FB.ui
if !opts
opts = {}
if postMethod?
params = {
'request_id' : requestId
'object_properties' : JSON.stringify(opts['object_properties'] || {})
}
if opts['object_type'] && opts['object_id']
params['object_type'] = opts['object_type']
params['object_instance_id'] = opts['object_id']
@postSignedRequest("/me/request.json", params, (jqXHR) =>
carrotResponse = $.parseJSON(jqXHR.responseText)
fb_data = $.extend({}, opts, carrotResponse.fb_data)
postMethod(fb_data,
(fbResponse) =>
if fbResponse && fbResponse.request
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{carrotResponse.request_id}/ids", {platform_id: fbResponse.request})
if fbResponse && fbResponse.to
for receivingUser in fbResponse.to
@ajaxPost("#{@scheme}://parsnip.gocarrot.com/request_send", {platform_id: carrotResponse.request_id, posting_user_id: @udid, user_id: receivingUser})
callback(carrotResponse, fbResponse) if callback
)
)
acceptRequest: (requestId, callback) ->
@ajaxPost("#{@scheme}://posts.gocarrot.com/requests/#{requestId}/clicks", {clicking_user_id: @udid, sig: "s"},
(jqXHR) =>
response = $.parseJSON(jqXHR.responseText).response;
if response.cascade && response.cascade.method == "sendRequest"
@sendRequest(response.cascade.arguments.request_id, response.cascade.arguments.opts)
callback(response) if callback
)
getTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
actionProperties = if typeof actionProperties is "string" then actionProperties else JSON.stringify(actionProperties || {})
objectProperties = if typeof objectProperties is "string" then objectProperties else JSON.stringify(objectProperties || {})
params = {
'action_id': actionId,
'action_properties': actionProperties,
'object_properties': objectProperties
}
params['object_instance_id'] = objectInstanceId if objectInstanceId
@getSignedRequest("/me/template_post.json", params, (jqXHR) -> callback($.parseJSON(jqXHR.responseText)) if callback)
showTweet: (actionId, objectInstanceId, actionProperties, objectProperties, callback) ->
@getTweet actionId, objectInstanceId, actionProperties, objectProperties, (reply) ->
callback(reply) if callback
if reply
width = 512
height = 258
leftPosition = (window.screen.width / 2) - ((width / 2))
topPosition = (window.screen.height / 2) - ((height / 2))
url = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(reply.tweet.contents) + "&url=" + encodeURIComponent(reply.tweet.short_url)
window.open(url, "Twitter", "status=no,height=" + height + ",width=" + width + ",resizable=no,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=yes,directories=no,dialog=yes")
getSignedRequest: (endpoint, query_params, callback) ->
query_params['_method'] = "GET"
@doSignedRequest(endpoint, query_params, callback)
postSignedRequest: (endpoint, query_params, callback) ->
@doSignedRequest(endpoint, query_params, callback)
doSignedRequest: (endpoint, query_params, callback) ->
url_params = {
'api_key': PI:KEY:<KEY>END_PI,
'game_id': @appId,
'request_date': Math.round((new Date()).getTime() / 1000),
'request_id': @GUID()
}
for k, v of query_params
url_params[k] = v
keys = (k for k, v of url_params)
keys.sort()
url_string = ""
for k in keys
url_string = url_string + "#{k}=#{url_params[k]}&"
url_string = url_string.slice(0, url_string.length - 1);
sign_string = "POST\n#{@hostname.split(':')[0]}\n#{endpoint}\n#{url_string}"
digest = CryptoJS.HmacSHA256(sign_string, @appSecret).toString(CryptoJS.enc.Base64)
url_params.sig = digest
@ajaxPost("#{@scheme}://#{@hostname}#{endpoint}", url_params, callback)
GUID: ->
S4 = () => return Math.floor(Math.random() * 0x10000).toString(16)
return (
S4() + S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + S4() + S4()
);
(exports ? this).Carrot = Carrot
|
[
{
"context": " EC('secp256k1');\n\nkeyA = ec.genKeyPair();\nstr = \"Password456\"\nmsg = crypto.createHash(\"sha256\").update(str).di",
"end": 136,
"score": 0.9670528769493103,
"start": 125,
"tag": "PASSWORD",
"value": "Password456"
}
] | perfomance_simulations/idbp/idbp_store.coffee | lucy7li/compromised-credential-checking | 6 | crypto = require 'crypto';
ecc = require 'elliptic';
EC = ecc.ec;
ec = new EC('secp256k1');
keyA = ec.genKeyPair();
str = "Password456"
msg = crypto.createHash("sha256").update(str).digest('hex');
key = ec.keyFromPrivate(msg,'hex');
console.log(keyA.getPublic().mul(key.getPrivate()).encode('hex'))
#console.log(key.derive(keyA.getPublic()))
pk = key.derive(keyA.getPublic()).toString(16)
key1 = ec.keyFromPrivate(pk,'hex');
console.log(key1.getPublic())
key2 = ec.keyFromPublic(key1.getPublic().encode('hex'),'hex');
console.log(key2.getPublic()) | 216029 | crypto = require 'crypto';
ecc = require 'elliptic';
EC = ecc.ec;
ec = new EC('secp256k1');
keyA = ec.genKeyPair();
str = "<PASSWORD>"
msg = crypto.createHash("sha256").update(str).digest('hex');
key = ec.keyFromPrivate(msg,'hex');
console.log(keyA.getPublic().mul(key.getPrivate()).encode('hex'))
#console.log(key.derive(keyA.getPublic()))
pk = key.derive(keyA.getPublic()).toString(16)
key1 = ec.keyFromPrivate(pk,'hex');
console.log(key1.getPublic())
key2 = ec.keyFromPublic(key1.getPublic().encode('hex'),'hex');
console.log(key2.getPublic()) | true | crypto = require 'crypto';
ecc = require 'elliptic';
EC = ecc.ec;
ec = new EC('secp256k1');
keyA = ec.genKeyPair();
str = "PI:PASSWORD:<PASSWORD>END_PI"
msg = crypto.createHash("sha256").update(str).digest('hex');
key = ec.keyFromPrivate(msg,'hex');
console.log(keyA.getPublic().mul(key.getPrivate()).encode('hex'))
#console.log(key.derive(keyA.getPublic()))
pk = key.derive(keyA.getPublic()).toString(16)
key1 = ec.keyFromPrivate(pk,'hex');
console.log(key1.getPublic())
key2 = ec.keyFromPublic(key1.getPublic().encode('hex'),'hex');
console.log(key2.getPublic()) |
[
{
"context": " (SES Example)- No Javascript (Woo!)\n\n Created by Daniel Rowe\n http://danielrowe.me\n\n=========================",
"end": 142,
"score": 0.9998564720153809,
"start": 131,
"tag": "NAME",
"value": "Daniel Rowe"
},
{
"context": " port\" + config.NoJSPort)\nconsole.info(\"Created by Daniel Rowe (http://danielrowe.me)\")",
"end": 3387,
"score": 0.9998810887336731,
"start": 3376,
"tag": "NAME",
"value": "Daniel Rowe"
}
] | routes/js/contact_nojs.coffee | moelaknahour23/A.J.A.M.K.A | 0 | ###
===========================================================
Contact Form (SES Example)- No Javascript (Woo!)
Created by Daniel Rowe
http://danielrowe.me
============================================================
###
connect = require("connect")
http = require("http")
nodemailer = require("nodemailer")
ses = require("nodemailer-ses-transport")
config = require("./config") # Load all the settings.
isFieldValid = (field) -> field? and field.length > 0
validEmail = (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
app = connect()
.use(connect.bodyParser()) #So we can get the post data.
.use((req,res) ->
# pickup the body vars first to ease reading
{name, email, tel, subject, question} = req.body
# valid should be always defined, even if it's only true/false
# Was all the data submitted?
valid = isFieldValid(name) and isFieldValid(email) and isFieldValid(question)
if(valid)
transport = nodemailer.createTransport(ses({ #Set AWS Keys for SES
AWSAccessKeyID: config.AWSAccessKeyID
AWSSecretKey: config.AWSSecretKey
}))
#Clean up and format the question
question = (question.replace(/<(?:.|\n)*?>/gm, '') + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
#Set the date (for send time info)
date = new Date().toJSON().toString()
#Now set a easier way to recall the user IP
ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
#Validate email address
validEmail (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
if not validEmail(email)
res.redirect(config.siteURL + '/#error')
else
#Email content
message = {
from: name+' <' + config.SESFrom + '>'
replyTo: name+' <' + email + '>'
to: 'Contact Form <' + config.emailTo + '>'
subject: 'Online Contact Form: ' + subject
html: "<b>Site enquiry:</b>
<br><br>
<i>Sender:</i> " + name + "<br>
<i>Email:</i> " + email + "<br>
<i>Telephone:</i> " + tel + "<br>
<i>Subject:</i> " + subject + "<br><br>
" + question + "
<br><br><br>
-------------------------------------------- <br>
Send Time: <i>" + date + "</i><br>
User IP: <i>" + ip + "</i>
"
}
transport.sendMail(message, (error) ->
if error
console.log('Error occured') #Error sending message
console.log(error.message)
res.redirect(config.siteURL + '#error')
else
console.log('Message sent successfully!') #Wooo it sent! Return a json sucess
res.redirect(config.siteURL + '#success')
)
else
#sling your hook, and give me some info!
res.redirect(config.siteURL + '#error')
)
http.createServer(app).listen(config.NoJSPort) #Lastly lets fire up the server!
console.log("Contact-NoJS server running on port" + config.NoJSPort)
console.info("Created by Daniel Rowe (http://danielrowe.me)") | 15919 | ###
===========================================================
Contact Form (SES Example)- No Javascript (Woo!)
Created by <NAME>
http://danielrowe.me
============================================================
###
connect = require("connect")
http = require("http")
nodemailer = require("nodemailer")
ses = require("nodemailer-ses-transport")
config = require("./config") # Load all the settings.
isFieldValid = (field) -> field? and field.length > 0
validEmail = (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
app = connect()
.use(connect.bodyParser()) #So we can get the post data.
.use((req,res) ->
# pickup the body vars first to ease reading
{name, email, tel, subject, question} = req.body
# valid should be always defined, even if it's only true/false
# Was all the data submitted?
valid = isFieldValid(name) and isFieldValid(email) and isFieldValid(question)
if(valid)
transport = nodemailer.createTransport(ses({ #Set AWS Keys for SES
AWSAccessKeyID: config.AWSAccessKeyID
AWSSecretKey: config.AWSSecretKey
}))
#Clean up and format the question
question = (question.replace(/<(?:.|\n)*?>/gm, '') + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
#Set the date (for send time info)
date = new Date().toJSON().toString()
#Now set a easier way to recall the user IP
ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
#Validate email address
validEmail (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
if not validEmail(email)
res.redirect(config.siteURL + '/#error')
else
#Email content
message = {
from: name+' <' + config.SESFrom + '>'
replyTo: name+' <' + email + '>'
to: 'Contact Form <' + config.emailTo + '>'
subject: 'Online Contact Form: ' + subject
html: "<b>Site enquiry:</b>
<br><br>
<i>Sender:</i> " + name + "<br>
<i>Email:</i> " + email + "<br>
<i>Telephone:</i> " + tel + "<br>
<i>Subject:</i> " + subject + "<br><br>
" + question + "
<br><br><br>
-------------------------------------------- <br>
Send Time: <i>" + date + "</i><br>
User IP: <i>" + ip + "</i>
"
}
transport.sendMail(message, (error) ->
if error
console.log('Error occured') #Error sending message
console.log(error.message)
res.redirect(config.siteURL + '#error')
else
console.log('Message sent successfully!') #Wooo it sent! Return a json sucess
res.redirect(config.siteURL + '#success')
)
else
#sling your hook, and give me some info!
res.redirect(config.siteURL + '#error')
)
http.createServer(app).listen(config.NoJSPort) #Lastly lets fire up the server!
console.log("Contact-NoJS server running on port" + config.NoJSPort)
console.info("Created by <NAME> (http://danielrowe.me)") | true | ###
===========================================================
Contact Form (SES Example)- No Javascript (Woo!)
Created by PI:NAME:<NAME>END_PI
http://danielrowe.me
============================================================
###
connect = require("connect")
http = require("http")
nodemailer = require("nodemailer")
ses = require("nodemailer-ses-transport")
config = require("./config") # Load all the settings.
isFieldValid = (field) -> field? and field.length > 0
validEmail = (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
app = connect()
.use(connect.bodyParser()) #So we can get the post data.
.use((req,res) ->
# pickup the body vars first to ease reading
{name, email, tel, subject, question} = req.body
# valid should be always defined, even if it's only true/false
# Was all the data submitted?
valid = isFieldValid(name) and isFieldValid(email) and isFieldValid(question)
if(valid)
transport = nodemailer.createTransport(ses({ #Set AWS Keys for SES
AWSAccessKeyID: config.AWSAccessKeyID
AWSSecretKey: config.AWSSecretKey
}))
#Clean up and format the question
question = (question.replace(/<(?:.|\n)*?>/gm, '') + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
#Set the date (for send time info)
date = new Date().toJSON().toString()
#Now set a easier way to recall the user IP
ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
#Validate email address
validEmail (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
if not validEmail(email)
res.redirect(config.siteURL + '/#error')
else
#Email content
message = {
from: name+' <' + config.SESFrom + '>'
replyTo: name+' <' + email + '>'
to: 'Contact Form <' + config.emailTo + '>'
subject: 'Online Contact Form: ' + subject
html: "<b>Site enquiry:</b>
<br><br>
<i>Sender:</i> " + name + "<br>
<i>Email:</i> " + email + "<br>
<i>Telephone:</i> " + tel + "<br>
<i>Subject:</i> " + subject + "<br><br>
" + question + "
<br><br><br>
-------------------------------------------- <br>
Send Time: <i>" + date + "</i><br>
User IP: <i>" + ip + "</i>
"
}
transport.sendMail(message, (error) ->
if error
console.log('Error occured') #Error sending message
console.log(error.message)
res.redirect(config.siteURL + '#error')
else
console.log('Message sent successfully!') #Wooo it sent! Return a json sucess
res.redirect(config.siteURL + '#success')
)
else
#sling your hook, and give me some info!
res.redirect(config.siteURL + '#error')
)
http.createServer(app).listen(config.NoJSPort) #Lastly lets fire up the server!
console.log("Contact-NoJS server running on port" + config.NoJSPort)
console.info("Created by PI:NAME:<NAME>END_PI (http://danielrowe.me)") |
[
{
"context": "submit\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope ",
"end": 1825,
"score": 0.8812359571456909,
"start": 1821,
"tag": "NAME",
"value": "test"
},
{
"context": "ccess\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope ",
"end": 2309,
"score": 0.9314554929733276,
"start": 2305,
"tag": "NAME",
"value": "test"
},
{
"context": "l error\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope =",
"end": 2796,
"score": 0.8692284226417542,
"start": 2792,
"tag": "NAME",
"value": "test"
},
{
"context": "always\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope ",
"end": 3324,
"score": 0.9541341066360474,
"start": 3320,
"tag": "NAME",
"value": "test"
},
{
"context": "ress\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope ",
"end": 3810,
"score": 0.87835693359375,
"start": 3806,
"tag": "NAME",
"value": "test"
},
{
"context": "rray\", ->\n param = {files: [{name: 'test'}]}\n called = false\n scope ",
"end": 4512,
"score": 0.9452369213104248,
"start": 4508,
"tag": "NAME",
"value": "test"
}
] | test/unit/file_upload.spec.coffee | neosavvyinc/MacGyver | 1 | describe "Mac Fileupload", ->
beforeEach module("Mac")
describe "Options updates", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should initialize fileupload plugin", ->
element = $compile("<input type='file' mac-upload />") $rootScope
expect(element.data("blueimp-fileupload")).not.toBe null
it "should update url", ->
scope = $rootScope.$new()
scope.url = "/test_upload"
element = $compile("<input type='file' mac-upload mac-upload-route='url' />") scope
scope.url = "/test"
scope.$digest()
expect(element.fileupload("option", "url")).toBe "/test"
it "should update form data", ->
scope = $rootScope.$new()
scope.formData = {randomText: "helloWorld"}
element = $compile("<input type='file' mac-upload mac-upload-form-data='formData' />") scope
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "helloWorld"
scope.formData = {randomText: "foobar"}
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "foobar"
it "should update default options", ->
scope = $rootScope.$new()
scope.options = {singleFileUploads: false}
element = $compile("<input type='file' mac-upload mac-upload-options='options' />") scope
scope.$digest()
expect(element.fileupload("option", "singleFileUploads")).toBe false
describe "Callbacks", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should call submit", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.submit = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Submit function should be called", "750"
runs ->
expect(called).toBe true
it "should call success", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.success = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-success='success()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Success function should be called", "750"
runs ->
expect(called).toBe true
it "should call error", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.error = -> called = true
scope.route = "404"
element = $compile("<input type='file' mac-upload mac-upload-error='error()' mac-upload-route='route' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Error function should be called", "750"
runs ->
expect(called).toBe true
it "should call always", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.always = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-always='always()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Always function should be called", "750"
runs ->
expect(called).toBe true
it "should call progress", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.progress = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-progress='progress()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Progress function should be called", "750"
runs ->
expect(called).toBe true
describe "Previews", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should push one file to preview array", ->
param = {files: [{name: 'test'}]}
called = false
scope = $rootScope.$new()
scope.previews = []
scope.submit = ->
called = true
element = $compile("<input type='file' mac-upload mac-upload-previews='previews' mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Files should be added to preview array", "750"
runs ->
scope.$digest()
expect(scope.previews.length).toBeGreaterThan 0
describe "dropZone", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should add droppable class on dragover", ->
scope = $rootScope.$new()
element = $compile("<div class='wrapper'><input type='file' mac-upload mac-upload-drop-zone='.wrapper' /></div>") scope
scope.$digest()
event = $.Event("dragover")
event.target = $("input", element)[0]
event.originalEvent = dataTransfer: {files: [{}]}
$(document).trigger event
expect(element.hasClass("droppable")).toBe true
| 157357 | describe "Mac Fileupload", ->
beforeEach module("Mac")
describe "Options updates", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should initialize fileupload plugin", ->
element = $compile("<input type='file' mac-upload />") $rootScope
expect(element.data("blueimp-fileupload")).not.toBe null
it "should update url", ->
scope = $rootScope.$new()
scope.url = "/test_upload"
element = $compile("<input type='file' mac-upload mac-upload-route='url' />") scope
scope.url = "/test"
scope.$digest()
expect(element.fileupload("option", "url")).toBe "/test"
it "should update form data", ->
scope = $rootScope.$new()
scope.formData = {randomText: "helloWorld"}
element = $compile("<input type='file' mac-upload mac-upload-form-data='formData' />") scope
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "helloWorld"
scope.formData = {randomText: "foobar"}
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "foobar"
it "should update default options", ->
scope = $rootScope.$new()
scope.options = {singleFileUploads: false}
element = $compile("<input type='file' mac-upload mac-upload-options='options' />") scope
scope.$digest()
expect(element.fileupload("option", "singleFileUploads")).toBe false
describe "Callbacks", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should call submit", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.submit = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Submit function should be called", "750"
runs ->
expect(called).toBe true
it "should call success", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.success = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-success='success()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Success function should be called", "750"
runs ->
expect(called).toBe true
it "should call error", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.error = -> called = true
scope.route = "404"
element = $compile("<input type='file' mac-upload mac-upload-error='error()' mac-upload-route='route' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Error function should be called", "750"
runs ->
expect(called).toBe true
it "should call always", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.always = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-always='always()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Always function should be called", "750"
runs ->
expect(called).toBe true
it "should call progress", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.progress = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-progress='progress()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Progress function should be called", "750"
runs ->
expect(called).toBe true
describe "Previews", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should push one file to preview array", ->
param = {files: [{name: '<NAME>'}]}
called = false
scope = $rootScope.$new()
scope.previews = []
scope.submit = ->
called = true
element = $compile("<input type='file' mac-upload mac-upload-previews='previews' mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Files should be added to preview array", "750"
runs ->
scope.$digest()
expect(scope.previews.length).toBeGreaterThan 0
describe "dropZone", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should add droppable class on dragover", ->
scope = $rootScope.$new()
element = $compile("<div class='wrapper'><input type='file' mac-upload mac-upload-drop-zone='.wrapper' /></div>") scope
scope.$digest()
event = $.Event("dragover")
event.target = $("input", element)[0]
event.originalEvent = dataTransfer: {files: [{}]}
$(document).trigger event
expect(element.hasClass("droppable")).toBe true
| true | describe "Mac Fileupload", ->
beforeEach module("Mac")
describe "Options updates", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should initialize fileupload plugin", ->
element = $compile("<input type='file' mac-upload />") $rootScope
expect(element.data("blueimp-fileupload")).not.toBe null
it "should update url", ->
scope = $rootScope.$new()
scope.url = "/test_upload"
element = $compile("<input type='file' mac-upload mac-upload-route='url' />") scope
scope.url = "/test"
scope.$digest()
expect(element.fileupload("option", "url")).toBe "/test"
it "should update form data", ->
scope = $rootScope.$new()
scope.formData = {randomText: "helloWorld"}
element = $compile("<input type='file' mac-upload mac-upload-form-data='formData' />") scope
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "helloWorld"
scope.formData = {randomText: "foobar"}
scope.$digest()
expect(element.fileupload("option", "formData").randomText).toBe "foobar"
it "should update default options", ->
scope = $rootScope.$new()
scope.options = {singleFileUploads: false}
element = $compile("<input type='file' mac-upload mac-upload-options='options' />") scope
scope.$digest()
expect(element.fileupload("option", "singleFileUploads")).toBe false
describe "Callbacks", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should call submit", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.submit = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Submit function should be called", "750"
runs ->
expect(called).toBe true
it "should call success", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.success = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-success='success()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Success function should be called", "750"
runs ->
expect(called).toBe true
it "should call error", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.error = -> called = true
scope.route = "404"
element = $compile("<input type='file' mac-upload mac-upload-error='error()' mac-upload-route='route' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Error function should be called", "750"
runs ->
expect(called).toBe true
it "should call always", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.always = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-always='always()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Always function should be called", "750"
runs ->
expect(called).toBe true
it "should call progress", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.progress = -> called = true
element = $compile("<input type='file' mac-upload mac-upload-progress='progress()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "send", param
return called
, "Progress function should be called", "750"
runs ->
expect(called).toBe true
describe "Previews", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should push one file to preview array", ->
param = {files: [{name: 'PI:NAME:<NAME>END_PI'}]}
called = false
scope = $rootScope.$new()
scope.previews = []
scope.submit = ->
called = true
element = $compile("<input type='file' mac-upload mac-upload-previews='previews' mac-upload-submit='submit()' />") scope
scope.$digest()
waitsFor ->
element.fileupload "add", param
return called
, "Files should be added to preview array", "750"
runs ->
scope.$digest()
expect(scope.previews.length).toBeGreaterThan 0
describe "dropZone", ->
$compile = null
$rootScope = null
beforeEach inject (_$compile_, _$rootScope_) ->
$compile = _$compile_
$rootScope = _$rootScope_
it "should add droppable class on dragover", ->
scope = $rootScope.$new()
element = $compile("<div class='wrapper'><input type='file' mac-upload mac-upload-drop-zone='.wrapper' /></div>") scope
scope.$digest()
event = $.Event("dragover")
event.target = $("input", element)[0]
event.originalEvent = dataTransfer: {files: [{}]}
$(document).trigger event
expect(element.hasClass("droppable")).toBe true
|
[
{
"context": " Flow-Based Programming for Node.js\n# (c) 2011 Henri Bergius, Nemein\n# NoFlo may be freely distributed und",
"end": 77,
"score": 0.9998487234115601,
"start": 64,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "gramming for Node.js\n# (c) 2011 Henri Bergius, Nemein\n# NoFlo may be freely distributed under the M",
"end": 85,
"score": 0.9994606971740723,
"start": 79,
"tag": "NAME",
"value": "Nemein"
}
] | src/lib/NoFlo.coffee | rybesh/noflo | 0 | # NoFlo - Flow-Based Programming for Node.js
# (c) 2011 Henri Bergius, Nemein
# NoFlo may be freely distributed under the MIT license
internalSocket = require "./InternalSocket"
component = require "./Component"
asynccomponent = require "./AsyncComponent"
port = require "./Port"
arrayport = require "./ArrayPort"
graph = require "./Graph"
# # The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class NoFlo
processes: {}
connections: []
graph: null
startupDate: null
constructor: (graph) ->
@processes = {}
@connections = []
@graph = graph
# As most NoFlo networks are long-running processes, the
# network coordinator marks down the start-up time. This
# way we can calculate the uptime of the network.
@startupDate = new Date()
# A NoFlo graph may change after network initialization.
# For this, the network subscribes to the change events from
# the graph.
#
# In graph we talk about nodes and edges. Nodes correspond
# to NoFlo processes, and edges to connections between them.
@graph.on 'addNode', (node) =>
@addNode node
@graph.on 'removeNode', (node) =>
@removeNode node
@graph.on 'addEdge', (edge) =>
@addEdge edge
@graph.on 'removeEdge', (edge) =>
@removeEdge edge
# The uptime of the network is the current time minus the start-up
# time, in seconds.
uptime: -> new Date() - @startupDate
# ## Loading components
#
# Components can be passed to the NoFlo network in two ways:
#
# * As direct, instantiated JavaScript objects
# * As filenames
load: (component) ->
# Direct component instance, return as is
if typeof component is 'object'
return component
try
if component.substr(0, 1) is "."
component = "#{process.cwd()}#{component.substr(1)}"
implementation = require component
catch error
try
implementation = require "../components/#{component}"
catch localError
# Throw the original error instead
error.message = "#{localError.message} (#{error.message})"
throw error
implementation.getComponent()
# ## Add a process to the network
#
# Processes can be added to a network at either start-up time
# or later. The processes are added with a node definition object
# that includes the following properties:
#
# * `id`: Identifier of the process in the network. Typically a string
# * `component`: Filename or path of a NoFlo component, or a component instance object
addNode: (node) ->
# Processes are treated as singletons by their identifier. If
# we already have a process with the given ID, return that.
return if @processes[node.id]
process =
id: node.id
# Load the process for the node.
if node.component
process.component = @load node.component
# Store and return the process instance
@processes[process.id] = process
removeNode: (node) ->
return unless @processes[node.id]
# TODO: Check for existing edges with this node
delete @processes[node.id]
# Get process by its ID.
getNode: (id) ->
@processes[id]
connectPort: (socket, process, port, inbound) ->
if inbound
socket.to =
process: process
port: port
unless process.component.inPorts and process.component.inPorts[port]
throw new Error "No inport '#{port}' defined in process #{process.id}"
return
return process.component.inPorts[port].attach socket
socket.from =
process: process
port: port
unless process.component.outPorts and process.component.outPorts[port]
throw new Error "No outport '#{port}' defined in process #{process.id}"
return
process.component.outPorts[port].attach socket
addDebug: (socket) ->
logSocket = (message) ->
console.error "#{socket.getId()} #{message}"
socket.on "connect", ->
logSocket "CONN"
socket.on "begingroup", (group) ->
logSocket "< #{group}"
socket.on "disconnect", ->
logSocket "DISC"
socket.on "endgroup", (group) ->
logSocket "> #{group}"
socket.on "data", (data) ->
logSocket "DATA"
addEdge: (edge, callback) ->
return @addInitial edge, callback unless edge.from.node
socket = internalSocket.createSocket()
@addDebug socket if @debug
from = @getNode edge.from.node
unless from
throw new Error "No process defined for outbound node #{edge.from.node}"
unless from.component
throw new Error "No component defined for outbound node #{edge.from.node}"
unless from.component.isReady()
from.component.once "ready", =>
@addEdge edge, callback
return
to = @getNode edge.to.node
unless to
throw new Error "No process defined for inbound node #{edge.to.node}"
unless to.component
throw new Error "No component defined for inbound node #{edge.to.node}"
unless to.component.isReady()
to.component.once "ready", =>
@addEdge edge, callback
return
@connectPort socket, to, edge.to.port, true
@connectPort socket, from, edge.from.port, false
@connections.push socket
callback() if callback?
removeEdge: (edge) ->
for connection,index in @connections
if edge.to.node is connection.to.process.id and edge.to.port is connection.to.port
connection.to.process.component.inPorts[connection.to.port]?.detach connection
@connections.splice index, 1
if edge.from.node
if connection.from and edge.from.node is connection.from.process.id and edge.from.port is connection.from.port
connection.from.process.component.inPorts[connection.from.port].detach connection
@connections.splice index, 1
addInitial: (initializer, callback) ->
socket = internalSocket.createSocket()
@addDebug socket if @debug
to = @getNode initializer.to.node
unless to
throw new Error "No process defined for inbound node #{initializer.to.node}"
unless to.component.isReady() or to.component.inPorts[initializer.to.port]
to.component.setMaxListeners 0
to.component.once "ready", =>
@addInitial initializer, callback
return
@connectPort socket, to, initializer.to.port, true
@connections.push socket
socket.connect()
socket.send initializer.from.data
socket.disconnect()
callback() if callback?
exports.createNetwork = (graph, debug = false, callback) ->
network = new NoFlo graph
network.debug = debug
network.addNode node for node in graph.nodes
toadd = graph.edges.length + graph.initializers.length
for edge in graph.edges
network.addEdge edge, ->
toadd--
callback() if callback? and toadd == 0
for initializer in graph.initializers
network.addInitial initializer, ->
toadd--
callback() if callback? and toadd == 0
network
exports.loadFile = (file, success, debug = false) ->
graph.loadFile file, (net) ->
success exports.createNetwork net, debug
exports.saveFile = (graph, file, success) ->
graph.save file, ->
success file
exports.Component = component.Component
exports.AsyncComponent = asynccomponent.AsyncComponent
exports.Port = port.Port
exports.ArrayPort = arrayport.ArrayPort
exports.Graph = graph.Graph
exports.graph = graph
exports.internalSocket = internalSocket
| 132892 | # NoFlo - Flow-Based Programming for Node.js
# (c) 2011 <NAME>, <NAME>
# NoFlo may be freely distributed under the MIT license
internalSocket = require "./InternalSocket"
component = require "./Component"
asynccomponent = require "./AsyncComponent"
port = require "./Port"
arrayport = require "./ArrayPort"
graph = require "./Graph"
# # The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class NoFlo
processes: {}
connections: []
graph: null
startupDate: null
constructor: (graph) ->
@processes = {}
@connections = []
@graph = graph
# As most NoFlo networks are long-running processes, the
# network coordinator marks down the start-up time. This
# way we can calculate the uptime of the network.
@startupDate = new Date()
# A NoFlo graph may change after network initialization.
# For this, the network subscribes to the change events from
# the graph.
#
# In graph we talk about nodes and edges. Nodes correspond
# to NoFlo processes, and edges to connections between them.
@graph.on 'addNode', (node) =>
@addNode node
@graph.on 'removeNode', (node) =>
@removeNode node
@graph.on 'addEdge', (edge) =>
@addEdge edge
@graph.on 'removeEdge', (edge) =>
@removeEdge edge
# The uptime of the network is the current time minus the start-up
# time, in seconds.
uptime: -> new Date() - @startupDate
# ## Loading components
#
# Components can be passed to the NoFlo network in two ways:
#
# * As direct, instantiated JavaScript objects
# * As filenames
load: (component) ->
# Direct component instance, return as is
if typeof component is 'object'
return component
try
if component.substr(0, 1) is "."
component = "#{process.cwd()}#{component.substr(1)}"
implementation = require component
catch error
try
implementation = require "../components/#{component}"
catch localError
# Throw the original error instead
error.message = "#{localError.message} (#{error.message})"
throw error
implementation.getComponent()
# ## Add a process to the network
#
# Processes can be added to a network at either start-up time
# or later. The processes are added with a node definition object
# that includes the following properties:
#
# * `id`: Identifier of the process in the network. Typically a string
# * `component`: Filename or path of a NoFlo component, or a component instance object
addNode: (node) ->
# Processes are treated as singletons by their identifier. If
# we already have a process with the given ID, return that.
return if @processes[node.id]
process =
id: node.id
# Load the process for the node.
if node.component
process.component = @load node.component
# Store and return the process instance
@processes[process.id] = process
removeNode: (node) ->
return unless @processes[node.id]
# TODO: Check for existing edges with this node
delete @processes[node.id]
# Get process by its ID.
getNode: (id) ->
@processes[id]
connectPort: (socket, process, port, inbound) ->
if inbound
socket.to =
process: process
port: port
unless process.component.inPorts and process.component.inPorts[port]
throw new Error "No inport '#{port}' defined in process #{process.id}"
return
return process.component.inPorts[port].attach socket
socket.from =
process: process
port: port
unless process.component.outPorts and process.component.outPorts[port]
throw new Error "No outport '#{port}' defined in process #{process.id}"
return
process.component.outPorts[port].attach socket
addDebug: (socket) ->
logSocket = (message) ->
console.error "#{socket.getId()} #{message}"
socket.on "connect", ->
logSocket "CONN"
socket.on "begingroup", (group) ->
logSocket "< #{group}"
socket.on "disconnect", ->
logSocket "DISC"
socket.on "endgroup", (group) ->
logSocket "> #{group}"
socket.on "data", (data) ->
logSocket "DATA"
addEdge: (edge, callback) ->
return @addInitial edge, callback unless edge.from.node
socket = internalSocket.createSocket()
@addDebug socket if @debug
from = @getNode edge.from.node
unless from
throw new Error "No process defined for outbound node #{edge.from.node}"
unless from.component
throw new Error "No component defined for outbound node #{edge.from.node}"
unless from.component.isReady()
from.component.once "ready", =>
@addEdge edge, callback
return
to = @getNode edge.to.node
unless to
throw new Error "No process defined for inbound node #{edge.to.node}"
unless to.component
throw new Error "No component defined for inbound node #{edge.to.node}"
unless to.component.isReady()
to.component.once "ready", =>
@addEdge edge, callback
return
@connectPort socket, to, edge.to.port, true
@connectPort socket, from, edge.from.port, false
@connections.push socket
callback() if callback?
removeEdge: (edge) ->
for connection,index in @connections
if edge.to.node is connection.to.process.id and edge.to.port is connection.to.port
connection.to.process.component.inPorts[connection.to.port]?.detach connection
@connections.splice index, 1
if edge.from.node
if connection.from and edge.from.node is connection.from.process.id and edge.from.port is connection.from.port
connection.from.process.component.inPorts[connection.from.port].detach connection
@connections.splice index, 1
addInitial: (initializer, callback) ->
socket = internalSocket.createSocket()
@addDebug socket if @debug
to = @getNode initializer.to.node
unless to
throw new Error "No process defined for inbound node #{initializer.to.node}"
unless to.component.isReady() or to.component.inPorts[initializer.to.port]
to.component.setMaxListeners 0
to.component.once "ready", =>
@addInitial initializer, callback
return
@connectPort socket, to, initializer.to.port, true
@connections.push socket
socket.connect()
socket.send initializer.from.data
socket.disconnect()
callback() if callback?
exports.createNetwork = (graph, debug = false, callback) ->
network = new NoFlo graph
network.debug = debug
network.addNode node for node in graph.nodes
toadd = graph.edges.length + graph.initializers.length
for edge in graph.edges
network.addEdge edge, ->
toadd--
callback() if callback? and toadd == 0
for initializer in graph.initializers
network.addInitial initializer, ->
toadd--
callback() if callback? and toadd == 0
network
exports.loadFile = (file, success, debug = false) ->
graph.loadFile file, (net) ->
success exports.createNetwork net, debug
exports.saveFile = (graph, file, success) ->
graph.save file, ->
success file
exports.Component = component.Component
exports.AsyncComponent = asynccomponent.AsyncComponent
exports.Port = port.Port
exports.ArrayPort = arrayport.ArrayPort
exports.Graph = graph.Graph
exports.graph = graph
exports.internalSocket = internalSocket
| true | # NoFlo - Flow-Based Programming for Node.js
# (c) 2011 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# NoFlo may be freely distributed under the MIT license
internalSocket = require "./InternalSocket"
component = require "./Component"
asynccomponent = require "./AsyncComponent"
port = require "./Port"
arrayport = require "./ArrayPort"
graph = require "./Graph"
# # The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class NoFlo
processes: {}
connections: []
graph: null
startupDate: null
constructor: (graph) ->
@processes = {}
@connections = []
@graph = graph
# As most NoFlo networks are long-running processes, the
# network coordinator marks down the start-up time. This
# way we can calculate the uptime of the network.
@startupDate = new Date()
# A NoFlo graph may change after network initialization.
# For this, the network subscribes to the change events from
# the graph.
#
# In graph we talk about nodes and edges. Nodes correspond
# to NoFlo processes, and edges to connections between them.
@graph.on 'addNode', (node) =>
@addNode node
@graph.on 'removeNode', (node) =>
@removeNode node
@graph.on 'addEdge', (edge) =>
@addEdge edge
@graph.on 'removeEdge', (edge) =>
@removeEdge edge
# The uptime of the network is the current time minus the start-up
# time, in seconds.
uptime: -> new Date() - @startupDate
# ## Loading components
#
# Components can be passed to the NoFlo network in two ways:
#
# * As direct, instantiated JavaScript objects
# * As filenames
load: (component) ->
# Direct component instance, return as is
if typeof component is 'object'
return component
try
if component.substr(0, 1) is "."
component = "#{process.cwd()}#{component.substr(1)}"
implementation = require component
catch error
try
implementation = require "../components/#{component}"
catch localError
# Throw the original error instead
error.message = "#{localError.message} (#{error.message})"
throw error
implementation.getComponent()
# ## Add a process to the network
#
# Processes can be added to a network at either start-up time
# or later. The processes are added with a node definition object
# that includes the following properties:
#
# * `id`: Identifier of the process in the network. Typically a string
# * `component`: Filename or path of a NoFlo component, or a component instance object
addNode: (node) ->
# Processes are treated as singletons by their identifier. If
# we already have a process with the given ID, return that.
return if @processes[node.id]
process =
id: node.id
# Load the process for the node.
if node.component
process.component = @load node.component
# Store and return the process instance
@processes[process.id] = process
removeNode: (node) ->
return unless @processes[node.id]
# TODO: Check for existing edges with this node
delete @processes[node.id]
# Get process by its ID.
getNode: (id) ->
@processes[id]
connectPort: (socket, process, port, inbound) ->
if inbound
socket.to =
process: process
port: port
unless process.component.inPorts and process.component.inPorts[port]
throw new Error "No inport '#{port}' defined in process #{process.id}"
return
return process.component.inPorts[port].attach socket
socket.from =
process: process
port: port
unless process.component.outPorts and process.component.outPorts[port]
throw new Error "No outport '#{port}' defined in process #{process.id}"
return
process.component.outPorts[port].attach socket
addDebug: (socket) ->
logSocket = (message) ->
console.error "#{socket.getId()} #{message}"
socket.on "connect", ->
logSocket "CONN"
socket.on "begingroup", (group) ->
logSocket "< #{group}"
socket.on "disconnect", ->
logSocket "DISC"
socket.on "endgroup", (group) ->
logSocket "> #{group}"
socket.on "data", (data) ->
logSocket "DATA"
addEdge: (edge, callback) ->
return @addInitial edge, callback unless edge.from.node
socket = internalSocket.createSocket()
@addDebug socket if @debug
from = @getNode edge.from.node
unless from
throw new Error "No process defined for outbound node #{edge.from.node}"
unless from.component
throw new Error "No component defined for outbound node #{edge.from.node}"
unless from.component.isReady()
from.component.once "ready", =>
@addEdge edge, callback
return
to = @getNode edge.to.node
unless to
throw new Error "No process defined for inbound node #{edge.to.node}"
unless to.component
throw new Error "No component defined for inbound node #{edge.to.node}"
unless to.component.isReady()
to.component.once "ready", =>
@addEdge edge, callback
return
@connectPort socket, to, edge.to.port, true
@connectPort socket, from, edge.from.port, false
@connections.push socket
callback() if callback?
removeEdge: (edge) ->
for connection,index in @connections
if edge.to.node is connection.to.process.id and edge.to.port is connection.to.port
connection.to.process.component.inPorts[connection.to.port]?.detach connection
@connections.splice index, 1
if edge.from.node
if connection.from and edge.from.node is connection.from.process.id and edge.from.port is connection.from.port
connection.from.process.component.inPorts[connection.from.port].detach connection
@connections.splice index, 1
addInitial: (initializer, callback) ->
socket = internalSocket.createSocket()
@addDebug socket if @debug
to = @getNode initializer.to.node
unless to
throw new Error "No process defined for inbound node #{initializer.to.node}"
unless to.component.isReady() or to.component.inPorts[initializer.to.port]
to.component.setMaxListeners 0
to.component.once "ready", =>
@addInitial initializer, callback
return
@connectPort socket, to, initializer.to.port, true
@connections.push socket
socket.connect()
socket.send initializer.from.data
socket.disconnect()
callback() if callback?
exports.createNetwork = (graph, debug = false, callback) ->
network = new NoFlo graph
network.debug = debug
network.addNode node for node in graph.nodes
toadd = graph.edges.length + graph.initializers.length
for edge in graph.edges
network.addEdge edge, ->
toadd--
callback() if callback? and toadd == 0
for initializer in graph.initializers
network.addInitial initializer, ->
toadd--
callback() if callback? and toadd == 0
network
exports.loadFile = (file, success, debug = false) ->
graph.loadFile file, (net) ->
success exports.createNetwork net, debug
exports.saveFile = (graph, file, success) ->
graph.save file, ->
success file
exports.Component = component.Component
exports.AsyncComponent = asynccomponent.AsyncComponent
exports.Port = port.Port
exports.ArrayPort = arrayport.ArrayPort
exports.Graph = graph.Graph
exports.graph = graph
exports.internalSocket = internalSocket
|
[
{
"context": "\"./lib/esm.mjs\"\n version: \"0.0.0\"\n author: \"Anatoly Chernov <chertoly@gmail.com>\"\n description: \"left as a",
"end": 318,
"score": 0.9998875260353088,
"start": 303,
"tag": "NAME",
"value": "Anatoly Chernov"
},
{
"context": " version: \"0.0.0\"\n author: \"Anatoly Chernov <chertoly@gmail.com>\"\n description: \"left as an exercise to the re",
"end": 338,
"score": 0.999928891658783,
"start": 320,
"tag": "EMAIL",
"value": "chertoly@gmail.com"
}
] | src/commands/create/package.coffee | ch1c0t/coffeelib | 0 | exports.CreatePackageFile = ({ name }) ->
await IO.copy "#{ROOT}/LICENSE", "#{DIR}/LICENSE"
{ version } = require '../../../package.json'
spec =
name: name
main: "./lib/main.js"
exports:
require: "./lib/main.js"
import: "./lib/esm.mjs"
version: "0.0.0"
author: "Anatoly Chernov <chertoly@gmail.com>"
description: "left as an exercise to the reader"
license: "0BSD"
keywords: [
'coffeescript'
]
scripts:
build: "coffeelib build"
start: "coffeelib watch"
test: "jasmine"
devDependencies:
coffeelib: "^#{version}"
jasmine: "^4.0.0"
source = JSON.stringify spec, null, 2
IO.write "#{DIR}/package.json", source
| 183258 | exports.CreatePackageFile = ({ name }) ->
await IO.copy "#{ROOT}/LICENSE", "#{DIR}/LICENSE"
{ version } = require '../../../package.json'
spec =
name: name
main: "./lib/main.js"
exports:
require: "./lib/main.js"
import: "./lib/esm.mjs"
version: "0.0.0"
author: "<NAME> <<EMAIL>>"
description: "left as an exercise to the reader"
license: "0BSD"
keywords: [
'coffeescript'
]
scripts:
build: "coffeelib build"
start: "coffeelib watch"
test: "jasmine"
devDependencies:
coffeelib: "^#{version}"
jasmine: "^4.0.0"
source = JSON.stringify spec, null, 2
IO.write "#{DIR}/package.json", source
| true | exports.CreatePackageFile = ({ name }) ->
await IO.copy "#{ROOT}/LICENSE", "#{DIR}/LICENSE"
{ version } = require '../../../package.json'
spec =
name: name
main: "./lib/main.js"
exports:
require: "./lib/main.js"
import: "./lib/esm.mjs"
version: "0.0.0"
author: "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
description: "left as an exercise to the reader"
license: "0BSD"
keywords: [
'coffeescript'
]
scripts:
build: "coffeelib build"
start: "coffeelib watch"
test: "jasmine"
devDependencies:
coffeelib: "^#{version}"
jasmine: "^4.0.0"
source = JSON.stringify spec, null, 2
IO.write "#{DIR}/package.json", source
|
[
{
"context": " \"#081d58\"\n ]\n }\n {\n name: 'GnBu'\n range:\n 3: [\n \"#e0f3db\"\n ",
"end": 2172,
"score": 0.9510190486907959,
"start": 2168,
"tag": "NAME",
"value": "GnBu"
},
{
"context": " \"#00441b\"\n ]\n }\n {\n name: 'PuBuGn'\n range:\n 3: [\n \"#ece2f0",
"end": 4260,
"score": 0.45199793577194214,
"start": 4258,
"tag": "NAME",
"value": "Pu"
},
{
"context": " \"#00441b\"\n ]\n }\n {\n name: 'PuBuGn'\n range:\n 3: [\n \"#ece2f0\"\n ",
"end": 4264,
"score": 0.9081130027770996,
"start": 4260,
"tag": "USERNAME",
"value": "BuGn"
},
{
"context": " \"#014636\"\n ]\n }\n {\n name: 'PuBu'\n range:\n 3: [\n \"#ece7f2\"\n",
"end": 5307,
"score": 0.5306621193885803,
"start": 5305,
"tag": "NAME",
"value": "Pu"
},
{
"context": " \"#014636\"\n ]\n }\n {\n name: 'PuBu'\n range:\n 3: [\n \"#ece7f2\"\n ",
"end": 5309,
"score": 0.8885360956192017,
"start": 5307,
"tag": "USERNAME",
"value": "Bu"
},
{
"context": " \"#023858\"\n ]\n }\n {\n name: 'BuPu'\n range:\n 3: [\n \"#e0ecf4\"\n ",
"end": 6354,
"score": 0.9139050245285034,
"start": 6350,
"tag": "NAME",
"value": "BuPu"
},
{
"context": " \"#662506\"\n ]\n }\n {\n name: 'Purples'\n range:\n 3: [\n \"#efedf5\"\n ",
"end": 12631,
"score": 0.999556839466095,
"start": 12624,
"tag": "NAME",
"value": "Purples"
},
{
"context": " \"#3f007d\"\n ]\n }\n {\n name: 'Blues'\n range:\n 3: [\n \"#deebf7\"\n ",
"end": 13677,
"score": 0.9995560050010681,
"start": 13672,
"tag": "NAME",
"value": "Blues"
},
{
"context": " \"#08306b\"\n ]\n }\n {\n name: 'Greens'\n range:\n 3: [\n \"#e5f5e0\"\n ",
"end": 14724,
"score": 0.9994589686393738,
"start": 14718,
"tag": "NAME",
"value": "Greens"
},
{
"context": " \"#7f2704\"\n ]\n }\n {\n name: 'Reds'\n range:\n 3: [\n \"#fee0d2\"\n ",
"end": 16817,
"score": 0.9984204769134521,
"start": 16813,
"tag": "NAME",
"value": "Reds"
},
{
"context": " \"#67000d\"\n ]\n }\n {\n name: 'Greys'\n range:\n 3: [\n \"#f0f0f0\"\n ",
"end": 17863,
"score": 0.9977080225944519,
"start": 17858,
"tag": "NAME",
"value": "Greys"
},
{
"context": " \"#2d004b\"\n ]\n }\n {\n name: 'BrBG'\n range:\n 3: [\n \"#d8b365\"\n ",
"end": 20421,
"score": 0.669949471950531,
"start": 20417,
"tag": "NAME",
"value": "BrBG"
},
{
"context": " \"#00441b\"\n ]\n }\n {\n name: 'PiYG'\n range:\n 3: [\n \"#e9a3c9\"\n ",
"end": 23447,
"score": 0.7529523372650146,
"start": 23443,
"tag": "USERNAME",
"value": "PiYG"
},
{
"context": " \"#276419\"\n ]\n }\n {\n name: 'RdBu'\n range:\n 3: [\n \"#ef8a62\"\n ",
"end": 24960,
"score": 0.9369785785675049,
"start": 24956,
"tag": "NAME",
"value": "RdBu"
},
{
"context": " \"#5e4fa2\"\n ]\n }\n {\n name: 'RdYlGn'\n range:\n 3: [\n \"#fc8d59\"\n ",
"end": 31020,
"score": 0.8400425910949707,
"start": 31014,
"tag": "NAME",
"value": "RdYlGn"
},
{
"context": " \"#666666\"\n ]\n }\n {\n name: 'Paired'\n range:\n 3: [\n \"#a6cee3\"\n ",
"end": 34222,
"score": 0.9996867179870605,
"start": 34216,
"tag": "NAME",
"value": "Paired"
},
{
"context": " \"#b15928\"\n ]\n }\n {\n name: 'Pastel1'\n range:\n 3: [\n \"#fbb4ae\"\n ",
"end": 36002,
"score": 0.9970758557319641,
"start": 35995,
"tag": "NAME",
"value": "Pastel1"
},
{
"context": " \"#f2f2f2\"\n ]\n }\n {\n name: 'Pastel2'\n range:\n 3: [\n \"#b3e2cd\"\n ",
"end": 37050,
"score": 0.9994692206382751,
"start": 37043,
"tag": "USERNAME",
"value": "Pastel2"
}
] | src/services/palettes.coffee | nicgirault/angular-colorBrewer-selector | 0 | angular.module('colorBrewer').factory 'palettes', ->
[
{
name: 'YlGn'
range:
3: [
"#f7fcb9"
"#addd8e"
"#31a354"
]
4: [
"#ffffcc"
"#c2e699"
"#78c679"
"#238443"
]
5: [
"#ffffcc"
"#c2e699"
"#78c679"
"#31a354"
"#006837"
]
6: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#31a354"
"#006837"
]
7: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
8: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
9: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#006837"
"#004529"
]
}
{
name: 'YlGnBu'
range:
3: [
"#edf8b1"
"#7fcdbb"
"#2c7fb8"
]
4: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#225ea8"
]
5: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#2c7fb8"
"#253494"
]
6: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#2c7fb8"
"#253494"
]
7: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
8: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
9: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#253494"
"#081d58"
]
}
{
name: 'GnBu'
range:
3: [
"#e0f3db"
"#a8ddb5"
"#43a2ca"
]
4: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#2b8cbe"
]
5: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
6: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
7: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
8: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
9: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#0868ac"
"#084081"
]
}
{
name: 'BuGn'
range:
3: [
"#e5f5f9"
"#99d8c9"
"#2ca25f"
]
4: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#238b45"
]
5: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
6: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
7: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
8: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
9: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: 'PuBuGn'
range:
3: [
"#ece2f0"
"#a6bddb"
"#1c9099"
]
4: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#02818a"
]
5: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#1c9099"
"#016c59"
]
6: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#1c9099"
"#016c59"
]
7: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
8: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
9: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016c59"
"#014636"
]
}
{
name: 'PuBu'
range:
3: [
"#ece7f2"
"#a6bddb"
"#2b8cbe"
]
4: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#0570b0"
]
5: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
6: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
7: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
8: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
9: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#045a8d"
"#023858"
]
}
{
name: 'BuPu'
range:
3: [
"#e0ecf4"
"#9ebcda"
"#8856a7"
]
4: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#88419d"
]
5: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#8856a7"
"#810f7c"
]
6: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8856a7"
"#810f7c"
]
7: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
8: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
9: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#810f7c"
"#4d004b"
]
}
{
name: 'RdPu'
range:
3: [
"#fde0dd"
"#fa9fb5"
"#c51b8a"
]
4: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#ae017e"
]
5: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#c51b8a"
"#7a0177"
]
6: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#c51b8a"
"#7a0177"
]
7: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
8: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
9: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
"#49006a"
]
}
{
name: 'PuRd'
range:
3: [
"#e7e1ef"
"#c994c7"
"#dd1c77"
]
4: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#ce1256"
]
5: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#dd1c77"
"#980043"
]
6: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#dd1c77"
"#980043"
]
7: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
8: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
9: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#980043"
"#67001f"
]
}
{
name: 'OrRd'
range:
3: [
"#fee8c8"
"#fdbb84"
"#e34a33"
]
4: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#d7301f"
]
5: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#e34a33"
"#b30000"
]
6: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#e34a33"
"#b30000"
]
7: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
8: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
9: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#b30000"
"#7f0000"
]
}
{
name: 'YlOrRd'
range:
3: [
"#ffeda0"
"#feb24c"
"#f03b20"
]
4: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#e31a1c"
]
5: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
6: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
7: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
8: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
9: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#bd0026"
"#800026"
]
}
{
name: 'YlOrBr'
range:
3: [
"#fff7bc"
"#fec44f"
"#d95f0e"
]
4: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#cc4c02"
]
5: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#d95f0e"
"#993404"
]
6: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#d95f0e"
"#993404"
]
7: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
8: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
9: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#993404"
"#662506"
]
}
{
name: 'Purples'
range:
3: [
"#efedf5"
"#bcbddc"
"#756bb1"
]
4: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#6a51a3"
]
5: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#756bb1"
"#54278f"
]
6: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#756bb1"
"#54278f"
]
7: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
8: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
9: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#54278f"
"#3f007d"
]
}
{
name: 'Blues'
range:
3: [
"#deebf7"
"#9ecae1"
"#3182bd"
]
4: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#2171b5"
]
5: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#3182bd"
"#08519c"
]
6: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#3182bd"
"#08519c"
]
7: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
8: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
9: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#08519c"
"#08306b"
]
}
{
name: 'Greens'
range:
3: [
"#e5f5e0"
"#a1d99b"
"#31a354"
]
4: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#238b45"
]
5: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#31a354"
"#006d2c"
]
6: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#31a354"
"#006d2c"
]
7: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
8: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
9: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: 'Oranges'
range:
3: [
"#fee6ce"
"#fdae6b"
"#e6550d"
]
4: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#d94701"
]
5: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#e6550d"
"#a63603"
]
6: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#e6550d"
"#a63603"
]
7: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
8: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
9: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#a63603"
"#7f2704"
]
}
{
name: 'Reds'
range:
3: [
"#fee0d2"
"#fc9272"
"#de2d26"
]
4: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#cb181d"
]
5: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
6: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
7: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
8: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
9: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#a50f15"
"#67000d"
]
}
{
name: 'Greys'
range:
3: [
"#f0f0f0"
"#bdbdbd"
"#636363"
]
4: [
"#f7f7f7"
"#cccccc"
"#969696"
"#525252"
]
5: [
"#f7f7f7"
"#cccccc"
"#969696"
"#636363"
"#252525"
]
6: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#636363"
"#252525"
]
7: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
8: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
9: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
"#000000"
]
}
{
name: 'PuOr'
range:
3: [
"#f1a340"
"#f7f7f7"
"#998ec3"
]
4: [
"#e66101"
"#fdb863"
"#b2abd2"
"#5e3c99"
]
5: [
"#e66101"
"#fdb863"
"#f7f7f7"
"#b2abd2"
"#5e3c99"
]
6: [
"#b35806"
"#f1a340"
"#fee0b6"
"#d8daeb"
"#998ec3"
"#542788"
]
7: [
"#b35806"
"#f1a340"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#998ec3"
"#542788"
]
8: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
9: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
10: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
11: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
}
{
name: 'BrBG'
range:
3: [
"#d8b365"
"#f5f5f5"
"#5ab4ac"
]
4: [
"#a6611a"
"#dfc27d"
"#80cdc1"
"#018571"
]
5: [
"#a6611a"
"#dfc27d"
"#f5f5f5"
"#80cdc1"
"#018571"
]
6: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
7: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
8: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
9: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
10: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
11: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
}
{
name: 'PRGn'
range:
3: [
"#af8dc3"
"#f7f7f7"
"#7fbf7b"
]
4: [
"#7b3294"
"#c2a5cf"
"#a6dba0"
"#008837"
]
5: [
"#7b3294"
"#c2a5cf"
"#f7f7f7"
"#a6dba0"
"#008837"
]
6: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
7: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
8: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
9: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
10: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
11: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
}
{
name: 'PiYG'
range:
3: [
"#e9a3c9"
"#f7f7f7"
"#a1d76a"
]
4: [
"#d01c8b"
"#f1b6da"
"#b8e186"
"#4dac26"
]
5: [
"#d01c8b"
"#f1b6da"
"#f7f7f7"
"#b8e186"
"#4dac26"
]
6: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
7: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
8: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
9: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
10: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
11: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
}
{
name: 'RdBu'
range:
3: [
"#ef8a62"
"#f7f7f7"
"#67a9cf"
]
4: [
"#ca0020"
"#f4a582"
"#92c5de"
"#0571b0"
]
5: [
"#ca0020"
"#f4a582"
"#f7f7f7"
"#92c5de"
"#0571b0"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
}
{
name: 'RdGy'
range:
3: [
"#ef8a62"
"#ffffff"
"#999999"
]
4: [
"#ca0020"
"#f4a582"
"#bababa"
"#404040"
]
5: [
"#ca0020"
"#f4a582"
"#ffffff"
"#bababa"
"#404040"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
}
{
name: 'RdYlBu'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91bfdb"
]
4: [
"#d7191c"
"#fdae61"
"#abd9e9"
"#2c7bb6"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abd9e9"
"#2c7bb6"
]
6: [
"#d73027"
"#fc8d59"
"#fee090"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
7: [
"#d73027"
"#fc8d59"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
}
{
name: 'Spectral'
range:
3: [
"#fc8d59"
"#ffffbf"
"#99d594"
]
4: [
"#d7191c"
"#fdae61"
"#abdda4"
"#2b83ba"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abdda4"
"#2b83ba"
]
6: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#e6f598"
"#99d594"
"#3288bd"
]
7: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#e6f598"
"#99d594"
"#3288bd"
]
8: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
9: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
10: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
11: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
}
{
name: 'RdYlGn'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91cf60"
]
4: [
"#d7191c"
"#fdae61"
"#a6d96a"
"#1a9641"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#a6d96a"
"#1a9641"
]
6: [
"#d73027"
"#fc8d59"
"#fee08b"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
7: [
"#d73027"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
}
{
name: 'Accent'
range:
3: [
"#7fc97f"
"#beaed4"
"#fdc086"
]
4: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
]
5: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
]
6: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
]
7: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
]
8: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
"#666666"
]
}
{
name: 'Dark2'
range:
3: [
"#1b9e77"
"#d95f02"
"#7570b3"
]
4: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
]
5: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
]
6: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
]
7: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
]
8: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
"#666666"
]
}
{
name: 'Paired'
range:
3: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
]
4: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
]
5: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
]
6: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
]
7: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
]
8: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
]
9: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
]
10: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
]
11: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
]
12: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
"#b15928"
]
}
{
name: 'Pastel1'
range:
3: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
]
4: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
]
5: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
]
6: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
]
7: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
]
8: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
]
9: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
"#f2f2f2"
]
}
{
name: 'Pastel2'
range:
3: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
]
4: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
]
5: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
]
6: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
]
7: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
]
8: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
"#cccccc"
]
}
{
name: 'Set1'
range:
3: [
"#e41a1c"
"#377eb8"
"#4daf4a"
]
4: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
]
5: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
]
6: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
]
7: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
]
8: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
]
9: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
"#999999"
]
}
{
name: 'Set2'
range:
3: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
]
4: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
]
5: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
]
6: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
]
7: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
]
8: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
"#b3b3b3"
]
}
{
name: 'Set3'
range:
3: [
"#8dd3c7"
"#ffffb3"
"#bebada"
]
4: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
]
5: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
]
6: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
]
7: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
]
8: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
]
9: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
]
10: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
]
11: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
]
12: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
"#ffed6f"
]
}
]
| 216051 | angular.module('colorBrewer').factory 'palettes', ->
[
{
name: 'YlGn'
range:
3: [
"#f7fcb9"
"#addd8e"
"#31a354"
]
4: [
"#ffffcc"
"#c2e699"
"#78c679"
"#238443"
]
5: [
"#ffffcc"
"#c2e699"
"#78c679"
"#31a354"
"#006837"
]
6: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#31a354"
"#006837"
]
7: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
8: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
9: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#006837"
"#004529"
]
}
{
name: 'YlGnBu'
range:
3: [
"#edf8b1"
"#7fcdbb"
"#2c7fb8"
]
4: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#225ea8"
]
5: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#2c7fb8"
"#253494"
]
6: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#2c7fb8"
"#253494"
]
7: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
8: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
9: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#253494"
"#081d58"
]
}
{
name: '<NAME>'
range:
3: [
"#e0f3db"
"#a8ddb5"
"#43a2ca"
]
4: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#2b8cbe"
]
5: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
6: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
7: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
8: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
9: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#0868ac"
"#084081"
]
}
{
name: 'BuGn'
range:
3: [
"#e5f5f9"
"#99d8c9"
"#2ca25f"
]
4: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#238b45"
]
5: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
6: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
7: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
8: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
9: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: '<NAME>BuGn'
range:
3: [
"#ece2f0"
"#a6bddb"
"#1c9099"
]
4: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#02818a"
]
5: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#1c9099"
"#016c59"
]
6: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#1c9099"
"#016c59"
]
7: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
8: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
9: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016c59"
"#014636"
]
}
{
name: '<NAME>Bu'
range:
3: [
"#ece7f2"
"#a6bddb"
"#2b8cbe"
]
4: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#0570b0"
]
5: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
6: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
7: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
8: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
9: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#045a8d"
"#023858"
]
}
{
name: '<NAME>'
range:
3: [
"#e0ecf4"
"#9ebcda"
"#8856a7"
]
4: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#88419d"
]
5: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#8856a7"
"#810f7c"
]
6: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8856a7"
"#810f7c"
]
7: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
8: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
9: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#810f7c"
"#4d004b"
]
}
{
name: 'RdPu'
range:
3: [
"#fde0dd"
"#fa9fb5"
"#c51b8a"
]
4: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#ae017e"
]
5: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#c51b8a"
"#7a0177"
]
6: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#c51b8a"
"#7a0177"
]
7: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
8: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
9: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
"#49006a"
]
}
{
name: 'PuRd'
range:
3: [
"#e7e1ef"
"#c994c7"
"#dd1c77"
]
4: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#ce1256"
]
5: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#dd1c77"
"#980043"
]
6: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#dd1c77"
"#980043"
]
7: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
8: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
9: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#980043"
"#67001f"
]
}
{
name: 'OrRd'
range:
3: [
"#fee8c8"
"#fdbb84"
"#e34a33"
]
4: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#d7301f"
]
5: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#e34a33"
"#b30000"
]
6: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#e34a33"
"#b30000"
]
7: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
8: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
9: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#b30000"
"#7f0000"
]
}
{
name: 'YlOrRd'
range:
3: [
"#ffeda0"
"#feb24c"
"#f03b20"
]
4: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#e31a1c"
]
5: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
6: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
7: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
8: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
9: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#bd0026"
"#800026"
]
}
{
name: 'YlOrBr'
range:
3: [
"#fff7bc"
"#fec44f"
"#d95f0e"
]
4: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#cc4c02"
]
5: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#d95f0e"
"#993404"
]
6: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#d95f0e"
"#993404"
]
7: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
8: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
9: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#993404"
"#662506"
]
}
{
name: '<NAME>'
range:
3: [
"#efedf5"
"#bcbddc"
"#756bb1"
]
4: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#6a51a3"
]
5: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#756bb1"
"#54278f"
]
6: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#756bb1"
"#54278f"
]
7: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
8: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
9: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#54278f"
"#3f007d"
]
}
{
name: '<NAME>'
range:
3: [
"#deebf7"
"#9ecae1"
"#3182bd"
]
4: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#2171b5"
]
5: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#3182bd"
"#08519c"
]
6: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#3182bd"
"#08519c"
]
7: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
8: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
9: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#08519c"
"#08306b"
]
}
{
name: '<NAME>'
range:
3: [
"#e5f5e0"
"#a1d99b"
"#31a354"
]
4: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#238b45"
]
5: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#31a354"
"#006d2c"
]
6: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#31a354"
"#006d2c"
]
7: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
8: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
9: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: 'Oranges'
range:
3: [
"#fee6ce"
"#fdae6b"
"#e6550d"
]
4: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#d94701"
]
5: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#e6550d"
"#a63603"
]
6: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#e6550d"
"#a63603"
]
7: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
8: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
9: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#a63603"
"#7f2704"
]
}
{
name: '<NAME>'
range:
3: [
"#fee0d2"
"#fc9272"
"#de2d26"
]
4: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#cb181d"
]
5: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
6: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
7: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
8: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
9: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#a50f15"
"#67000d"
]
}
{
name: '<NAME>'
range:
3: [
"#f0f0f0"
"#bdbdbd"
"#636363"
]
4: [
"#f7f7f7"
"#cccccc"
"#969696"
"#525252"
]
5: [
"#f7f7f7"
"#cccccc"
"#969696"
"#636363"
"#252525"
]
6: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#636363"
"#252525"
]
7: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
8: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
9: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
"#000000"
]
}
{
name: 'PuOr'
range:
3: [
"#f1a340"
"#f7f7f7"
"#998ec3"
]
4: [
"#e66101"
"#fdb863"
"#b2abd2"
"#5e3c99"
]
5: [
"#e66101"
"#fdb863"
"#f7f7f7"
"#b2abd2"
"#5e3c99"
]
6: [
"#b35806"
"#f1a340"
"#fee0b6"
"#d8daeb"
"#998ec3"
"#542788"
]
7: [
"#b35806"
"#f1a340"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#998ec3"
"#542788"
]
8: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
9: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
10: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
11: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
}
{
name: '<NAME>'
range:
3: [
"#d8b365"
"#f5f5f5"
"#5ab4ac"
]
4: [
"#a6611a"
"#dfc27d"
"#80cdc1"
"#018571"
]
5: [
"#a6611a"
"#dfc27d"
"#f5f5f5"
"#80cdc1"
"#018571"
]
6: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
7: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
8: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
9: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
10: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
11: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
}
{
name: 'PRGn'
range:
3: [
"#af8dc3"
"#f7f7f7"
"#7fbf7b"
]
4: [
"#7b3294"
"#c2a5cf"
"#a6dba0"
"#008837"
]
5: [
"#7b3294"
"#c2a5cf"
"#f7f7f7"
"#a6dba0"
"#008837"
]
6: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
7: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
8: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
9: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
10: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
11: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
}
{
name: 'PiYG'
range:
3: [
"#e9a3c9"
"#f7f7f7"
"#a1d76a"
]
4: [
"#d01c8b"
"#f1b6da"
"#b8e186"
"#4dac26"
]
5: [
"#d01c8b"
"#f1b6da"
"#f7f7f7"
"#b8e186"
"#4dac26"
]
6: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
7: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
8: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
9: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
10: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
11: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
}
{
name: '<NAME>'
range:
3: [
"#ef8a62"
"#f7f7f7"
"#67a9cf"
]
4: [
"#ca0020"
"#f4a582"
"#92c5de"
"#0571b0"
]
5: [
"#ca0020"
"#f4a582"
"#f7f7f7"
"#92c5de"
"#0571b0"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
}
{
name: 'RdGy'
range:
3: [
"#ef8a62"
"#ffffff"
"#999999"
]
4: [
"#ca0020"
"#f4a582"
"#bababa"
"#404040"
]
5: [
"#ca0020"
"#f4a582"
"#ffffff"
"#bababa"
"#404040"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
}
{
name: 'RdYlBu'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91bfdb"
]
4: [
"#d7191c"
"#fdae61"
"#abd9e9"
"#2c7bb6"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abd9e9"
"#2c7bb6"
]
6: [
"#d73027"
"#fc8d59"
"#fee090"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
7: [
"#d73027"
"#fc8d59"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
}
{
name: 'Spectral'
range:
3: [
"#fc8d59"
"#ffffbf"
"#99d594"
]
4: [
"#d7191c"
"#fdae61"
"#abdda4"
"#2b83ba"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abdda4"
"#2b83ba"
]
6: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#e6f598"
"#99d594"
"#3288bd"
]
7: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#e6f598"
"#99d594"
"#3288bd"
]
8: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
9: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
10: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
11: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
}
{
name: '<NAME>'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91cf60"
]
4: [
"#d7191c"
"#fdae61"
"#a6d96a"
"#1a9641"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#a6d96a"
"#1a9641"
]
6: [
"#d73027"
"#fc8d59"
"#fee08b"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
7: [
"#d73027"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
}
{
name: 'Accent'
range:
3: [
"#7fc97f"
"#beaed4"
"#fdc086"
]
4: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
]
5: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
]
6: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
]
7: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
]
8: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
"#666666"
]
}
{
name: 'Dark2'
range:
3: [
"#1b9e77"
"#d95f02"
"#7570b3"
]
4: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
]
5: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
]
6: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
]
7: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
]
8: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
"#666666"
]
}
{
name: '<NAME>'
range:
3: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
]
4: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
]
5: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
]
6: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
]
7: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
]
8: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
]
9: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
]
10: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
]
11: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
]
12: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
"#b15928"
]
}
{
name: '<NAME>'
range:
3: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
]
4: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
]
5: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
]
6: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
]
7: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
]
8: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
]
9: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
"#f2f2f2"
]
}
{
name: 'Pastel2'
range:
3: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
]
4: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
]
5: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
]
6: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
]
7: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
]
8: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
"#cccccc"
]
}
{
name: 'Set1'
range:
3: [
"#e41a1c"
"#377eb8"
"#4daf4a"
]
4: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
]
5: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
]
6: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
]
7: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
]
8: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
]
9: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
"#999999"
]
}
{
name: 'Set2'
range:
3: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
]
4: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
]
5: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
]
6: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
]
7: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
]
8: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
"#b3b3b3"
]
}
{
name: 'Set3'
range:
3: [
"#8dd3c7"
"#ffffb3"
"#bebada"
]
4: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
]
5: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
]
6: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
]
7: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
]
8: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
]
9: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
]
10: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
]
11: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
]
12: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
"#ffed6f"
]
}
]
| true | angular.module('colorBrewer').factory 'palettes', ->
[
{
name: 'YlGn'
range:
3: [
"#f7fcb9"
"#addd8e"
"#31a354"
]
4: [
"#ffffcc"
"#c2e699"
"#78c679"
"#238443"
]
5: [
"#ffffcc"
"#c2e699"
"#78c679"
"#31a354"
"#006837"
]
6: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#31a354"
"#006837"
]
7: [
"#ffffcc"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
8: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#005a32"
]
9: [
"#ffffe5"
"#f7fcb9"
"#d9f0a3"
"#addd8e"
"#78c679"
"#41ab5d"
"#238443"
"#006837"
"#004529"
]
}
{
name: 'YlGnBu'
range:
3: [
"#edf8b1"
"#7fcdbb"
"#2c7fb8"
]
4: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#225ea8"
]
5: [
"#ffffcc"
"#a1dab4"
"#41b6c4"
"#2c7fb8"
"#253494"
]
6: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#2c7fb8"
"#253494"
]
7: [
"#ffffcc"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
8: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#0c2c84"
]
9: [
"#ffffd9"
"#edf8b1"
"#c7e9b4"
"#7fcdbb"
"#41b6c4"
"#1d91c0"
"#225ea8"
"#253494"
"#081d58"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#e0f3db"
"#a8ddb5"
"#43a2ca"
]
4: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#2b8cbe"
]
5: [
"#f0f9e8"
"#bae4bc"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
6: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#43a2ca"
"#0868ac"
]
7: [
"#f0f9e8"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
8: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#08589e"
]
9: [
"#f7fcf0"
"#e0f3db"
"#ccebc5"
"#a8ddb5"
"#7bccc4"
"#4eb3d3"
"#2b8cbe"
"#0868ac"
"#084081"
]
}
{
name: 'BuGn'
range:
3: [
"#e5f5f9"
"#99d8c9"
"#2ca25f"
]
4: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#238b45"
]
5: [
"#edf8fb"
"#b2e2e2"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
6: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#2ca25f"
"#006d2c"
]
7: [
"#edf8fb"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
8: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#005824"
]
9: [
"#f7fcfd"
"#e5f5f9"
"#ccece6"
"#99d8c9"
"#66c2a4"
"#41ae76"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: 'PI:NAME:<NAME>END_PIBuGn'
range:
3: [
"#ece2f0"
"#a6bddb"
"#1c9099"
]
4: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#02818a"
]
5: [
"#f6eff7"
"#bdc9e1"
"#67a9cf"
"#1c9099"
"#016c59"
]
6: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#1c9099"
"#016c59"
]
7: [
"#f6eff7"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
8: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016450"
]
9: [
"#fff7fb"
"#ece2f0"
"#d0d1e6"
"#a6bddb"
"#67a9cf"
"#3690c0"
"#02818a"
"#016c59"
"#014636"
]
}
{
name: 'PI:NAME:<NAME>END_PIBu'
range:
3: [
"#ece7f2"
"#a6bddb"
"#2b8cbe"
]
4: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#0570b0"
]
5: [
"#f1eef6"
"#bdc9e1"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
6: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#2b8cbe"
"#045a8d"
]
7: [
"#f1eef6"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
8: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#034e7b"
]
9: [
"#fff7fb"
"#ece7f2"
"#d0d1e6"
"#a6bddb"
"#74a9cf"
"#3690c0"
"#0570b0"
"#045a8d"
"#023858"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#e0ecf4"
"#9ebcda"
"#8856a7"
]
4: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#88419d"
]
5: [
"#edf8fb"
"#b3cde3"
"#8c96c6"
"#8856a7"
"#810f7c"
]
6: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8856a7"
"#810f7c"
]
7: [
"#edf8fb"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
8: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#6e016b"
]
9: [
"#f7fcfd"
"#e0ecf4"
"#bfd3e6"
"#9ebcda"
"#8c96c6"
"#8c6bb1"
"#88419d"
"#810f7c"
"#4d004b"
]
}
{
name: 'RdPu'
range:
3: [
"#fde0dd"
"#fa9fb5"
"#c51b8a"
]
4: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#ae017e"
]
5: [
"#feebe2"
"#fbb4b9"
"#f768a1"
"#c51b8a"
"#7a0177"
]
6: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#c51b8a"
"#7a0177"
]
7: [
"#feebe2"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
8: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
]
9: [
"#fff7f3"
"#fde0dd"
"#fcc5c0"
"#fa9fb5"
"#f768a1"
"#dd3497"
"#ae017e"
"#7a0177"
"#49006a"
]
}
{
name: 'PuRd'
range:
3: [
"#e7e1ef"
"#c994c7"
"#dd1c77"
]
4: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#ce1256"
]
5: [
"#f1eef6"
"#d7b5d8"
"#df65b0"
"#dd1c77"
"#980043"
]
6: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#dd1c77"
"#980043"
]
7: [
"#f1eef6"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
8: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#91003f"
]
9: [
"#f7f4f9"
"#e7e1ef"
"#d4b9da"
"#c994c7"
"#df65b0"
"#e7298a"
"#ce1256"
"#980043"
"#67001f"
]
}
{
name: 'OrRd'
range:
3: [
"#fee8c8"
"#fdbb84"
"#e34a33"
]
4: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#d7301f"
]
5: [
"#fef0d9"
"#fdcc8a"
"#fc8d59"
"#e34a33"
"#b30000"
]
6: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#e34a33"
"#b30000"
]
7: [
"#fef0d9"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
8: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#990000"
]
9: [
"#fff7ec"
"#fee8c8"
"#fdd49e"
"#fdbb84"
"#fc8d59"
"#ef6548"
"#d7301f"
"#b30000"
"#7f0000"
]
}
{
name: 'YlOrRd'
range:
3: [
"#ffeda0"
"#feb24c"
"#f03b20"
]
4: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#e31a1c"
]
5: [
"#ffffb2"
"#fecc5c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
6: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#f03b20"
"#bd0026"
]
7: [
"#ffffb2"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
8: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#b10026"
]
9: [
"#ffffcc"
"#ffeda0"
"#fed976"
"#feb24c"
"#fd8d3c"
"#fc4e2a"
"#e31a1c"
"#bd0026"
"#800026"
]
}
{
name: 'YlOrBr'
range:
3: [
"#fff7bc"
"#fec44f"
"#d95f0e"
]
4: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#cc4c02"
]
5: [
"#ffffd4"
"#fed98e"
"#fe9929"
"#d95f0e"
"#993404"
]
6: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#d95f0e"
"#993404"
]
7: [
"#ffffd4"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
8: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#8c2d04"
]
9: [
"#ffffe5"
"#fff7bc"
"#fee391"
"#fec44f"
"#fe9929"
"#ec7014"
"#cc4c02"
"#993404"
"#662506"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#efedf5"
"#bcbddc"
"#756bb1"
]
4: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#6a51a3"
]
5: [
"#f2f0f7"
"#cbc9e2"
"#9e9ac8"
"#756bb1"
"#54278f"
]
6: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#756bb1"
"#54278f"
]
7: [
"#f2f0f7"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
8: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#4a1486"
]
9: [
"#fcfbfd"
"#efedf5"
"#dadaeb"
"#bcbddc"
"#9e9ac8"
"#807dba"
"#6a51a3"
"#54278f"
"#3f007d"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#deebf7"
"#9ecae1"
"#3182bd"
]
4: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#2171b5"
]
5: [
"#eff3ff"
"#bdd7e7"
"#6baed6"
"#3182bd"
"#08519c"
]
6: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#3182bd"
"#08519c"
]
7: [
"#eff3ff"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
8: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#084594"
]
9: [
"#f7fbff"
"#deebf7"
"#c6dbef"
"#9ecae1"
"#6baed6"
"#4292c6"
"#2171b5"
"#08519c"
"#08306b"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#e5f5e0"
"#a1d99b"
"#31a354"
]
4: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#238b45"
]
5: [
"#edf8e9"
"#bae4b3"
"#74c476"
"#31a354"
"#006d2c"
]
6: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#31a354"
"#006d2c"
]
7: [
"#edf8e9"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
8: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#005a32"
]
9: [
"#f7fcf5"
"#e5f5e0"
"#c7e9c0"
"#a1d99b"
"#74c476"
"#41ab5d"
"#238b45"
"#006d2c"
"#00441b"
]
}
{
name: 'Oranges'
range:
3: [
"#fee6ce"
"#fdae6b"
"#e6550d"
]
4: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#d94701"
]
5: [
"#feedde"
"#fdbe85"
"#fd8d3c"
"#e6550d"
"#a63603"
]
6: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#e6550d"
"#a63603"
]
7: [
"#feedde"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
8: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#8c2d04"
]
9: [
"#fff5eb"
"#fee6ce"
"#fdd0a2"
"#fdae6b"
"#fd8d3c"
"#f16913"
"#d94801"
"#a63603"
"#7f2704"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#fee0d2"
"#fc9272"
"#de2d26"
]
4: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#cb181d"
]
5: [
"#fee5d9"
"#fcae91"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
6: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#de2d26"
"#a50f15"
]
7: [
"#fee5d9"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
8: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#99000d"
]
9: [
"#fff5f0"
"#fee0d2"
"#fcbba1"
"#fc9272"
"#fb6a4a"
"#ef3b2c"
"#cb181d"
"#a50f15"
"#67000d"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#f0f0f0"
"#bdbdbd"
"#636363"
]
4: [
"#f7f7f7"
"#cccccc"
"#969696"
"#525252"
]
5: [
"#f7f7f7"
"#cccccc"
"#969696"
"#636363"
"#252525"
]
6: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#636363"
"#252525"
]
7: [
"#f7f7f7"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
8: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
]
9: [
"#ffffff"
"#f0f0f0"
"#d9d9d9"
"#bdbdbd"
"#969696"
"#737373"
"#525252"
"#252525"
"#000000"
]
}
{
name: 'PuOr'
range:
3: [
"#f1a340"
"#f7f7f7"
"#998ec3"
]
4: [
"#e66101"
"#fdb863"
"#b2abd2"
"#5e3c99"
]
5: [
"#e66101"
"#fdb863"
"#f7f7f7"
"#b2abd2"
"#5e3c99"
]
6: [
"#b35806"
"#f1a340"
"#fee0b6"
"#d8daeb"
"#998ec3"
"#542788"
]
7: [
"#b35806"
"#f1a340"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#998ec3"
"#542788"
]
8: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
9: [
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
]
10: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
11: [
"#7f3b08"
"#b35806"
"#e08214"
"#fdb863"
"#fee0b6"
"#f7f7f7"
"#d8daeb"
"#b2abd2"
"#8073ac"
"#542788"
"#2d004b"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#d8b365"
"#f5f5f5"
"#5ab4ac"
]
4: [
"#a6611a"
"#dfc27d"
"#80cdc1"
"#018571"
]
5: [
"#a6611a"
"#dfc27d"
"#f5f5f5"
"#80cdc1"
"#018571"
]
6: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
7: [
"#8c510a"
"#d8b365"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#5ab4ac"
"#01665e"
]
8: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
9: [
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
]
10: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
11: [
"#543005"
"#8c510a"
"#bf812d"
"#dfc27d"
"#f6e8c3"
"#f5f5f5"
"#c7eae5"
"#80cdc1"
"#35978f"
"#01665e"
"#003c30"
]
}
{
name: 'PRGn'
range:
3: [
"#af8dc3"
"#f7f7f7"
"#7fbf7b"
]
4: [
"#7b3294"
"#c2a5cf"
"#a6dba0"
"#008837"
]
5: [
"#7b3294"
"#c2a5cf"
"#f7f7f7"
"#a6dba0"
"#008837"
]
6: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
7: [
"#762a83"
"#af8dc3"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#7fbf7b"
"#1b7837"
]
8: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
9: [
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
]
10: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
11: [
"#40004b"
"#762a83"
"#9970ab"
"#c2a5cf"
"#e7d4e8"
"#f7f7f7"
"#d9f0d3"
"#a6dba0"
"#5aae61"
"#1b7837"
"#00441b"
]
}
{
name: 'PiYG'
range:
3: [
"#e9a3c9"
"#f7f7f7"
"#a1d76a"
]
4: [
"#d01c8b"
"#f1b6da"
"#b8e186"
"#4dac26"
]
5: [
"#d01c8b"
"#f1b6da"
"#f7f7f7"
"#b8e186"
"#4dac26"
]
6: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
7: [
"#c51b7d"
"#e9a3c9"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#a1d76a"
"#4d9221"
]
8: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
9: [
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
]
10: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
11: [
"#8e0152"
"#c51b7d"
"#de77ae"
"#f1b6da"
"#fde0ef"
"#f7f7f7"
"#e6f5d0"
"#b8e186"
"#7fbc41"
"#4d9221"
"#276419"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#ef8a62"
"#f7f7f7"
"#67a9cf"
]
4: [
"#ca0020"
"#f4a582"
"#92c5de"
"#0571b0"
]
5: [
"#ca0020"
"#f4a582"
"#f7f7f7"
"#92c5de"
"#0571b0"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#67a9cf"
"#2166ac"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#f7f7f7"
"#d1e5f0"
"#92c5de"
"#4393c3"
"#2166ac"
"#053061"
]
}
{
name: 'RdGy'
range:
3: [
"#ef8a62"
"#ffffff"
"#999999"
]
4: [
"#ca0020"
"#f4a582"
"#bababa"
"#404040"
]
5: [
"#ca0020"
"#f4a582"
"#ffffff"
"#bababa"
"#404040"
]
6: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
7: [
"#b2182b"
"#ef8a62"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#999999"
"#4d4d4d"
]
8: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
9: [
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
]
10: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
11: [
"#67001f"
"#b2182b"
"#d6604d"
"#f4a582"
"#fddbc7"
"#ffffff"
"#e0e0e0"
"#bababa"
"#878787"
"#4d4d4d"
"#1a1a1a"
]
}
{
name: 'RdYlBu'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91bfdb"
]
4: [
"#d7191c"
"#fdae61"
"#abd9e9"
"#2c7bb6"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abd9e9"
"#2c7bb6"
]
6: [
"#d73027"
"#fc8d59"
"#fee090"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
7: [
"#d73027"
"#fc8d59"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#91bfdb"
"#4575b4"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee090"
"#ffffbf"
"#e0f3f8"
"#abd9e9"
"#74add1"
"#4575b4"
"#313695"
]
}
{
name: 'Spectral'
range:
3: [
"#fc8d59"
"#ffffbf"
"#99d594"
]
4: [
"#d7191c"
"#fdae61"
"#abdda4"
"#2b83ba"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#abdda4"
"#2b83ba"
]
6: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#e6f598"
"#99d594"
"#3288bd"
]
7: [
"#d53e4f"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#e6f598"
"#99d594"
"#3288bd"
]
8: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
9: [
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
]
10: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
11: [
"#9e0142"
"#d53e4f"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#e6f598"
"#abdda4"
"#66c2a5"
"#3288bd"
"#5e4fa2"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#fc8d59"
"#ffffbf"
"#91cf60"
]
4: [
"#d7191c"
"#fdae61"
"#a6d96a"
"#1a9641"
]
5: [
"#d7191c"
"#fdae61"
"#ffffbf"
"#a6d96a"
"#1a9641"
]
6: [
"#d73027"
"#fc8d59"
"#fee08b"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
7: [
"#d73027"
"#fc8d59"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#91cf60"
"#1a9850"
]
8: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
9: [
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
]
10: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
11: [
"#a50026"
"#d73027"
"#f46d43"
"#fdae61"
"#fee08b"
"#ffffbf"
"#d9ef8b"
"#a6d96a"
"#66bd63"
"#1a9850"
"#006837"
]
}
{
name: 'Accent'
range:
3: [
"#7fc97f"
"#beaed4"
"#fdc086"
]
4: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
]
5: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
]
6: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
]
7: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
]
8: [
"#7fc97f"
"#beaed4"
"#fdc086"
"#ffff99"
"#386cb0"
"#f0027f"
"#bf5b17"
"#666666"
]
}
{
name: 'Dark2'
range:
3: [
"#1b9e77"
"#d95f02"
"#7570b3"
]
4: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
]
5: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
]
6: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
]
7: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
]
8: [
"#1b9e77"
"#d95f02"
"#7570b3"
"#e7298a"
"#66a61e"
"#e6ab02"
"#a6761d"
"#666666"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
]
4: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
]
5: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
]
6: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
]
7: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
]
8: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
]
9: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
]
10: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
]
11: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
]
12: [
"#a6cee3"
"#1f78b4"
"#b2df8a"
"#33a02c"
"#fb9a99"
"#e31a1c"
"#fdbf6f"
"#ff7f00"
"#cab2d6"
"#6a3d9a"
"#ffff99"
"#b15928"
]
}
{
name: 'PI:NAME:<NAME>END_PI'
range:
3: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
]
4: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
]
5: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
]
6: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
]
7: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
]
8: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
]
9: [
"#fbb4ae"
"#b3cde3"
"#ccebc5"
"#decbe4"
"#fed9a6"
"#ffffcc"
"#e5d8bd"
"#fddaec"
"#f2f2f2"
]
}
{
name: 'Pastel2'
range:
3: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
]
4: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
]
5: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
]
6: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
]
7: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
]
8: [
"#b3e2cd"
"#fdcdac"
"#cbd5e8"
"#f4cae4"
"#e6f5c9"
"#fff2ae"
"#f1e2cc"
"#cccccc"
]
}
{
name: 'Set1'
range:
3: [
"#e41a1c"
"#377eb8"
"#4daf4a"
]
4: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
]
5: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
]
6: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
]
7: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
]
8: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
]
9: [
"#e41a1c"
"#377eb8"
"#4daf4a"
"#984ea3"
"#ff7f00"
"#ffff33"
"#a65628"
"#f781bf"
"#999999"
]
}
{
name: 'Set2'
range:
3: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
]
4: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
]
5: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
]
6: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
]
7: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
]
8: [
"#66c2a5"
"#fc8d62"
"#8da0cb"
"#e78ac3"
"#a6d854"
"#ffd92f"
"#e5c494"
"#b3b3b3"
]
}
{
name: 'Set3'
range:
3: [
"#8dd3c7"
"#ffffb3"
"#bebada"
]
4: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
]
5: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
]
6: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
]
7: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
]
8: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
]
9: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
]
10: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
]
11: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
]
12: [
"#8dd3c7"
"#ffffb3"
"#bebada"
"#fb8072"
"#80b1d3"
"#fdb462"
"#b3de69"
"#fccde5"
"#d9d9d9"
"#bc80bd"
"#ccebc5"
"#ffed6f"
]
}
]
|
[
{
"context": "entage: 0\n vat_percentage: 20\n company_name: 'Toggl OU'\n company_address: 'Rävala 8'\n contact_person: ",
"end": 376,
"score": 0.6610127091407776,
"start": 370,
"tag": "NAME",
"value": "ggl OU"
},
{
"context": "\n company_address: 'Rävala 8'\n contact_person: 'Toggl employee'\n vat_number: 'EE12345678'\n\ninvoice.output(fs.cr",
"end": 441,
"score": 0.994088888168335,
"start": 427,
"tag": "NAME",
"value": "Toggl employee"
}
] | testdata/test_invoice.coffee | meeDamian/toggl-pdf | 1 | Invoice = require '../app/invoice'
fs = require 'fs'
invoice = new Invoice
id: 142250
description: 'Description'
amount_in_usd: 135
subscription_from: new Date
subscription_to: new Date
users_in_workspace: 5
paid_at: null
profile: 13
cancelled_at: null
created_at: 'October 10, 2013'
discount_percentage: 0
vat_percentage: 20
company_name: 'Toggl OU'
company_address: 'Rävala 8'
contact_person: 'Toggl employee'
vat_number: 'EE12345678'
invoice.output(fs.createWriteStream('invoice.pdf'))
| 34541 | Invoice = require '../app/invoice'
fs = require 'fs'
invoice = new Invoice
id: 142250
description: 'Description'
amount_in_usd: 135
subscription_from: new Date
subscription_to: new Date
users_in_workspace: 5
paid_at: null
profile: 13
cancelled_at: null
created_at: 'October 10, 2013'
discount_percentage: 0
vat_percentage: 20
company_name: 'To<NAME>'
company_address: 'Rävala 8'
contact_person: '<NAME>'
vat_number: 'EE12345678'
invoice.output(fs.createWriteStream('invoice.pdf'))
| true | Invoice = require '../app/invoice'
fs = require 'fs'
invoice = new Invoice
id: 142250
description: 'Description'
amount_in_usd: 135
subscription_from: new Date
subscription_to: new Date
users_in_workspace: 5
paid_at: null
profile: 13
cancelled_at: null
created_at: 'October 10, 2013'
discount_percentage: 0
vat_percentage: 20
company_name: 'ToPI:NAME:<NAME>END_PI'
company_address: 'Rävala 8'
contact_person: 'PI:NAME:<NAME>END_PI'
vat_number: 'EE12345678'
invoice.output(fs.createWriteStream('invoice.pdf'))
|
[
{
"context": "shop = {\n owner: new Person \"KeiSei\" \n animals: Animal.loadSeedData()\n featured: [\"",
"end": 36,
"score": 0.9782439470291138,
"start": 30,
"tag": "NAME",
"value": "KeiSei"
}
] | src/setup.coffee | keisei77/coffee_demo | 0 | shop = {
owner: new Person "KeiSei"
animals: Animal.loadSeedData()
featured: ["Chupa", "Kelsey", "Flops"]
}
petViews = (new PetView pet for pet in shop.animals)
petListView = new PetListView petViews, shop.featured
mainView = new ShopView shop.owner, petListView
mainView.render() | 157655 | shop = {
owner: new Person "<NAME>"
animals: Animal.loadSeedData()
featured: ["Chupa", "Kelsey", "Flops"]
}
petViews = (new PetView pet for pet in shop.animals)
petListView = new PetListView petViews, shop.featured
mainView = new ShopView shop.owner, petListView
mainView.render() | true | shop = {
owner: new Person "PI:NAME:<NAME>END_PI"
animals: Animal.loadSeedData()
featured: ["Chupa", "Kelsey", "Flops"]
}
petViews = (new PetView pet for pet in shop.animals)
petListView = new PetListView petViews, shop.featured
mainView = new ShopView shop.owner, petListView
mainView.render() |
[
{
"context": " mixin-js-subscriptions.js 0.1.5\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/\n License: M",
"end": 69,
"score": 0.9998294115066528,
"start": 55,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": "js 0.1.5\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/\n License: MIT (http://www.open",
"end": 88,
"score": 0.9952394366264343,
"start": 79,
"tag": "USERNAME",
"value": "kmalakoff"
}
] | src/lib/mixin-js-subscriptions.coffee | kmalakoff/mixin | 14 | ###
mixin-js-subscriptions.js 0.1.5
(c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Mixin.Core
###
####################################################
# Classes
# options:
# destroy -> calls you back when link is destroyed
# keep_until_destroyed -> overrides the Mixin.Subscription.TYPE.EXCLUSIVE flag
####################################################
Mixin.Subscriptions or= {}
class Mixin.Subscriptions._SubscriptionLink
constructor: (@subscription, @subscriber, @notification_callback, options) ->
@options = _.clone(options||{})
# register the back link
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
subscriber_instance_data.subscription_backlinks.push(@) # store us so they can remove us if they are destroyed
mustKeepUntilDestroyed: -> return ((@options.keep_until_destroyed==undefined) or not @options.keep_until_destroyed)
destroy: ->
throw new Error("Mixin.Subscriptions: _SubscriptionLink destroyed multiple times") if not @subscription # already destroyed
(@options.destroy(); @options.destroy=null) if @options.destroy
# unregister back links
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
_.remove(subscriber_instance_data.subscription_backlinks, @)
# remove from subscription - it won't exist if destroy called by the subscription destroy
_.remove(@subscription.subscription_links, @)
@subscription = null
@subscriber = null
@notification_callback = null
@options = null
Mixin.Subscription||Mixin.Subscription={}
Mixin.Subscription.TYPE = {}
Mixin.Subscription.TYPE.MULTIPLE = 0
Mixin.Subscription.TYPE.EXCLUSIVE = 1
class Mixin.Subscriptions._Subscription
constructor: (@observable, @subscription_type) ->
if Mixin.DEBUG
throw new Error("Mixin.Subscriptions: Mixin.Subscription.TYPE is invalid") if (typeof(@subscription_type) != 'number') or (@subscription_type<Mixin.Subscription.TYPE.MULTIPLE) or (@subscription_type>Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links = []
addSubscriber: (subscriber, notification_callback, options) ->
@removeSubscribers((test_subscription)-> return test_subscription.mustKeepUntilDestroyed()) if (@subscription_type==Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links.push(new Mixin.Subscriptions._SubscriptionLink(@, subscriber, notification_callback, options))
removeSubscriber: (subscriber, notification_callback, subscription_name) ->
subscription_link = _.find(@subscription_links, (test) -> return (subscriber==test.subscriber) and (notification_callback==test.notification_callback))
throw new Error("Mixin.Subscriptions.removeSubscriber: subscription '#{subscription_name}' does not exist for '#{_.classOf(subscriber)}'") if not subscription_link
_.remove(@subscription_links, subscription_link)
subscription_link.destroy()
subscribers: (subscribers) ->
subscribers.push(subscription_link.subscriber) for subscription_link in @subscription_links
return
notifySubscribers: ->
args = Array.prototype.slice.call(arguments)
subscription_link.notification_callback.apply(subscription_link.subscriber, args) for subscription_link in @subscription_links
return
removeSubscribers: (test_fn) ->
if (test_fn)
removed_subscription_links = _.select(@subscription_links, test_fn)
return if (removed_subscription_links.length == 0)
@subscription_links = _.difference(@subscription_links, removed_subscription_links)
subscription_link.destroy() for subscription_link in removed_subscription_links
else
removed_subscription_links = @subscription_links
@subscription_links = []
subscription_link.destroy() for subscription_link in removed_subscription_links
return
destroy: ->
subscription_links = @subscription_links; @subscription_links = []
link.destroy() for link in subscription_links
return
Mixin.Subscriptions.Observable||Mixin.Subscriptions.Observable={}
Mixin.Subscriptions.Observable._mixin_info =
mixin_name: 'Observable'
initialize: ->
Mixin.instanceData(@, 'Observable', {subscriptions: {}, is_destroyed: false})
(@publishSubscription.apply(@, if _.isArray(arg) then arg else [arg])) for arg in arguments
return
destroy: ->
instance_data = Mixin.instanceData(@, 'Observable')
throw new Error("Mixin.Observable.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
subscriptions = instance_data.subscriptions; instance_data.subscriptions = []
subscription.destroy() for subscription in subscriptions # clear all of the subscriptions to me
return
mixin_object: {
hasSubscription: (subscription_name) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.hasSubscription', 'subscription_name')
instance_data = Mixin.instanceData(@, 'Observable')
return (instance_data.subscriptions.hasOwnProperty(subscription_name))
publishSubscription: (subscription_name, subscription_type) ->
instance_data = Mixin.instanceData(@, 'Observable')
subscription_type = Mixin.Subscription.TYPE.MULTIPLE if (subscription_type == undefined)
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
Mixin.Core._Validate.noKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
instance_data.subscriptions[subscription_name] = new Mixin.Subscriptions._Subscription(@, subscription_type)
return @
subscriptions: ->
instance_data = Mixin.instanceData(@, 'Observable')
subscriptions = []; subscriptions.push(key) for key, value of instance_data.subscriptions
return subscriptions
subscribers: (subscription_name) ->
subscribers = []
instance_data = Mixin.instanceData(@, 'Observable')
if subscription_name==undefined
subscription.subscribers(subscribers) for key, subscription of instance_data.subscriptions
else
throw new Error("Mixin.Observable.subscribers: subscriber '#{_classOf(@)}' does not recognize '#{subscription_name}'") if not instance_data.subscriptions.hasOwnProperty(subscription_name)
(subscription.subscribers(subscribers) if (subscription.subscription_name==subscription_name)) for key, subscription of instance_data.subscriptions
return _.uniq(subscribers)
# Accepts forms:
# subscriber, subscription1, subscription2
# subscriber, [subscription1, param1, etc], subscription2
addSubscriber: (subscriber, subscription_parameters) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doSubscribe = (subscription_name, notification_callback, options) ->
options||options={}
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.addSubscriber', 'notification_callback')
Mixin.Core._Validate.object(options, 'Mixin.Observable.addSubscriber', 'options')
Mixin.Core._Validate.callback(options.destroy, 'Mixin.Observable.addSubscriber', 'options.destroy') if (options.destroy!=undefined)
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.addSubscriber(subscriber, notification_callback, options)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.addSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doSubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doSubscribe.apply(@, parameter) else _doSubscribe.apply(parameter)) for parameter in args
return @
notifySubscribers: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Observable')
return if instance_data.is_destroyed
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.notifySubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.notifySubscribers')
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.notifySubscribers.apply(subscription, Array.prototype.slice.call(arguments,1))
return @
removeSubscriber: (subscriber, subscription_name, notification_callback) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doUnsubscribe = (subscription_name, notification_callback) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.removeSubscriber', 'notification_callback')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.removeSubscriber(subscriber, notification_callback, subscription_name)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
if Mixin.DEBUG
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.removeSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doUnsubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doUnsubscribe.apply(@, parameter) else _doUnsubscribe.apply(parameter)) for parameter in args
return @
removeSubscribers: (subscription_name, test_fn) ->
instance_data = Mixin.instanceData(@, 'Observable')
if Mixin.DEBUG
if (subscription_name!=undefined)
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscribers')
Mixin.Core._Validate.callback(test_fn, 'Mixin.Observable.removeSubscribers', 'test_fn') if (test_fn!=undefined)
if (subscription_name)
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.removeSubscribers(test_fn)
else
subscription.removeSubscribers(test_fn) for key, subscription of instance_data.subscriptions
return @
}
####################################################
# Mixin.Subscriber
# Usage:
####################################################
Mixin.Subscriptions.Subscriber||Mixin.Subscriptions.Subscriber={}
Mixin.Subscriptions.Subscriber._mixin_info =
mixin_name: 'Subscriber'
initialize: ->
Mixin.instanceData(@, 'Subscriber', {subscription_backlinks: [], is_destroyed: false})
destroy: ->
instance_data = Mixin.instanceData(@, 'Subscriber')
throw new Error("Mixin.Subscriber.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
backlinks = instance_data.subscription_backlinks; instance_data.subscription_backlinks = []
backlink.destroy() for backlink in backlinks # clear all of my subscriptions to others
return
mixin_object: {
observables: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Subscriber')
obserables = []
if (subscription_name==undefined)
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription and (subscription_link.subscription.subscription_name==subscription_name))) for subscription_link in instance_data.subscription_backlinks
else
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Subscriptions.observables', 'subscription_name')
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription)) for subscription_link in instance_data.subscription_backlinks
return _.uniq(obserables)
}
####################################################
# Mixin.ObservableSubscriber
# Usage:
####################################################
Mixin.Subscriptions.ObservableSubscriber||Mixin.Subscriptions.ObservableSubscriber={}
Mixin.Subscriptions.ObservableSubscriber._mixin_info =
mixin_name: 'ObservableSubscriber'
mixin_object: {}
initialize: -> Mixin.in(@, 'Subscriber', ['Observable'].concat(Array.prototype.slice.call(arguments)))
destroy: -> Mixin.out(@, 'Subscriber', 'Observable')
####################################################
# Make mixins available
####################################################
Mixin.registerMixin(Mixin.Subscriptions.Observable._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.Subscriber._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.ObservableSubscriber._mixin_info)
| 208123 | ###
mixin-js-subscriptions.js 0.1.5
(c) 2011, 2012 <NAME> - http://kmalakoff.github.com/mixin/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Mixin.Core
###
####################################################
# Classes
# options:
# destroy -> calls you back when link is destroyed
# keep_until_destroyed -> overrides the Mixin.Subscription.TYPE.EXCLUSIVE flag
####################################################
Mixin.Subscriptions or= {}
class Mixin.Subscriptions._SubscriptionLink
constructor: (@subscription, @subscriber, @notification_callback, options) ->
@options = _.clone(options||{})
# register the back link
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
subscriber_instance_data.subscription_backlinks.push(@) # store us so they can remove us if they are destroyed
mustKeepUntilDestroyed: -> return ((@options.keep_until_destroyed==undefined) or not @options.keep_until_destroyed)
destroy: ->
throw new Error("Mixin.Subscriptions: _SubscriptionLink destroyed multiple times") if not @subscription # already destroyed
(@options.destroy(); @options.destroy=null) if @options.destroy
# unregister back links
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
_.remove(subscriber_instance_data.subscription_backlinks, @)
# remove from subscription - it won't exist if destroy called by the subscription destroy
_.remove(@subscription.subscription_links, @)
@subscription = null
@subscriber = null
@notification_callback = null
@options = null
Mixin.Subscription||Mixin.Subscription={}
Mixin.Subscription.TYPE = {}
Mixin.Subscription.TYPE.MULTIPLE = 0
Mixin.Subscription.TYPE.EXCLUSIVE = 1
class Mixin.Subscriptions._Subscription
constructor: (@observable, @subscription_type) ->
if Mixin.DEBUG
throw new Error("Mixin.Subscriptions: Mixin.Subscription.TYPE is invalid") if (typeof(@subscription_type) != 'number') or (@subscription_type<Mixin.Subscription.TYPE.MULTIPLE) or (@subscription_type>Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links = []
addSubscriber: (subscriber, notification_callback, options) ->
@removeSubscribers((test_subscription)-> return test_subscription.mustKeepUntilDestroyed()) if (@subscription_type==Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links.push(new Mixin.Subscriptions._SubscriptionLink(@, subscriber, notification_callback, options))
removeSubscriber: (subscriber, notification_callback, subscription_name) ->
subscription_link = _.find(@subscription_links, (test) -> return (subscriber==test.subscriber) and (notification_callback==test.notification_callback))
throw new Error("Mixin.Subscriptions.removeSubscriber: subscription '#{subscription_name}' does not exist for '#{_.classOf(subscriber)}'") if not subscription_link
_.remove(@subscription_links, subscription_link)
subscription_link.destroy()
subscribers: (subscribers) ->
subscribers.push(subscription_link.subscriber) for subscription_link in @subscription_links
return
notifySubscribers: ->
args = Array.prototype.slice.call(arguments)
subscription_link.notification_callback.apply(subscription_link.subscriber, args) for subscription_link in @subscription_links
return
removeSubscribers: (test_fn) ->
if (test_fn)
removed_subscription_links = _.select(@subscription_links, test_fn)
return if (removed_subscription_links.length == 0)
@subscription_links = _.difference(@subscription_links, removed_subscription_links)
subscription_link.destroy() for subscription_link in removed_subscription_links
else
removed_subscription_links = @subscription_links
@subscription_links = []
subscription_link.destroy() for subscription_link in removed_subscription_links
return
destroy: ->
subscription_links = @subscription_links; @subscription_links = []
link.destroy() for link in subscription_links
return
Mixin.Subscriptions.Observable||Mixin.Subscriptions.Observable={}
Mixin.Subscriptions.Observable._mixin_info =
mixin_name: 'Observable'
initialize: ->
Mixin.instanceData(@, 'Observable', {subscriptions: {}, is_destroyed: false})
(@publishSubscription.apply(@, if _.isArray(arg) then arg else [arg])) for arg in arguments
return
destroy: ->
instance_data = Mixin.instanceData(@, 'Observable')
throw new Error("Mixin.Observable.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
subscriptions = instance_data.subscriptions; instance_data.subscriptions = []
subscription.destroy() for subscription in subscriptions # clear all of the subscriptions to me
return
mixin_object: {
hasSubscription: (subscription_name) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.hasSubscription', 'subscription_name')
instance_data = Mixin.instanceData(@, 'Observable')
return (instance_data.subscriptions.hasOwnProperty(subscription_name))
publishSubscription: (subscription_name, subscription_type) ->
instance_data = Mixin.instanceData(@, 'Observable')
subscription_type = Mixin.Subscription.TYPE.MULTIPLE if (subscription_type == undefined)
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
Mixin.Core._Validate.noKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
instance_data.subscriptions[subscription_name] = new Mixin.Subscriptions._Subscription(@, subscription_type)
return @
subscriptions: ->
instance_data = Mixin.instanceData(@, 'Observable')
subscriptions = []; subscriptions.push(key) for key, value of instance_data.subscriptions
return subscriptions
subscribers: (subscription_name) ->
subscribers = []
instance_data = Mixin.instanceData(@, 'Observable')
if subscription_name==undefined
subscription.subscribers(subscribers) for key, subscription of instance_data.subscriptions
else
throw new Error("Mixin.Observable.subscribers: subscriber '#{_classOf(@)}' does not recognize '#{subscription_name}'") if not instance_data.subscriptions.hasOwnProperty(subscription_name)
(subscription.subscribers(subscribers) if (subscription.subscription_name==subscription_name)) for key, subscription of instance_data.subscriptions
return _.uniq(subscribers)
# Accepts forms:
# subscriber, subscription1, subscription2
# subscriber, [subscription1, param1, etc], subscription2
addSubscriber: (subscriber, subscription_parameters) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doSubscribe = (subscription_name, notification_callback, options) ->
options||options={}
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.addSubscriber', 'notification_callback')
Mixin.Core._Validate.object(options, 'Mixin.Observable.addSubscriber', 'options')
Mixin.Core._Validate.callback(options.destroy, 'Mixin.Observable.addSubscriber', 'options.destroy') if (options.destroy!=undefined)
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.addSubscriber(subscriber, notification_callback, options)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.addSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doSubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doSubscribe.apply(@, parameter) else _doSubscribe.apply(parameter)) for parameter in args
return @
notifySubscribers: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Observable')
return if instance_data.is_destroyed
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.notifySubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.notifySubscribers')
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.notifySubscribers.apply(subscription, Array.prototype.slice.call(arguments,1))
return @
removeSubscriber: (subscriber, subscription_name, notification_callback) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doUnsubscribe = (subscription_name, notification_callback) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.removeSubscriber', 'notification_callback')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.removeSubscriber(subscriber, notification_callback, subscription_name)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
if Mixin.DEBUG
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.removeSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doUnsubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doUnsubscribe.apply(@, parameter) else _doUnsubscribe.apply(parameter)) for parameter in args
return @
removeSubscribers: (subscription_name, test_fn) ->
instance_data = Mixin.instanceData(@, 'Observable')
if Mixin.DEBUG
if (subscription_name!=undefined)
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscribers')
Mixin.Core._Validate.callback(test_fn, 'Mixin.Observable.removeSubscribers', 'test_fn') if (test_fn!=undefined)
if (subscription_name)
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.removeSubscribers(test_fn)
else
subscription.removeSubscribers(test_fn) for key, subscription of instance_data.subscriptions
return @
}
####################################################
# Mixin.Subscriber
# Usage:
####################################################
Mixin.Subscriptions.Subscriber||Mixin.Subscriptions.Subscriber={}
Mixin.Subscriptions.Subscriber._mixin_info =
mixin_name: 'Subscriber'
initialize: ->
Mixin.instanceData(@, 'Subscriber', {subscription_backlinks: [], is_destroyed: false})
destroy: ->
instance_data = Mixin.instanceData(@, 'Subscriber')
throw new Error("Mixin.Subscriber.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
backlinks = instance_data.subscription_backlinks; instance_data.subscription_backlinks = []
backlink.destroy() for backlink in backlinks # clear all of my subscriptions to others
return
mixin_object: {
observables: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Subscriber')
obserables = []
if (subscription_name==undefined)
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription and (subscription_link.subscription.subscription_name==subscription_name))) for subscription_link in instance_data.subscription_backlinks
else
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Subscriptions.observables', 'subscription_name')
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription)) for subscription_link in instance_data.subscription_backlinks
return _.uniq(obserables)
}
####################################################
# Mixin.ObservableSubscriber
# Usage:
####################################################
Mixin.Subscriptions.ObservableSubscriber||Mixin.Subscriptions.ObservableSubscriber={}
Mixin.Subscriptions.ObservableSubscriber._mixin_info =
mixin_name: 'ObservableSubscriber'
mixin_object: {}
initialize: -> Mixin.in(@, 'Subscriber', ['Observable'].concat(Array.prototype.slice.call(arguments)))
destroy: -> Mixin.out(@, 'Subscriber', 'Observable')
####################################################
# Make mixins available
####################################################
Mixin.registerMixin(Mixin.Subscriptions.Observable._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.Subscriber._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.ObservableSubscriber._mixin_info)
| true | ###
mixin-js-subscriptions.js 0.1.5
(c) 2011, 2012 PI:NAME:<NAME>END_PI - http://kmalakoff.github.com/mixin/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Mixin.Core
###
####################################################
# Classes
# options:
# destroy -> calls you back when link is destroyed
# keep_until_destroyed -> overrides the Mixin.Subscription.TYPE.EXCLUSIVE flag
####################################################
Mixin.Subscriptions or= {}
class Mixin.Subscriptions._SubscriptionLink
constructor: (@subscription, @subscriber, @notification_callback, options) ->
@options = _.clone(options||{})
# register the back link
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
subscriber_instance_data.subscription_backlinks.push(@) # store us so they can remove us if they are destroyed
mustKeepUntilDestroyed: -> return ((@options.keep_until_destroyed==undefined) or not @options.keep_until_destroyed)
destroy: ->
throw new Error("Mixin.Subscriptions: _SubscriptionLink destroyed multiple times") if not @subscription # already destroyed
(@options.destroy(); @options.destroy=null) if @options.destroy
# unregister back links
subscriber_instance_data = Mixin.instanceData(@subscriber, 'Subscriber')
_.remove(subscriber_instance_data.subscription_backlinks, @)
# remove from subscription - it won't exist if destroy called by the subscription destroy
_.remove(@subscription.subscription_links, @)
@subscription = null
@subscriber = null
@notification_callback = null
@options = null
Mixin.Subscription||Mixin.Subscription={}
Mixin.Subscription.TYPE = {}
Mixin.Subscription.TYPE.MULTIPLE = 0
Mixin.Subscription.TYPE.EXCLUSIVE = 1
class Mixin.Subscriptions._Subscription
constructor: (@observable, @subscription_type) ->
if Mixin.DEBUG
throw new Error("Mixin.Subscriptions: Mixin.Subscription.TYPE is invalid") if (typeof(@subscription_type) != 'number') or (@subscription_type<Mixin.Subscription.TYPE.MULTIPLE) or (@subscription_type>Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links = []
addSubscriber: (subscriber, notification_callback, options) ->
@removeSubscribers((test_subscription)-> return test_subscription.mustKeepUntilDestroyed()) if (@subscription_type==Mixin.Subscription.TYPE.EXCLUSIVE)
@subscription_links.push(new Mixin.Subscriptions._SubscriptionLink(@, subscriber, notification_callback, options))
removeSubscriber: (subscriber, notification_callback, subscription_name) ->
subscription_link = _.find(@subscription_links, (test) -> return (subscriber==test.subscriber) and (notification_callback==test.notification_callback))
throw new Error("Mixin.Subscriptions.removeSubscriber: subscription '#{subscription_name}' does not exist for '#{_.classOf(subscriber)}'") if not subscription_link
_.remove(@subscription_links, subscription_link)
subscription_link.destroy()
subscribers: (subscribers) ->
subscribers.push(subscription_link.subscriber) for subscription_link in @subscription_links
return
notifySubscribers: ->
args = Array.prototype.slice.call(arguments)
subscription_link.notification_callback.apply(subscription_link.subscriber, args) for subscription_link in @subscription_links
return
removeSubscribers: (test_fn) ->
if (test_fn)
removed_subscription_links = _.select(@subscription_links, test_fn)
return if (removed_subscription_links.length == 0)
@subscription_links = _.difference(@subscription_links, removed_subscription_links)
subscription_link.destroy() for subscription_link in removed_subscription_links
else
removed_subscription_links = @subscription_links
@subscription_links = []
subscription_link.destroy() for subscription_link in removed_subscription_links
return
destroy: ->
subscription_links = @subscription_links; @subscription_links = []
link.destroy() for link in subscription_links
return
Mixin.Subscriptions.Observable||Mixin.Subscriptions.Observable={}
Mixin.Subscriptions.Observable._mixin_info =
mixin_name: 'Observable'
initialize: ->
Mixin.instanceData(@, 'Observable', {subscriptions: {}, is_destroyed: false})
(@publishSubscription.apply(@, if _.isArray(arg) then arg else [arg])) for arg in arguments
return
destroy: ->
instance_data = Mixin.instanceData(@, 'Observable')
throw new Error("Mixin.Observable.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
subscriptions = instance_data.subscriptions; instance_data.subscriptions = []
subscription.destroy() for subscription in subscriptions # clear all of the subscriptions to me
return
mixin_object: {
hasSubscription: (subscription_name) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.hasSubscription', 'subscription_name')
instance_data = Mixin.instanceData(@, 'Observable')
return (instance_data.subscriptions.hasOwnProperty(subscription_name))
publishSubscription: (subscription_name, subscription_type) ->
instance_data = Mixin.instanceData(@, 'Observable')
subscription_type = Mixin.Subscription.TYPE.MULTIPLE if (subscription_type == undefined)
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
Mixin.Core._Validate.noKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.publishSubscription', 'subscription_name')
instance_data.subscriptions[subscription_name] = new Mixin.Subscriptions._Subscription(@, subscription_type)
return @
subscriptions: ->
instance_data = Mixin.instanceData(@, 'Observable')
subscriptions = []; subscriptions.push(key) for key, value of instance_data.subscriptions
return subscriptions
subscribers: (subscription_name) ->
subscribers = []
instance_data = Mixin.instanceData(@, 'Observable')
if subscription_name==undefined
subscription.subscribers(subscribers) for key, subscription of instance_data.subscriptions
else
throw new Error("Mixin.Observable.subscribers: subscriber '#{_classOf(@)}' does not recognize '#{subscription_name}'") if not instance_data.subscriptions.hasOwnProperty(subscription_name)
(subscription.subscribers(subscribers) if (subscription.subscription_name==subscription_name)) for key, subscription of instance_data.subscriptions
return _.uniq(subscribers)
# Accepts forms:
# subscriber, subscription1, subscription2
# subscriber, [subscription1, param1, etc], subscription2
addSubscriber: (subscriber, subscription_parameters) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doSubscribe = (subscription_name, notification_callback, options) ->
options||options={}
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.addSubscriber', 'notification_callback')
Mixin.Core._Validate.object(options, 'Mixin.Observable.addSubscriber', 'options')
Mixin.Core._Validate.callback(options.destroy, 'Mixin.Observable.addSubscriber', 'options.destroy') if (options.destroy!=undefined)
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.addSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.addSubscriber(subscriber, notification_callback, options)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.addSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doSubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doSubscribe.apply(@, parameter) else _doSubscribe.apply(parameter)) for parameter in args
return @
notifySubscribers: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Observable')
return if instance_data.is_destroyed
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.notifySubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.notifySubscribers')
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.notifySubscribers.apply(subscription, Array.prototype.slice.call(arguments,1))
return @
removeSubscriber: (subscriber, subscription_name, notification_callback) ->
instance_data = Mixin.instanceData(@, 'Observable')
_doUnsubscribe = (subscription_name, notification_callback) ->
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
Mixin.Core._Validate.callback(notification_callback, 'Mixin.Observable.removeSubscriber', 'notification_callback')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscriber', 'subscription_name')
subscription = instance_data.subscriptions[subscription_name]
subscription.removeSubscriber(subscriber, notification_callback, subscription_name)
# check for infering parameters
args = Array.prototype.slice.call(arguments, 1)
if Mixin.DEBUG
Mixin.Core._Validate.instanceWithMixin(subscriber, 'Subscriber', 'Mixin.Observable.removeSubscriber', 'subscriber')
if (args.length>1)
check_arg = args[1]
# the next parameter after the first subscription is not a subscription
if not ((_.isString(check_arg) and @hasSubscription(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and @hasSubscription(check_arg[0])))
_doUnsubscribe.apply(@, Array.prototype.slice.call(arguments,1))
return @
(if _.isArray(parameter) then _doUnsubscribe.apply(@, parameter) else _doUnsubscribe.apply(parameter)) for parameter in args
return @
removeSubscribers: (subscription_name, test_fn) ->
instance_data = Mixin.instanceData(@, 'Observable')
if Mixin.DEBUG
if (subscription_name!=undefined)
Mixin.Core._Validate.string(subscription_name, 'Mixin.Observable.removeSubscribers', 'subscription_name')
Mixin.Core._Validate.hasKey(instance_data.subscriptions, subscription_name, 'Mixin.Observable.removeSubscribers')
Mixin.Core._Validate.callback(test_fn, 'Mixin.Observable.removeSubscribers', 'test_fn') if (test_fn!=undefined)
if (subscription_name)
subscription = instance_data.subscriptions[subscription_name]; return if not subscription
subscription.removeSubscribers(test_fn)
else
subscription.removeSubscribers(test_fn) for key, subscription of instance_data.subscriptions
return @
}
####################################################
# Mixin.Subscriber
# Usage:
####################################################
Mixin.Subscriptions.Subscriber||Mixin.Subscriptions.Subscriber={}
Mixin.Subscriptions.Subscriber._mixin_info =
mixin_name: 'Subscriber'
initialize: ->
Mixin.instanceData(@, 'Subscriber', {subscription_backlinks: [], is_destroyed: false})
destroy: ->
instance_data = Mixin.instanceData(@, 'Subscriber')
throw new Error("Mixin.Subscriber.destroy: already destroyed") if instance_data.is_destroyed
instance_data.is_destroyed = true
backlinks = instance_data.subscription_backlinks; instance_data.subscription_backlinks = []
backlink.destroy() for backlink in backlinks # clear all of my subscriptions to others
return
mixin_object: {
observables: (subscription_name) ->
instance_data = Mixin.instanceData(@, 'Subscriber')
obserables = []
if (subscription_name==undefined)
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription and (subscription_link.subscription.subscription_name==subscription_name))) for subscription_link in instance_data.subscription_backlinks
else
if Mixin.DEBUG
Mixin.Core._Validate.string(subscription_name, 'Mixin.Subscriptions.observables', 'subscription_name')
(obserables.push(subscription_link.subscription.observable) if (subscription_link.subscription)) for subscription_link in instance_data.subscription_backlinks
return _.uniq(obserables)
}
####################################################
# Mixin.ObservableSubscriber
# Usage:
####################################################
Mixin.Subscriptions.ObservableSubscriber||Mixin.Subscriptions.ObservableSubscriber={}
Mixin.Subscriptions.ObservableSubscriber._mixin_info =
mixin_name: 'ObservableSubscriber'
mixin_object: {}
initialize: -> Mixin.in(@, 'Subscriber', ['Observable'].concat(Array.prototype.slice.call(arguments)))
destroy: -> Mixin.out(@, 'Subscriber', 'Observable')
####################################################
# Make mixins available
####################################################
Mixin.registerMixin(Mixin.Subscriptions.Observable._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.Subscriber._mixin_info)
Mixin.registerMixin(Mixin.Subscriptions.ObservableSubscriber._mixin_info)
|
[
{
"context": "duct = new @Product\n product.fromJSON\n name: \"Product One\"\n id: 1\n store_id: 1\n productVariants: [",
"end": 4270,
"score": 0.9709024429321289,
"start": 4259,
"tag": "NAME",
"value": "Product One"
},
{
"context": ", 3\n @Product.createFromJSON(id: 100, name: 'New!', store_id: 1)\n equal products.length, 4\n\na",
"end": 5721,
"score": 0.5064623951911926,
"start": 5718,
"tag": "NAME",
"value": "New"
},
{
"context": " parent model\", 5, ->\n store = new @Store name: 'Zellers'\n product1 = new @Product name: 'Gizmo'\n produc",
"end": 8190,
"score": 0.6767686009407043,
"start": 8183,
"tag": "NAME",
"value": "Zellers"
},
{
"context": " name: 'Zellers'\n product1 = new @Product name: 'Gizmo'\n product2 = new @Product name: 'Gadget'\n s",
"end": 8226,
"score": 0.8796268701553345,
"start": 8225,
"tag": "NAME",
"value": "G"
},
{
"context": "ct name: 'Gizmo'\n product2 = new @Product name: 'Gadget'\n store.set 'products', new Batman.Set(prod",
"end": 8266,
"score": 0.7579899430274963,
"start": 8265,
"tag": "NAME",
"value": "G"
},
{
"context": "er(storedJSON.products), sorter([\n {name: \"Gizmo\", store_id: record.get('id'), productVariants",
"end": 8912,
"score": 0.6574340462684631,
"start": 8911,
"tag": "NAME",
"value": "G"
},
{
"context": "d.get('id'), productVariants: []}\n {name: \"Gadget\", store_id: record.get('id'), productVariant",
"end": 8985,
"score": 0.5611100196838379,
"start": 8984,
"tag": "NAME",
"value": "G"
},
{
"context": "hrow err if err\n product = new @Product name: 'Gizmo'\n product.set 'store', store\n product.s",
"end": 9231,
"score": 0.8020270466804504,
"start": 9230,
"tag": "NAME",
"value": "G"
},
{
"context": "riant = new @ProductVariant(product_id: 3, name: \"Test Variant\")\n variant.save (err) ->\n throw err if er",
"end": 11534,
"score": 0.9774919748306274,
"start": 11522,
"tag": "NAME",
"value": "Test Variant"
},
{
"context": " children\", 4, ->\n product = new @Product(name: \"Hello!\")\n variants = product.get('productVariants')\n ",
"end": 12260,
"score": 0.9533441662788391,
"start": 12255,
"tag": "NAME",
"value": "Hello"
},
{
"context": " deepEqual storedJSON,\n id: 11\n name: \"Hello!\"\n productVariants:[\n {price: 100, prod",
"end": 13104,
"score": 0.8847310543060303,
"start": 13099,
"tag": "NAME",
"value": "Hello"
}
] | tests/batman/model/associations/has_many_test.coffee | Shipow/batman | 1 | {createStorageAdapter, TestStorageAdapter, AsyncTestStorageAdapter, generateSorterOnProperty} = if typeof require isnt 'undefined' then require '../model_helper' else window
helpers = if typeof require is 'undefined' then window.viewHelpers else require '../../view/view_helper'
QUnit.module "Batman.Model hasMany Associations"
setup: ->
Batman.currentApp = null
namespace = @namespace = {}
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@belongsTo 'store', namespace: namespace
@hasMany 'productVariants', namespace: namespace
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
store_id: 1
productVariants: [{
id:3
price:50
product_id:1
},{
id:4
price:60
product_id:1
}]
products2:
name: "Product Two"
id: 2
store_id: 1
productVariants: [{
id:1
price:50
product_id:2
},{
id:2
price:60
product_id:2
}]
products3:
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:5
price:50
product_id:3
},{
id:6
price:60
product_id:3
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'id', 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants1:
id:1
price:50
product_id:2
product_variants2:
id:2
price:60
product_id:2
product_variants3:
id:3
price:50
product_id:1
product_variants4:
id:4
price:60
product_id:1
product_variants5:
id:5
price:50
product_id:3
product_variants6:
id:6
price:60
product_id:3
asyncTest "hasMany associations are loaded and custom url is used", 2, ->
@Store._batman.get('associations').get('products').options.url = "/stores/1/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal associationSpy.lastCallArguments[2].collectionUrl, '/stores/1/products'
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded and custom url function has the parent's context", 3, ->
@Store._batman.get('associations').get('products').options.url = -> "/stores/#{@get('id')}/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal typeof associationSpy.lastCallArguments[2].collectionUrl, 'function'
ok associationSpy.lastCallArguments[2].urlContext is store
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded", 4, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
asyncTest "AssociationSet fires loaded event and sets loaded accessor", 2, ->
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.get('products').on 'loaded', ->
equal store.get('products').get('loaded'), true
QUnit.start()
asyncTest "AssociationSet becomes loaded when a new record is saved", 2, ->
store = new @Store(name: "Test")
equal store.get('products').get('loaded'), false
store.save =>
equal store.get('products').get('loaded'), true
QUnit.start()
test "AssociationSet becomes loaded when the parent record is decoded", 1, ->
product = new @Product
product.fromJSON
name: "Product One"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
ok variants.get('loaded')
asyncTest "AssociationSet does not become loaded when an existing record is saved and the response includes no information about the association", 2, ->
namespace = @
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace, autoload: false
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.save (err, store) ->
equal store.get('products').get('loaded'), false
QUnit.start()
asyncTest "hasMany associations are loaded using encoders", 1, ->
@Product.encode 'name'
encode: (x) -> x
decode: (x) -> x.toUpperCase()
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay ->
deepEqual products.map((x) -> x.get('name')), ["PRODUCT ONE", "PRODUCT TWO", "PRODUCT THREE"]
asyncTest "associations loaded via encoders index the child record loaded set", 2, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 3
@Product.createFromJSON(id: 100, name: 'New!', store_id: 1)
equal products.length, 4
asyncTest "embedded hasMany associations are loaded using encoders", 1, ->
@ProductVariant.encode 'price'
encode: (x) -> x
decode: (x) -> x * 100
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
deepEqual variants.map((x) -> x.get('price')), [5000, 6000]
QUnit.start()
asyncTest "embedded associations loaded via encoders index the child record loaded set", 3, ->
@Product.find 2, (err, product) =>
throw err if err
variants = product.get 'productVariants'
equal variants.length, 2
variant = @ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 2)
equal variants.length, 3
@ProductVariant.get('loaded').remove(variant)
equal variants.length, 2
QUnit.start()
test "embedded associations loaded via encoders index the child record loaded set when the parent is decoded all at once", 2, ->
product = new @Product
product.fromJSON
name: "Product One"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
equal variants.length, 2
@ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 1)
equal variants.length, 3
asyncTest "hasMany associations are not loaded when autoload is false", 1, ->
ns = @namespace
class Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: ns, autoload: false}
storeAdapter = createStorageAdapter Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 0
asyncTest "hasMany associations can be reloaded", 8, ->
loadSpy = spyOn(@Product, 'loadWithOptions')
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
ok !products.loaded
setTimeout =>
ok products.loaded
equal loadSpy.callCount, 1
products.load (err, products) =>
throw err if err
equal loadSpy.callCount, 2
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
QUnit.start()
, ASYNC_TEST_DELAY
asyncTest "hasMany associations are saved via the parent model", 5, ->
store = new @Store name: 'Zellers'
product1 = new @Product name: 'Gizmo'
product2 = new @Product name: 'Gadget'
store.set 'products', new Batman.Set(product1, product2)
storeSaveSpy = spyOn store, 'save'
store.save (err, record) =>
throw err if err
equal storeSaveSpy.callCount, 1
equal product1.get('store_id'), record.get('id')
equal product2.get('store_id'), record.get('id')
@Store.find record.get('id'), (err, store2) =>
throw err if err
storedJSON = @storeAdapter.storage["stores#{record.get('id')}"]
deepEqual store2.toJSON(), storedJSON
# hasMany saves inline by default
sorter = generateSorterOnProperty('name')
deepEqual sorter(storedJSON.products), sorter([
{name: "Gizmo", store_id: record.get('id'), productVariants: []}
{name: "Gadget", store_id: record.get('id'), productVariants: []}
])
QUnit.start()
asyncTest "hasMany associations are saved via the child model", 2, ->
@Store.find 1, (err, store) =>
throw err if err
product = new @Product name: 'Gizmo'
product.set 'store', store
product.save (err, savedProduct) ->
equal savedProduct.get('store_id'), store.get('id')
products = store.get('products')
ok products.has(savedProduct)
QUnit.start()
asyncTest "hasMany association can be loaded from JSON data", 14, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.length, 2
variant5 = variants.toArray()[0]
ok variant5 instanceof @ProductVariant
equal variant5.get('id'), 5
equal variant5.get('price'), 50
equal variant5.get('product_id'), 3
proxiedProduct = variant5.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
variant6 = variants.toArray()[1]
ok variant6 instanceof @ProductVariant
equal variant6.get('id'), 6
equal variant6.get('price'), 60
equal variant6.get('product_id'), 3
proxiedProduct = variant6.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
QUnit.start()
asyncTest "hasMany associations loaded from JSON data should not do an implicit remote fetch", 3, ->
variantLoadSpy = spyOn @variantsAdapter, 'readAll'
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
delay =>
equal variants.length, 2
equal variantLoadSpy.callCount, 0
asyncTest "hasMany associations loaded from JSON should be reloadable", 2, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
variants.load (err, newVariants) =>
throw err if err
equal newVariants.length, 2
QUnit.start()
asyncTest "hasMany associations loaded from JSON should index the loaded set like normal associations", 3, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.get('length'), 2
variant = new @ProductVariant(product_id: 3, name: "Test Variant")
variant.save (err) ->
throw err if err
equal variants.get('length'), 3
QUnit.start()
asyncTest "hasMany child models are added to the identity map", 2, ->
equal @ProductVariant.get('loaded').length, 0
@Product.find 3, (err, product) =>
equal @ProductVariant.get('loaded').length, 2
QUnit.start()
asyncTest "unsaved hasMany models should accept associated children", 2, ->
product = new @Product
variants = product.get('productVariants')
delay =>
equal variants.length, 0
variant = new @ProductVariant
variants.add variant
equal variants.length, 1
asyncTest "unsaved hasMany models should save their associated children", 4, ->
product = new @Product(name: "Hello!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
storedJSON = @productAdapter.storage["products#{product.get('id')}"]
deepEqual storedJSON,
id: 11
name: "Hello!"
productVariants:[
{price: 100, product_id: product.get('id')}
]
ok !product.isNew()
ok !variant.isNew()
equal variant.get('product_id'), product.get('id')
QUnit.start()
asyncTest "unsaved hasMany models should reflect their associated children after save", 3, ->
product = new @Product(name: "Hello!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
equal product.get('productVariants.length'), 1
ok product.get('productVariants').has(variant)
equal variants.get('length'), 1
QUnit.start()
asyncTest "saved hasMany models who's related records have been removed should serialize the association as empty to notify the backend", ->
@Product.find 3, (err, product) =>
throw err if err
ok product.get('productVariants').length
product.get('productVariants').forEach (variant) ->
variant.set('product_id', 10)
equal product.get('productVariants').length, 0
product.save (err) =>
throw err if err
deepEqual @productAdapter.storage['products3'], {id: 3, name: "Product Three", store_id: 1, productVariants: []}
QUnit.start()
asyncTest "unsaved hasMany models should decode their child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
five = variants[0]
six = variants[1]
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "unsaved hasMany models should decode their existing child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
for variant in variants when variant.get('id') in [5,6]
product.get('productVariants').add(variant)
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "saved hasMany models should decode their child records based on ID", ->
@Product.find 3, (err, product) =>
throw err if err
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "hasMany adds new related model instances to its set", ->
@Store.find 1, (err, store) =>
throw err if err
addedProduct = new @Product(name: 'Product Four', store_id: store.get('id'))
addedProduct.save (err, savedProduct) =>
ok store.get('products').has(savedProduct)
QUnit.start()
asyncTest "hasMany removes destroyed related model instances from its set", ->
@Store.find 1, (err, store) =>
throw err if err
store.get('products').load (err, products) ->
throw err if err
destroyedProduct = products.toArray()[0]
destroyedProduct.destroy (err) ->
throw err if err
ok !store.get('products').has(destroyedProduct)
QUnit.start()
asyncTest "hasMany loads records for each parent instance", 2, ->
@storeAdapter.storage["stores2"] =
name: "Store Two"
id: 2
@productAdapter.storage["products4"] =
name: "Product Four"
id: 4
store_id: 2
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
setTimeout =>
equal products.length, 3
@Store.find 2, (err, store2) =>
throw err if err
products2 = store2.get('products')
delay =>
equal products2.length, 1
, ASYNC_TEST_DELAY
asyncTest "hasMany loads after an instance of the related model is saved locally", 2, ->
product = new @Product
name: "Local product"
store_id: 1
product.save (err, savedProduct) =>
throw err if err
@Store.find 1, (err, store) ->
throw err if err
products = store.get('products')
ok products.has(savedProduct)
delay ->
equal products.length, 4
asyncTest "hasMany supports custom foreign keys", 1, ->
namespace = @
class Shop extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: namespace, foreignKey: 'store_id'}
shopAdapter = createStorageAdapter Shop, AsyncTestStorageAdapter,
'shops1':
id: 1
name: 'Shop One'
Shop.find 1, (err, shop) ->
products = shop.get('products')
delay ->
equal products.length, 3
test "hasMany supports custom proxy classes", 1, ->
namespace = @
class CoolAssociationSet extends Batman.AssociationSet
class Shop extends Batman.Model
@encode 'id'
@hasMany 'products', {namespace: namespace, extend: {proxyClass: CoolAssociationSet}}
shop = new Shop()
ok shop.get('products') instanceof CoolAssociationSet
asyncTest "regression test: identity mapping works", ->
@ProductVariant.load (err, variants) =>
originalIDs = variants.map (v) -> v.get('id')
@Product.load (err, products) =>
currentIDs = variants.map (v) -> v.get('id')
deepEqual currentIDs, originalIDs
deepEqual @ProductVariant.get('loaded').mapToProperty('id').sort(), [1,2,3,4,5,6]
QUnit.start()
QUnit.module "Batman.Model hasMany Associations with inverse of"
setup: ->
namespace = {}
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@hasMany 'productVariants', {namespace: namespace, inverseOf: 'product'}
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
productVariants: [{
id:5
price:50
},{
id:6
price:60
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants5:
id:5
price:50
product_variants6:
id:6
price:60
asyncTest "hasMany sets the foreign key on the inverse relation if the children haven't been loaded", 3, ->
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
asyncTest "hasMany sets the foreign key on the inverse relation if the children have already been loaded", 3, ->
@ProductVariant.load (err, variants) =>
throw err if err
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
| 45343 | {createStorageAdapter, TestStorageAdapter, AsyncTestStorageAdapter, generateSorterOnProperty} = if typeof require isnt 'undefined' then require '../model_helper' else window
helpers = if typeof require is 'undefined' then window.viewHelpers else require '../../view/view_helper'
QUnit.module "Batman.Model hasMany Associations"
setup: ->
Batman.currentApp = null
namespace = @namespace = {}
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@belongsTo 'store', namespace: namespace
@hasMany 'productVariants', namespace: namespace
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
store_id: 1
productVariants: [{
id:3
price:50
product_id:1
},{
id:4
price:60
product_id:1
}]
products2:
name: "Product Two"
id: 2
store_id: 1
productVariants: [{
id:1
price:50
product_id:2
},{
id:2
price:60
product_id:2
}]
products3:
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:5
price:50
product_id:3
},{
id:6
price:60
product_id:3
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'id', 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants1:
id:1
price:50
product_id:2
product_variants2:
id:2
price:60
product_id:2
product_variants3:
id:3
price:50
product_id:1
product_variants4:
id:4
price:60
product_id:1
product_variants5:
id:5
price:50
product_id:3
product_variants6:
id:6
price:60
product_id:3
asyncTest "hasMany associations are loaded and custom url is used", 2, ->
@Store._batman.get('associations').get('products').options.url = "/stores/1/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal associationSpy.lastCallArguments[2].collectionUrl, '/stores/1/products'
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded and custom url function has the parent's context", 3, ->
@Store._batman.get('associations').get('products').options.url = -> "/stores/#{@get('id')}/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal typeof associationSpy.lastCallArguments[2].collectionUrl, 'function'
ok associationSpy.lastCallArguments[2].urlContext is store
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded", 4, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
asyncTest "AssociationSet fires loaded event and sets loaded accessor", 2, ->
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.get('products').on 'loaded', ->
equal store.get('products').get('loaded'), true
QUnit.start()
asyncTest "AssociationSet becomes loaded when a new record is saved", 2, ->
store = new @Store(name: "Test")
equal store.get('products').get('loaded'), false
store.save =>
equal store.get('products').get('loaded'), true
QUnit.start()
test "AssociationSet becomes loaded when the parent record is decoded", 1, ->
product = new @Product
product.fromJSON
name: "<NAME>"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
ok variants.get('loaded')
asyncTest "AssociationSet does not become loaded when an existing record is saved and the response includes no information about the association", 2, ->
namespace = @
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace, autoload: false
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.save (err, store) ->
equal store.get('products').get('loaded'), false
QUnit.start()
asyncTest "hasMany associations are loaded using encoders", 1, ->
@Product.encode 'name'
encode: (x) -> x
decode: (x) -> x.toUpperCase()
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay ->
deepEqual products.map((x) -> x.get('name')), ["PRODUCT ONE", "PRODUCT TWO", "PRODUCT THREE"]
asyncTest "associations loaded via encoders index the child record loaded set", 2, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 3
@Product.createFromJSON(id: 100, name: '<NAME>!', store_id: 1)
equal products.length, 4
asyncTest "embedded hasMany associations are loaded using encoders", 1, ->
@ProductVariant.encode 'price'
encode: (x) -> x
decode: (x) -> x * 100
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
deepEqual variants.map((x) -> x.get('price')), [5000, 6000]
QUnit.start()
asyncTest "embedded associations loaded via encoders index the child record loaded set", 3, ->
@Product.find 2, (err, product) =>
throw err if err
variants = product.get 'productVariants'
equal variants.length, 2
variant = @ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 2)
equal variants.length, 3
@ProductVariant.get('loaded').remove(variant)
equal variants.length, 2
QUnit.start()
test "embedded associations loaded via encoders index the child record loaded set when the parent is decoded all at once", 2, ->
product = new @Product
product.fromJSON
name: "Product One"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
equal variants.length, 2
@ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 1)
equal variants.length, 3
asyncTest "hasMany associations are not loaded when autoload is false", 1, ->
ns = @namespace
class Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: ns, autoload: false}
storeAdapter = createStorageAdapter Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 0
asyncTest "hasMany associations can be reloaded", 8, ->
loadSpy = spyOn(@Product, 'loadWithOptions')
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
ok !products.loaded
setTimeout =>
ok products.loaded
equal loadSpy.callCount, 1
products.load (err, products) =>
throw err if err
equal loadSpy.callCount, 2
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
QUnit.start()
, ASYNC_TEST_DELAY
asyncTest "hasMany associations are saved via the parent model", 5, ->
store = new @Store name: '<NAME>'
product1 = new @Product name: '<NAME>izmo'
product2 = new @Product name: '<NAME>adget'
store.set 'products', new Batman.Set(product1, product2)
storeSaveSpy = spyOn store, 'save'
store.save (err, record) =>
throw err if err
equal storeSaveSpy.callCount, 1
equal product1.get('store_id'), record.get('id')
equal product2.get('store_id'), record.get('id')
@Store.find record.get('id'), (err, store2) =>
throw err if err
storedJSON = @storeAdapter.storage["stores#{record.get('id')}"]
deepEqual store2.toJSON(), storedJSON
# hasMany saves inline by default
sorter = generateSorterOnProperty('name')
deepEqual sorter(storedJSON.products), sorter([
{name: "<NAME>izmo", store_id: record.get('id'), productVariants: []}
{name: "<NAME>adget", store_id: record.get('id'), productVariants: []}
])
QUnit.start()
asyncTest "hasMany associations are saved via the child model", 2, ->
@Store.find 1, (err, store) =>
throw err if err
product = new @Product name: '<NAME>izmo'
product.set 'store', store
product.save (err, savedProduct) ->
equal savedProduct.get('store_id'), store.get('id')
products = store.get('products')
ok products.has(savedProduct)
QUnit.start()
asyncTest "hasMany association can be loaded from JSON data", 14, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.length, 2
variant5 = variants.toArray()[0]
ok variant5 instanceof @ProductVariant
equal variant5.get('id'), 5
equal variant5.get('price'), 50
equal variant5.get('product_id'), 3
proxiedProduct = variant5.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
variant6 = variants.toArray()[1]
ok variant6 instanceof @ProductVariant
equal variant6.get('id'), 6
equal variant6.get('price'), 60
equal variant6.get('product_id'), 3
proxiedProduct = variant6.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
QUnit.start()
asyncTest "hasMany associations loaded from JSON data should not do an implicit remote fetch", 3, ->
variantLoadSpy = spyOn @variantsAdapter, 'readAll'
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
delay =>
equal variants.length, 2
equal variantLoadSpy.callCount, 0
asyncTest "hasMany associations loaded from JSON should be reloadable", 2, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
variants.load (err, newVariants) =>
throw err if err
equal newVariants.length, 2
QUnit.start()
asyncTest "hasMany associations loaded from JSON should index the loaded set like normal associations", 3, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.get('length'), 2
variant = new @ProductVariant(product_id: 3, name: "<NAME>")
variant.save (err) ->
throw err if err
equal variants.get('length'), 3
QUnit.start()
asyncTest "hasMany child models are added to the identity map", 2, ->
equal @ProductVariant.get('loaded').length, 0
@Product.find 3, (err, product) =>
equal @ProductVariant.get('loaded').length, 2
QUnit.start()
asyncTest "unsaved hasMany models should accept associated children", 2, ->
product = new @Product
variants = product.get('productVariants')
delay =>
equal variants.length, 0
variant = new @ProductVariant
variants.add variant
equal variants.length, 1
asyncTest "unsaved hasMany models should save their associated children", 4, ->
product = new @Product(name: "<NAME>!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
storedJSON = @productAdapter.storage["products#{product.get('id')}"]
deepEqual storedJSON,
id: 11
name: "<NAME>!"
productVariants:[
{price: 100, product_id: product.get('id')}
]
ok !product.isNew()
ok !variant.isNew()
equal variant.get('product_id'), product.get('id')
QUnit.start()
asyncTest "unsaved hasMany models should reflect their associated children after save", 3, ->
product = new @Product(name: "Hello!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
equal product.get('productVariants.length'), 1
ok product.get('productVariants').has(variant)
equal variants.get('length'), 1
QUnit.start()
asyncTest "saved hasMany models who's related records have been removed should serialize the association as empty to notify the backend", ->
@Product.find 3, (err, product) =>
throw err if err
ok product.get('productVariants').length
product.get('productVariants').forEach (variant) ->
variant.set('product_id', 10)
equal product.get('productVariants').length, 0
product.save (err) =>
throw err if err
deepEqual @productAdapter.storage['products3'], {id: 3, name: "Product Three", store_id: 1, productVariants: []}
QUnit.start()
asyncTest "unsaved hasMany models should decode their child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
five = variants[0]
six = variants[1]
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "unsaved hasMany models should decode their existing child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
for variant in variants when variant.get('id') in [5,6]
product.get('productVariants').add(variant)
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "saved hasMany models should decode their child records based on ID", ->
@Product.find 3, (err, product) =>
throw err if err
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "hasMany adds new related model instances to its set", ->
@Store.find 1, (err, store) =>
throw err if err
addedProduct = new @Product(name: 'Product Four', store_id: store.get('id'))
addedProduct.save (err, savedProduct) =>
ok store.get('products').has(savedProduct)
QUnit.start()
asyncTest "hasMany removes destroyed related model instances from its set", ->
@Store.find 1, (err, store) =>
throw err if err
store.get('products').load (err, products) ->
throw err if err
destroyedProduct = products.toArray()[0]
destroyedProduct.destroy (err) ->
throw err if err
ok !store.get('products').has(destroyedProduct)
QUnit.start()
asyncTest "hasMany loads records for each parent instance", 2, ->
@storeAdapter.storage["stores2"] =
name: "Store Two"
id: 2
@productAdapter.storage["products4"] =
name: "Product Four"
id: 4
store_id: 2
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
setTimeout =>
equal products.length, 3
@Store.find 2, (err, store2) =>
throw err if err
products2 = store2.get('products')
delay =>
equal products2.length, 1
, ASYNC_TEST_DELAY
asyncTest "hasMany loads after an instance of the related model is saved locally", 2, ->
product = new @Product
name: "Local product"
store_id: 1
product.save (err, savedProduct) =>
throw err if err
@Store.find 1, (err, store) ->
throw err if err
products = store.get('products')
ok products.has(savedProduct)
delay ->
equal products.length, 4
asyncTest "hasMany supports custom foreign keys", 1, ->
namespace = @
class Shop extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: namespace, foreignKey: 'store_id'}
shopAdapter = createStorageAdapter Shop, AsyncTestStorageAdapter,
'shops1':
id: 1
name: 'Shop One'
Shop.find 1, (err, shop) ->
products = shop.get('products')
delay ->
equal products.length, 3
test "hasMany supports custom proxy classes", 1, ->
namespace = @
class CoolAssociationSet extends Batman.AssociationSet
class Shop extends Batman.Model
@encode 'id'
@hasMany 'products', {namespace: namespace, extend: {proxyClass: CoolAssociationSet}}
shop = new Shop()
ok shop.get('products') instanceof CoolAssociationSet
asyncTest "regression test: identity mapping works", ->
@ProductVariant.load (err, variants) =>
originalIDs = variants.map (v) -> v.get('id')
@Product.load (err, products) =>
currentIDs = variants.map (v) -> v.get('id')
deepEqual currentIDs, originalIDs
deepEqual @ProductVariant.get('loaded').mapToProperty('id').sort(), [1,2,3,4,5,6]
QUnit.start()
QUnit.module "Batman.Model hasMany Associations with inverse of"
setup: ->
namespace = {}
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@hasMany 'productVariants', {namespace: namespace, inverseOf: 'product'}
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
productVariants: [{
id:5
price:50
},{
id:6
price:60
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants5:
id:5
price:50
product_variants6:
id:6
price:60
asyncTest "hasMany sets the foreign key on the inverse relation if the children haven't been loaded", 3, ->
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
asyncTest "hasMany sets the foreign key on the inverse relation if the children have already been loaded", 3, ->
@ProductVariant.load (err, variants) =>
throw err if err
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
| true | {createStorageAdapter, TestStorageAdapter, AsyncTestStorageAdapter, generateSorterOnProperty} = if typeof require isnt 'undefined' then require '../model_helper' else window
helpers = if typeof require is 'undefined' then window.viewHelpers else require '../../view/view_helper'
QUnit.module "Batman.Model hasMany Associations"
setup: ->
Batman.currentApp = null
namespace = @namespace = {}
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@belongsTo 'store', namespace: namespace
@hasMany 'productVariants', namespace: namespace
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
store_id: 1
productVariants: [{
id:3
price:50
product_id:1
},{
id:4
price:60
product_id:1
}]
products2:
name: "Product Two"
id: 2
store_id: 1
productVariants: [{
id:1
price:50
product_id:2
},{
id:2
price:60
product_id:2
}]
products3:
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:5
price:50
product_id:3
},{
id:6
price:60
product_id:3
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'id', 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants1:
id:1
price:50
product_id:2
product_variants2:
id:2
price:60
product_id:2
product_variants3:
id:3
price:50
product_id:1
product_variants4:
id:4
price:60
product_id:1
product_variants5:
id:5
price:50
product_id:3
product_variants6:
id:6
price:60
product_id:3
asyncTest "hasMany associations are loaded and custom url is used", 2, ->
@Store._batman.get('associations').get('products').options.url = "/stores/1/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal associationSpy.lastCallArguments[2].collectionUrl, '/stores/1/products'
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded and custom url function has the parent's context", 3, ->
@Store._batman.get('associations').get('products').options.url = -> "/stores/#{@get('id')}/products"
associationSpy = spyOn(@productAdapter, 'perform')
@Store.find 1, (err, store) =>
products = store.get 'products'
delay ->
equal typeof associationSpy.lastCallArguments[2].collectionUrl, 'function'
ok associationSpy.lastCallArguments[2].urlContext is store
equal associationSpy.callCount, 1
asyncTest "hasMany associations are loaded", 4, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
asyncTest "AssociationSet fires loaded event and sets loaded accessor", 2, ->
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.get('products').on 'loaded', ->
equal store.get('products').get('loaded'), true
QUnit.start()
asyncTest "AssociationSet becomes loaded when a new record is saved", 2, ->
store = new @Store(name: "Test")
equal store.get('products').get('loaded'), false
store.save =>
equal store.get('products').get('loaded'), true
QUnit.start()
test "AssociationSet becomes loaded when the parent record is decoded", 1, ->
product = new @Product
product.fromJSON
name: "PI:NAME:<NAME>END_PI"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
ok variants.get('loaded')
asyncTest "AssociationSet does not become loaded when an existing record is saved and the response includes no information about the association", 2, ->
namespace = @
namespace.Store = class @Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', namespace: namespace, autoload: false
@storeAdapter = createStorageAdapter @Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
@Store.find 1, (err, store) ->
equal store.get('products').get('loaded'), false
store.save (err, store) ->
equal store.get('products').get('loaded'), false
QUnit.start()
asyncTest "hasMany associations are loaded using encoders", 1, ->
@Product.encode 'name'
encode: (x) -> x
decode: (x) -> x.toUpperCase()
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay ->
deepEqual products.map((x) -> x.get('name')), ["PRODUCT ONE", "PRODUCT TWO", "PRODUCT THREE"]
asyncTest "associations loaded via encoders index the child record loaded set", 2, ->
@Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 3
@Product.createFromJSON(id: 100, name: 'PI:NAME:<NAME>END_PI!', store_id: 1)
equal products.length, 4
asyncTest "embedded hasMany associations are loaded using encoders", 1, ->
@ProductVariant.encode 'price'
encode: (x) -> x
decode: (x) -> x * 100
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
deepEqual variants.map((x) -> x.get('price')), [5000, 6000]
QUnit.start()
asyncTest "embedded associations loaded via encoders index the child record loaded set", 3, ->
@Product.find 2, (err, product) =>
throw err if err
variants = product.get 'productVariants'
equal variants.length, 2
variant = @ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 2)
equal variants.length, 3
@ProductVariant.get('loaded').remove(variant)
equal variants.length, 2
QUnit.start()
test "embedded associations loaded via encoders index the child record loaded set when the parent is decoded all at once", 2, ->
product = new @Product
product.fromJSON
name: "Product One"
id: 1
store_id: 1
productVariants: [
{id:3, price:50,product_id:1},
{id:4, price:60, product_id:1}
]
variants = product.get 'productVariants'
equal variants.length, 2
@ProductVariant.createFromJSON(id: 100, price: 20.99, product_id: 1)
equal variants.length, 3
asyncTest "hasMany associations are not loaded when autoload is false", 1, ->
ns = @namespace
class Store extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: ns, autoload: false}
storeAdapter = createStorageAdapter Store, AsyncTestStorageAdapter,
stores1:
name: "Store One"
id: 1
Store.find 1, (err, store) =>
throw err if err
products = store.get 'products'
delay =>
equal products.length, 0
asyncTest "hasMany associations can be reloaded", 8, ->
loadSpy = spyOn(@Product, 'loadWithOptions')
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
ok !products.loaded
setTimeout =>
ok products.loaded
equal loadSpy.callCount, 1
products.load (err, products) =>
throw err if err
equal loadSpy.callCount, 2
products.forEach (product) => ok product instanceof @Product
deepEqual products.map((x) -> x.get('id')), [1,2,3]
QUnit.start()
, ASYNC_TEST_DELAY
asyncTest "hasMany associations are saved via the parent model", 5, ->
store = new @Store name: 'PI:NAME:<NAME>END_PI'
product1 = new @Product name: 'PI:NAME:<NAME>END_PIizmo'
product2 = new @Product name: 'PI:NAME:<NAME>END_PIadget'
store.set 'products', new Batman.Set(product1, product2)
storeSaveSpy = spyOn store, 'save'
store.save (err, record) =>
throw err if err
equal storeSaveSpy.callCount, 1
equal product1.get('store_id'), record.get('id')
equal product2.get('store_id'), record.get('id')
@Store.find record.get('id'), (err, store2) =>
throw err if err
storedJSON = @storeAdapter.storage["stores#{record.get('id')}"]
deepEqual store2.toJSON(), storedJSON
# hasMany saves inline by default
sorter = generateSorterOnProperty('name')
deepEqual sorter(storedJSON.products), sorter([
{name: "PI:NAME:<NAME>END_PIizmo", store_id: record.get('id'), productVariants: []}
{name: "PI:NAME:<NAME>END_PIadget", store_id: record.get('id'), productVariants: []}
])
QUnit.start()
asyncTest "hasMany associations are saved via the child model", 2, ->
@Store.find 1, (err, store) =>
throw err if err
product = new @Product name: 'PI:NAME:<NAME>END_PIizmo'
product.set 'store', store
product.save (err, savedProduct) ->
equal savedProduct.get('store_id'), store.get('id')
products = store.get('products')
ok products.has(savedProduct)
QUnit.start()
asyncTest "hasMany association can be loaded from JSON data", 14, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.length, 2
variant5 = variants.toArray()[0]
ok variant5 instanceof @ProductVariant
equal variant5.get('id'), 5
equal variant5.get('price'), 50
equal variant5.get('product_id'), 3
proxiedProduct = variant5.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
variant6 = variants.toArray()[1]
ok variant6 instanceof @ProductVariant
equal variant6.get('id'), 6
equal variant6.get('price'), 60
equal variant6.get('product_id'), 3
proxiedProduct = variant6.get('product')
equal proxiedProduct.get('id'), product.get('id')
equal proxiedProduct.get('name'), product.get('name')
QUnit.start()
asyncTest "hasMany associations loaded from JSON data should not do an implicit remote fetch", 3, ->
variantLoadSpy = spyOn @variantsAdapter, 'readAll'
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
delay =>
equal variants.length, 2
equal variantLoadSpy.callCount, 0
asyncTest "hasMany associations loaded from JSON should be reloadable", 2, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
variants.load (err, newVariants) =>
throw err if err
equal newVariants.length, 2
QUnit.start()
asyncTest "hasMany associations loaded from JSON should index the loaded set like normal associations", 3, ->
@Product.find 3, (err, product) =>
throw err if err
variants = product.get('productVariants')
ok variants instanceof Batman.AssociationSet
equal variants.get('length'), 2
variant = new @ProductVariant(product_id: 3, name: "PI:NAME:<NAME>END_PI")
variant.save (err) ->
throw err if err
equal variants.get('length'), 3
QUnit.start()
asyncTest "hasMany child models are added to the identity map", 2, ->
equal @ProductVariant.get('loaded').length, 0
@Product.find 3, (err, product) =>
equal @ProductVariant.get('loaded').length, 2
QUnit.start()
asyncTest "unsaved hasMany models should accept associated children", 2, ->
product = new @Product
variants = product.get('productVariants')
delay =>
equal variants.length, 0
variant = new @ProductVariant
variants.add variant
equal variants.length, 1
asyncTest "unsaved hasMany models should save their associated children", 4, ->
product = new @Product(name: "PI:NAME:<NAME>END_PI!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
storedJSON = @productAdapter.storage["products#{product.get('id')}"]
deepEqual storedJSON,
id: 11
name: "PI:NAME:<NAME>END_PI!"
productVariants:[
{price: 100, product_id: product.get('id')}
]
ok !product.isNew()
ok !variant.isNew()
equal variant.get('product_id'), product.get('id')
QUnit.start()
asyncTest "unsaved hasMany models should reflect their associated children after save", 3, ->
product = new @Product(name: "Hello!")
variants = product.get('productVariants')
variant = new @ProductVariant(price: 100)
variants.add variant
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
@productAdapter.create = (record, options, callback) ->
id = @_setRecordID(record)
if id
@storage[@storageKey(record) + id] = record.toJSON()
record.fromJSON
id: id
productVariants: [{
price: 100
id: 11
}]
callback(undefined, record)
else
callback(new Error("Couldn't get record primary key."))
product.save (err, product) =>
throw err if err
# Mock out what a realbackend would do: assign ids to the child records
# The TestStorageAdapter is smart enough to do this for the parent, but not the children.
equal product.get('productVariants.length'), 1
ok product.get('productVariants').has(variant)
equal variants.get('length'), 1
QUnit.start()
asyncTest "saved hasMany models who's related records have been removed should serialize the association as empty to notify the backend", ->
@Product.find 3, (err, product) =>
throw err if err
ok product.get('productVariants').length
product.get('productVariants').forEach (variant) ->
variant.set('product_id', 10)
equal product.get('productVariants').length, 0
product.save (err) =>
throw err if err
deepEqual @productAdapter.storage['products3'], {id: 3, name: "Product Three", store_id: 1, productVariants: []}
QUnit.start()
asyncTest "unsaved hasMany models should decode their child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
five = variants[0]
six = variants[1]
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "unsaved hasMany models should decode their existing child records based on ID", ->
@ProductVariant.load (err, variants) =>
product = new @Product
for variant in variants when variant.get('id') in [5,6]
product.get('productVariants').add(variant)
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "saved hasMany models should decode their child records based on ID", ->
@Product.find 3, (err, product) =>
throw err if err
five = product.get('productVariants').indexedByUnique('id').get(5)
six = product.get('productVariants').indexedByUnique('id').get(6)
# decode with the variants out of order
product.fromJSON
name: "Product Three"
id: 3
store_id: 1
productVariants: [{
id:6
price:60
product_id:3
},{
id:5
price:50
product_id:3
}]
equal product.get('productVariants.length'), 2
deepEqual product.get('productVariants').mapToProperty('id').sort(), [5,6]
equal five.get('price'), 50
equal six.get('price'), 60
QUnit.start()
asyncTest "hasMany adds new related model instances to its set", ->
@Store.find 1, (err, store) =>
throw err if err
addedProduct = new @Product(name: 'Product Four', store_id: store.get('id'))
addedProduct.save (err, savedProduct) =>
ok store.get('products').has(savedProduct)
QUnit.start()
asyncTest "hasMany removes destroyed related model instances from its set", ->
@Store.find 1, (err, store) =>
throw err if err
store.get('products').load (err, products) ->
throw err if err
destroyedProduct = products.toArray()[0]
destroyedProduct.destroy (err) ->
throw err if err
ok !store.get('products').has(destroyedProduct)
QUnit.start()
asyncTest "hasMany loads records for each parent instance", 2, ->
@storeAdapter.storage["stores2"] =
name: "Store Two"
id: 2
@productAdapter.storage["products4"] =
name: "Product Four"
id: 4
store_id: 2
@Store.find 1, (err, store) =>
throw err if err
products = store.get('products')
setTimeout =>
equal products.length, 3
@Store.find 2, (err, store2) =>
throw err if err
products2 = store2.get('products')
delay =>
equal products2.length, 1
, ASYNC_TEST_DELAY
asyncTest "hasMany loads after an instance of the related model is saved locally", 2, ->
product = new @Product
name: "Local product"
store_id: 1
product.save (err, savedProduct) =>
throw err if err
@Store.find 1, (err, store) ->
throw err if err
products = store.get('products')
ok products.has(savedProduct)
delay ->
equal products.length, 4
asyncTest "hasMany supports custom foreign keys", 1, ->
namespace = @
class Shop extends Batman.Model
@encode 'id', 'name'
@hasMany 'products', {namespace: namespace, foreignKey: 'store_id'}
shopAdapter = createStorageAdapter Shop, AsyncTestStorageAdapter,
'shops1':
id: 1
name: 'Shop One'
Shop.find 1, (err, shop) ->
products = shop.get('products')
delay ->
equal products.length, 3
test "hasMany supports custom proxy classes", 1, ->
namespace = @
class CoolAssociationSet extends Batman.AssociationSet
class Shop extends Batman.Model
@encode 'id'
@hasMany 'products', {namespace: namespace, extend: {proxyClass: CoolAssociationSet}}
shop = new Shop()
ok shop.get('products') instanceof CoolAssociationSet
asyncTest "regression test: identity mapping works", ->
@ProductVariant.load (err, variants) =>
originalIDs = variants.map (v) -> v.get('id')
@Product.load (err, products) =>
currentIDs = variants.map (v) -> v.get('id')
deepEqual currentIDs, originalIDs
deepEqual @ProductVariant.get('loaded').mapToProperty('id').sort(), [1,2,3,4,5,6]
QUnit.start()
QUnit.module "Batman.Model hasMany Associations with inverse of"
setup: ->
namespace = {}
namespace.Product = class @Product extends Batman.Model
@encode 'id', 'name'
@hasMany 'productVariants', {namespace: namespace, inverseOf: 'product'}
@productAdapter = createStorageAdapter @Product, AsyncTestStorageAdapter,
products1:
name: "Product One"
id: 1
productVariants: [{
id:5
price:50
},{
id:6
price:60
}]
namespace.ProductVariant = class @ProductVariant extends Batman.Model
@encode 'price'
@belongsTo 'product', namespace: namespace
@variantsAdapter = createStorageAdapter @ProductVariant, AsyncTestStorageAdapter,
product_variants5:
id:5
price:50
product_variants6:
id:6
price:60
asyncTest "hasMany sets the foreign key on the inverse relation if the children haven't been loaded", 3, ->
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
asyncTest "hasMany sets the foreign key on the inverse relation if the children have already been loaded", 3, ->
@ProductVariant.load (err, variants) =>
throw err if err
@Product.find 1, (err, product) =>
throw err if err
variants = product.get('productVariants')
delay ->
variants = variants.toArray()
equal variants.length, 2
ok variants[0].get('product') == product
ok variants[1].get('product') == product
|
[
{
"context": "ch ->\n match = isApiCall url, 'api.topcoder-dev.com', ['https'], '/v3/events'\n\n it 'should match",
"end": 1707,
"score": 0.965916633605957,
"start": 1700,
"tag": "EMAIL",
"value": "dev.com"
}
] | tests/specs/is-api-call.spec.coffee | appirio-tech/swagger-fake-server | 0 | 'use strict'
match = null
url = null
isApiCall = AutoConfigFakeServerPrivates.isApiCall
describe 'isApiCall', ->
describe 'http://localhost:8080/api/v1/debug.html', ->
beforeEach ->
url = 'http://localhost:8080/api/v1/debug.html'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/v1'
it 'should match', ->
expect(match).to.be.ok
context 'match host, schemes but not basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/booger'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match host, basePath but not schemes', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['https'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match basePath, schemes but not host', ->
beforeEach ->
match = isApiCall url, 'localhost', ['http'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
describe 'https://www.localhost.com/api/batman', ->
beforeEach ->
url = 'https://www.localhost.com/api/batman'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'www.localhost.com', ['https'], '/api'
it 'should match', ->
expect(match).to.be.ok
describe 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123', ->
beforeEach ->
url = 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'api.topcoder-dev.com', ['https'], '/v3/events'
it 'should match', ->
expect(match).to.be.ok
| 64152 | 'use strict'
match = null
url = null
isApiCall = AutoConfigFakeServerPrivates.isApiCall
describe 'isApiCall', ->
describe 'http://localhost:8080/api/v1/debug.html', ->
beforeEach ->
url = 'http://localhost:8080/api/v1/debug.html'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/v1'
it 'should match', ->
expect(match).to.be.ok
context 'match host, schemes but not basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/booger'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match host, basePath but not schemes', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['https'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match basePath, schemes but not host', ->
beforeEach ->
match = isApiCall url, 'localhost', ['http'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
describe 'https://www.localhost.com/api/batman', ->
beforeEach ->
url = 'https://www.localhost.com/api/batman'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'www.localhost.com', ['https'], '/api'
it 'should match', ->
expect(match).to.be.ok
describe 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123', ->
beforeEach ->
url = 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'api.topcoder-<EMAIL>', ['https'], '/v3/events'
it 'should match', ->
expect(match).to.be.ok
| true | 'use strict'
match = null
url = null
isApiCall = AutoConfigFakeServerPrivates.isApiCall
describe 'isApiCall', ->
describe 'http://localhost:8080/api/v1/debug.html', ->
beforeEach ->
url = 'http://localhost:8080/api/v1/debug.html'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/v1'
it 'should match', ->
expect(match).to.be.ok
context 'match host, schemes but not basePath', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['http'], '/api/booger'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match host, basePath but not schemes', ->
beforeEach ->
match = isApiCall url, 'localhost:8080', ['https'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
context 'match basePath, schemes but not host', ->
beforeEach ->
match = isApiCall url, 'localhost', ['http'], '/api/v1'
it 'should not match', ->
expect(match).not.to.be.ok
describe 'https://www.localhost.com/api/batman', ->
beforeEach ->
url = 'https://www.localhost.com/api/batman'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'www.localhost.com', ['https'], '/api'
it 'should match', ->
expect(match).to.be.ok
describe 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123', ->
beforeEach ->
url = 'https://api.topcoder-dev.com/v3/events?abc=123&filter=id%253D123'
context 'match host, schemes, basePath', ->
beforeEach ->
match = isApiCall url, 'api.topcoder-PI:EMAIL:<EMAIL>END_PI', ['https'], '/v3/events'
it 'should match', ->
expect(match).to.be.ok
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9994129538536072,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": " address = socket.remoteAddress\n if host is \"127.0.0.1\"\n assert.equal address, \"127.0.0.1\"\n else",
"end": 1450,
"score": 0.9997734427452087,
"start": 1441,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " host is \"127.0.0.1\"\n assert.equal address, \"127.0.0.1\"\n else if not host? or host is \"localhost\"\n ",
"end": 1490,
"score": 0.999771237373352,
"start": 1481,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "? or host is \"localhost\"\n assert address is \"127.0.0.1\" or address is \"::ffff:127.0.0.1\"\n else\n ",
"end": 1571,
"score": 0.9997528791427612,
"start": 1562,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\n assert address is \"127.0.0.1\" or address is \"::ffff:127.0.0.1\"\n else\n console.log \"host = \" +",
"end": 1594,
"score": 0.995524525642395,
"start": 1587,
"tag": "IP_ADDRESS",
"value": "\"::ffff"
},
{
"context": "sert address is \"127.0.0.1\" or address is \"::ffff:127.0.0.1\"\n else\n console.log \"host = \" + host + \",",
"end": 1604,
"score": 0.9962475299835205,
"start": 1595,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "eAddress = \" + address\n assert.equal address, \"::1\"\n socket.setEncoding \"utf8\"\n socket.setNoDe",
"end": 1715,
"score": 0.9980578422546387,
"start": 1711,
"tag": "IP_ADDRESS",
"value": "\"::1"
},
{
"context": "st(process.platform)\npingPongTest common.PORT + 2, \"::1\" unless solaris\nprocess.on \"exit\", ->\n assert.e",
"end": 3473,
"score": 0.9917957186698914,
"start": 3469,
"tag": "IP_ADDRESS",
"value": "\"::1"
}
] | test/pummel/test-net-pingpong.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.
pingPongTest = (port, host, on_complete) ->
N = 1000
count = 0
sent_final_ping = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
assert.equal true, socket.remoteAddress isnt null
assert.equal true, socket.remoteAddress isnt `undefined`
address = socket.remoteAddress
if host is "127.0.0.1"
assert.equal address, "127.0.0.1"
else if not host? or host is "localhost"
assert address is "127.0.0.1" or address is "::ffff:127.0.0.1"
else
console.log "host = " + host + ", remoteAddress = " + address
assert.equal address, "::1"
socket.setEncoding "utf8"
socket.setNoDelay()
socket.timeout = 0
socket.on "data", (data) ->
console.log "server got: " + JSON.stringify(data)
assert.equal "open", socket.readyState
assert.equal true, count <= N
socket.write "PONG" if /PING/.exec(data)
return
socket.on "end", ->
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log "client got: " + data
assert.equal "PONG", data
count += 1
if sent_final_ping
assert.equal "readOnly", client.readyState
return
else
assert.equal "open", client.readyState
if count < N
client.write "PING"
else
sent_final_ping = true
client.write "PING"
client.end()
return
client.on "close", ->
assert.equal N + 1, count
assert.equal true, sent_final_ping
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
# All are run at once, so run on different ports
pingPongTest common.PORT, "localhost"
pingPongTest common.PORT + 1, null
# This IPv6 isn't working on Solaris
solaris = /sunos/i.test(process.platform)
pingPongTest common.PORT + 2, "::1" unless solaris
process.on "exit", ->
assert.equal (if solaris then 2 else 3), tests_run
return
| 39480 | # 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.
pingPongTest = (port, host, on_complete) ->
N = 1000
count = 0
sent_final_ping = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
assert.equal true, socket.remoteAddress isnt null
assert.equal true, socket.remoteAddress isnt `undefined`
address = socket.remoteAddress
if host is "127.0.0.1"
assert.equal address, "127.0.0.1"
else if not host? or host is "localhost"
assert address is "127.0.0.1" or address is "::ffff:127.0.0.1"
else
console.log "host = " + host + ", remoteAddress = " + address
assert.equal address, "::1"
socket.setEncoding "utf8"
socket.setNoDelay()
socket.timeout = 0
socket.on "data", (data) ->
console.log "server got: " + JSON.stringify(data)
assert.equal "open", socket.readyState
assert.equal true, count <= N
socket.write "PONG" if /PING/.exec(data)
return
socket.on "end", ->
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log "client got: " + data
assert.equal "PONG", data
count += 1
if sent_final_ping
assert.equal "readOnly", client.readyState
return
else
assert.equal "open", client.readyState
if count < N
client.write "PING"
else
sent_final_ping = true
client.write "PING"
client.end()
return
client.on "close", ->
assert.equal N + 1, count
assert.equal true, sent_final_ping
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
# All are run at once, so run on different ports
pingPongTest common.PORT, "localhost"
pingPongTest common.PORT + 1, null
# This IPv6 isn't working on Solaris
solaris = /sunos/i.test(process.platform)
pingPongTest common.PORT + 2, "::1" unless solaris
process.on "exit", ->
assert.equal (if solaris then 2 else 3), tests_run
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.
pingPongTest = (port, host, on_complete) ->
N = 1000
count = 0
sent_final_ping = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
assert.equal true, socket.remoteAddress isnt null
assert.equal true, socket.remoteAddress isnt `undefined`
address = socket.remoteAddress
if host is "127.0.0.1"
assert.equal address, "127.0.0.1"
else if not host? or host is "localhost"
assert address is "127.0.0.1" or address is "::ffff:127.0.0.1"
else
console.log "host = " + host + ", remoteAddress = " + address
assert.equal address, "::1"
socket.setEncoding "utf8"
socket.setNoDelay()
socket.timeout = 0
socket.on "data", (data) ->
console.log "server got: " + JSON.stringify(data)
assert.equal "open", socket.readyState
assert.equal true, count <= N
socket.write "PONG" if /PING/.exec(data)
return
socket.on "end", ->
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log "client got: " + data
assert.equal "PONG", data
count += 1
if sent_final_ping
assert.equal "readOnly", client.readyState
return
else
assert.equal "open", client.readyState
if count < N
client.write "PING"
else
sent_final_ping = true
client.write "PING"
client.end()
return
client.on "close", ->
assert.equal N + 1, count
assert.equal true, sent_final_ping
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
# All are run at once, so run on different ports
pingPongTest common.PORT, "localhost"
pingPongTest common.PORT + 1, null
# This IPv6 isn't working on Solaris
solaris = /sunos/i.test(process.platform)
pingPongTest common.PORT + 2, "::1" unless solaris
process.on "exit", ->
assert.equal (if solaris then 2 else 3), tests_run
return
|
[
{
"context": "e = name.toLowerCase()\n switch\n when name == 'nidoran f' then 29\n when name == 'nidoran m' then 32\n ",
"end": 206,
"score": 0.9993467926979065,
"start": 197,
"tag": "NAME",
"value": "nidoran f"
},
{
"context": "hen name == 'nidoran f' then 29\n when name == 'nidoran m' then 32\n else (id for id, pkmn of Pokemon.pok",
"end": 243,
"score": 0.9993443489074707,
"start": 234,
"tag": "NAME",
"value": "nidoran m"
}
] | index.coffee | mp-pinheiro/pokemon-battle | 0 | Pokemon = require './src/pokemon'
Trainer = require './src/trainer'
Battle = require './src/battle'
pokemon = {}
pokemon.lookup = (name) ->
name = name.toLowerCase()
switch
when name == 'nidoran f' then 29
when name == 'nidoran m' then 32
else (id for id, pkmn of Pokemon.pokedex when name is pkmn.name.toLowerCase())[0]
###pokemon.battle = (team1, team2) ->
# Standarize input
team1 = { trainer: null, pokemon: team1 } unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: 'the foe', pokemon: team2 } unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
return battle.start().toString()###
pokemon.battle = (team1, team2, fighter1, id1, fighter2, id2) ->
# Standarize input
team1 = { trainer: fighter1, pokemon: team1 } #unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: fighter2, pokemon: team2 } #unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] #unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] #unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer, id1
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer, id2
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
#console.log(battle)
battleMessage = battle.start().toString()
response = {
battle: {
log: battleMessage.replace(/\n\n\n/gm,"\n\n").replace(/(\r\n|\n|\r)/gm,"\\n"),
winner: {
id: battle.winner.id,
name: battle.winner.name,
damage: battle.damage[battle.winner.id],
hp: battle.winner.mainPokemon.hp
},
loser: {
id: battle.loser.id,
name: battle.loser.name,
damage: battle.damage[battle.loser.id],
hp: battle.loser.mainPokemon.hp
}
}
}
return JSON.stringify(response)
pokemon.build = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() for move in pokemon.moves).join("\n").toString()
pokemon.buildDebug = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() + " " + move.score for move in pokemon.debug.scoredMoves).join("\n").toString()
module.exports = pokemon
| 143530 | Pokemon = require './src/pokemon'
Trainer = require './src/trainer'
Battle = require './src/battle'
pokemon = {}
pokemon.lookup = (name) ->
name = name.toLowerCase()
switch
when name == '<NAME>' then 29
when name == '<NAME>' then 32
else (id for id, pkmn of Pokemon.pokedex when name is pkmn.name.toLowerCase())[0]
###pokemon.battle = (team1, team2) ->
# Standarize input
team1 = { trainer: null, pokemon: team1 } unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: 'the foe', pokemon: team2 } unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
return battle.start().toString()###
pokemon.battle = (team1, team2, fighter1, id1, fighter2, id2) ->
# Standarize input
team1 = { trainer: fighter1, pokemon: team1 } #unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: fighter2, pokemon: team2 } #unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] #unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] #unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer, id1
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer, id2
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
#console.log(battle)
battleMessage = battle.start().toString()
response = {
battle: {
log: battleMessage.replace(/\n\n\n/gm,"\n\n").replace(/(\r\n|\n|\r)/gm,"\\n"),
winner: {
id: battle.winner.id,
name: battle.winner.name,
damage: battle.damage[battle.winner.id],
hp: battle.winner.mainPokemon.hp
},
loser: {
id: battle.loser.id,
name: battle.loser.name,
damage: battle.damage[battle.loser.id],
hp: battle.loser.mainPokemon.hp
}
}
}
return JSON.stringify(response)
pokemon.build = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() for move in pokemon.moves).join("\n").toString()
pokemon.buildDebug = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() + " " + move.score for move in pokemon.debug.scoredMoves).join("\n").toString()
module.exports = pokemon
| true | Pokemon = require './src/pokemon'
Trainer = require './src/trainer'
Battle = require './src/battle'
pokemon = {}
pokemon.lookup = (name) ->
name = name.toLowerCase()
switch
when name == 'PI:NAME:<NAME>END_PI' then 29
when name == 'PI:NAME:<NAME>END_PI' then 32
else (id for id, pkmn of Pokemon.pokedex when name is pkmn.name.toLowerCase())[0]
###pokemon.battle = (team1, team2) ->
# Standarize input
team1 = { trainer: null, pokemon: team1 } unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: 'the foe', pokemon: team2 } unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
return battle.start().toString()###
pokemon.battle = (team1, team2, fighter1, id1, fighter2, id2) ->
# Standarize input
team1 = { trainer: fighter1, pokemon: team1 } #unless team1 instanceof Object and team1 not instanceof Array
team2 = { trainer: fighter2, pokemon: team2 } #unless team2 instanceof Object and team2 not instanceof Array
team1.pokemon = [ team1.pokemon ] #unless team1.pokemon instanceof Array
team2.pokemon = [ team2.pokemon ] #unless team2.pokemon instanceof Array
# Build trainers
trainer1 = new Trainer team1.trainer, id1
trainer1.addPokemon new Pokemon pokemon for pokemon in team1.pokemon
trainer2 = new Trainer team2.trainer, id2
trainer2.addPokemon new Pokemon pokemon for pokemon in team2.pokemon
# Fight!
battle = new Battle trainer1, trainer2
#console.log(battle)
battleMessage = battle.start().toString()
response = {
battle: {
log: battleMessage.replace(/\n\n\n/gm,"\n\n").replace(/(\r\n|\n|\r)/gm,"\\n"),
winner: {
id: battle.winner.id,
name: battle.winner.name,
damage: battle.damage[battle.winner.id],
hp: battle.winner.mainPokemon.hp
},
loser: {
id: battle.loser.id,
name: battle.loser.name,
damage: battle.damage[battle.loser.id],
hp: battle.loser.mainPokemon.hp
}
}
}
return JSON.stringify(response)
pokemon.build = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() for move in pokemon.moves).join("\n").toString()
pokemon.buildDebug = (pokemonId) ->
pokemon = new Pokemon pokemonId
return (move.toString() + " " + move.score for move in pokemon.debug.scoredMoves).join("\n").toString()
module.exports = pokemon
|
[
{
"context": "oggleDraft'\n\n enableLoadVsac: ->\n username = @$('#vsacUser')\n password = @$('#vsacPassword')\n if (user",
"end": 2232,
"score": 0.9262140989303589,
"start": 2220,
"tag": "USERNAME",
"value": "$('#vsacUser"
},
{
"context": " username = @$('#vsacUser')\n password = @$('#vsacPassword')\n if (username.val().length > 0) \n usern",
"end": 2267,
"score": 0.9793257117271423,
"start": 2255,
"tag": "PASSWORD",
"value": "vsacPassword"
}
] | app/assets/javascripts/views/import_measure_view.js.coffee | okeefm/bonnie | 0 | class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView
template: JST['import/import_measure']
context: ->
hqmfSetId = @model.get('hqmf_set_id') if @model?
measureTypeLabel = if @model?
if @model.get('type') is 'eh' then 'Eligible Hospital (EH)'
else if @model.get('type') is 'ep' then 'Eligible Professional (EP)'
calculationTypeLabel = if @model?
if @model.get('episode_of_care') is false and @model.get('continuous_variable') is false then 'Patient Based'
else if @model.get('episode_of_care') is true then 'Episode of Care'
else if @model.get('continuous_variable') is true then 'Continuous Variable'
currentRoute = Backbone.history.fragment
_(super).extend
titleSize: 4
dataSize: 8
token: $("meta[name='csrf-token']").attr('content')
dialogTitle: if @model? then @model.get('title') else "New Measure"
isUpdate: @model?
showLoadInformation: !@model? && @firstMeasure
measureTypeLabel: measureTypeLabel
calculationTypeLabel: calculationTypeLabel
hqmfSetId: hqmfSetId
redirectRoute: currentRoute
events:
rendered: ->
@$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')?
@$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible')
@$("input[type=radio]:checked").next().css("color","white")
@$('.date-picker').datepicker('setDate', moment().format('L'))
@$('.effective-date').hide()
'ready': 'setup'
'change input:file': 'enableLoad'
'keypress input:text': 'enableLoadVsac'
'keypress input:password': 'enableLoadVsac'
'change input[type=radio]': ->
@$('input[type=radio]').each (index, element) =>
if @$(element).prop("checked")
@$(element).next().css("color","white")
else
@$(element).next().css("color","")
'focus input': (e) -> if not @$(e.target).hasClass('date-picker') and $('.datepicker').is(':visible') then @$('.date-picker').datepicker('hide')
'change input[name="include_draft"]': 'toggleDraft'
enableLoadVsac: ->
username = @$('#vsacUser')
password = @$('#vsacPassword')
if (username.val().length > 0)
username.closest('.form-group').removeClass('has-error')
hasUser = true
if (password.val().length > 0)
password.closest('.form-group').removeClass('has-error')
hasPassword = true
@$('#loadButton').prop('disabled', !(hasUser && hasPassword))
enableLoad: ->
if @$('input:file').val().match /xml$/i
@$('#vsacSignIn').removeClass('hidden')
else
@$('#vsacSignIn').addClass('hidden')
@$('#loadButton').prop('disabled', !@$('input:file').val().length > 0)
toggleDraft: ->
isDraft = @$('#value_sets_draft').is(':checked')
if isDraft then @$('.effective-date').hide() else @$('.effective-date').show()
setup: ->
@importDialog = @$("#importMeasureDialog")
@importWait = @$("#pleaseWaitDialog")
@finalizeDialog = @$("#finalizeMeasureDialog")
display: ->
@importDialog.modal(
"backdrop" : "static",
"keyboard" : true,
"show" : true)
@$('.nice_input').bootstrapFileInput()
submit: ->
@importWait.modal(
"backdrop" : "static",
"keyboard" : false,
"show" : true)
@importDialog.modal('hide')
@$('form').submit()
# FIXME: Is anything additional required for cleaning up this view on close?
close: -> ''
| 204778 | class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView
template: JST['import/import_measure']
context: ->
hqmfSetId = @model.get('hqmf_set_id') if @model?
measureTypeLabel = if @model?
if @model.get('type') is 'eh' then 'Eligible Hospital (EH)'
else if @model.get('type') is 'ep' then 'Eligible Professional (EP)'
calculationTypeLabel = if @model?
if @model.get('episode_of_care') is false and @model.get('continuous_variable') is false then 'Patient Based'
else if @model.get('episode_of_care') is true then 'Episode of Care'
else if @model.get('continuous_variable') is true then 'Continuous Variable'
currentRoute = Backbone.history.fragment
_(super).extend
titleSize: 4
dataSize: 8
token: $("meta[name='csrf-token']").attr('content')
dialogTitle: if @model? then @model.get('title') else "New Measure"
isUpdate: @model?
showLoadInformation: !@model? && @firstMeasure
measureTypeLabel: measureTypeLabel
calculationTypeLabel: calculationTypeLabel
hqmfSetId: hqmfSetId
redirectRoute: currentRoute
events:
rendered: ->
@$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')?
@$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible')
@$("input[type=radio]:checked").next().css("color","white")
@$('.date-picker').datepicker('setDate', moment().format('L'))
@$('.effective-date').hide()
'ready': 'setup'
'change input:file': 'enableLoad'
'keypress input:text': 'enableLoadVsac'
'keypress input:password': 'enableLoadVsac'
'change input[type=radio]': ->
@$('input[type=radio]').each (index, element) =>
if @$(element).prop("checked")
@$(element).next().css("color","white")
else
@$(element).next().css("color","")
'focus input': (e) -> if not @$(e.target).hasClass('date-picker') and $('.datepicker').is(':visible') then @$('.date-picker').datepicker('hide')
'change input[name="include_draft"]': 'toggleDraft'
enableLoadVsac: ->
username = @$('#vsacUser')
password = @$('#<PASSWORD>')
if (username.val().length > 0)
username.closest('.form-group').removeClass('has-error')
hasUser = true
if (password.val().length > 0)
password.closest('.form-group').removeClass('has-error')
hasPassword = true
@$('#loadButton').prop('disabled', !(hasUser && hasPassword))
enableLoad: ->
if @$('input:file').val().match /xml$/i
@$('#vsacSignIn').removeClass('hidden')
else
@$('#vsacSignIn').addClass('hidden')
@$('#loadButton').prop('disabled', !@$('input:file').val().length > 0)
toggleDraft: ->
isDraft = @$('#value_sets_draft').is(':checked')
if isDraft then @$('.effective-date').hide() else @$('.effective-date').show()
setup: ->
@importDialog = @$("#importMeasureDialog")
@importWait = @$("#pleaseWaitDialog")
@finalizeDialog = @$("#finalizeMeasureDialog")
display: ->
@importDialog.modal(
"backdrop" : "static",
"keyboard" : true,
"show" : true)
@$('.nice_input').bootstrapFileInput()
submit: ->
@importWait.modal(
"backdrop" : "static",
"keyboard" : false,
"show" : true)
@importDialog.modal('hide')
@$('form').submit()
# FIXME: Is anything additional required for cleaning up this view on close?
close: -> ''
| true | class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView
template: JST['import/import_measure']
context: ->
hqmfSetId = @model.get('hqmf_set_id') if @model?
measureTypeLabel = if @model?
if @model.get('type') is 'eh' then 'Eligible Hospital (EH)'
else if @model.get('type') is 'ep' then 'Eligible Professional (EP)'
calculationTypeLabel = if @model?
if @model.get('episode_of_care') is false and @model.get('continuous_variable') is false then 'Patient Based'
else if @model.get('episode_of_care') is true then 'Episode of Care'
else if @model.get('continuous_variable') is true then 'Continuous Variable'
currentRoute = Backbone.history.fragment
_(super).extend
titleSize: 4
dataSize: 8
token: $("meta[name='csrf-token']").attr('content')
dialogTitle: if @model? then @model.get('title') else "New Measure"
isUpdate: @model?
showLoadInformation: !@model? && @firstMeasure
measureTypeLabel: measureTypeLabel
calculationTypeLabel: calculationTypeLabel
hqmfSetId: hqmfSetId
redirectRoute: currentRoute
events:
rendered: ->
@$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')?
@$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible')
@$("input[type=radio]:checked").next().css("color","white")
@$('.date-picker').datepicker('setDate', moment().format('L'))
@$('.effective-date').hide()
'ready': 'setup'
'change input:file': 'enableLoad'
'keypress input:text': 'enableLoadVsac'
'keypress input:password': 'enableLoadVsac'
'change input[type=radio]': ->
@$('input[type=radio]').each (index, element) =>
if @$(element).prop("checked")
@$(element).next().css("color","white")
else
@$(element).next().css("color","")
'focus input': (e) -> if not @$(e.target).hasClass('date-picker') and $('.datepicker').is(':visible') then @$('.date-picker').datepicker('hide')
'change input[name="include_draft"]': 'toggleDraft'
enableLoadVsac: ->
username = @$('#vsacUser')
password = @$('#PI:PASSWORD:<PASSWORD>END_PI')
if (username.val().length > 0)
username.closest('.form-group').removeClass('has-error')
hasUser = true
if (password.val().length > 0)
password.closest('.form-group').removeClass('has-error')
hasPassword = true
@$('#loadButton').prop('disabled', !(hasUser && hasPassword))
enableLoad: ->
if @$('input:file').val().match /xml$/i
@$('#vsacSignIn').removeClass('hidden')
else
@$('#vsacSignIn').addClass('hidden')
@$('#loadButton').prop('disabled', !@$('input:file').val().length > 0)
toggleDraft: ->
isDraft = @$('#value_sets_draft').is(':checked')
if isDraft then @$('.effective-date').hide() else @$('.effective-date').show()
setup: ->
@importDialog = @$("#importMeasureDialog")
@importWait = @$("#pleaseWaitDialog")
@finalizeDialog = @$("#finalizeMeasureDialog")
display: ->
@importDialog.modal(
"backdrop" : "static",
"keyboard" : true,
"show" : true)
@$('.nice_input').bootstrapFileInput()
submit: ->
@importWait.modal(
"backdrop" : "static",
"keyboard" : false,
"show" : true)
@importDialog.modal('hide')
@$('form').submit()
# FIXME: Is anything additional required for cleaning up this view on close?
close: -> ''
|
[
{
"context": " .set(\"passphrase\",\"${7:1234}\") #Optional passphrase to be added to ssh key",
"end": 1567,
"score": 0.8598355650901794,
"start": 1561,
"tag": "PASSWORD",
"value": "7:1234"
}
] | snippets/flint-ssh-connector.cson | manoj-dhadke/flint-atom | 0 | ##########################################################################
#
# INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL
# __________________
#
# (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE
# All Rights Reserved.
# Product / Project: Flint IT Automation Platform
# NOTICE: All information contained herein is, and remains
# the property of INFIVERVE TECHNOLOGIES PTE LIMITED.
# The intellectual and technical concepts contained
# herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED.
# Dissemination of this information or any form of reproduction of this material
# is strictly forbidden unless prior written permission is obtained
# from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE.
'.source.ruby':
'flint-ssh-connector-template':
'prefix': 'call-ssh-connector'
'body': """
@log.trace("Calling SSH Connector...")
${1:connector_name}_response = @call.connector("${1:connector_name}")
.set("target","${2:IP/hostname}") #Target machine hostname or ip address
.set("port",${3:22}) #Target machine port,default 22
.set("type","${4:exec}") #Shell execution type:shell or exec,default exec
.set("username","${5:username}") #Target machine username
.set("password","${6:password}") #Target machine password
.set("passphrase","${7:1234}") #Optional passphrase to be added to ssh key
.set("key-file","${8:id_rsa}") #Optional ssh key file absolute path
.set("command","${9:command}") #Command to be executed on target machine
.set("timeout",60000) #Optional timeout in milliseconds
.sync
if ${1:connector_name}_response.exitcode == 0
@log.info("Success")
${1:connector_name}_output = ${1:connector_name}_response.get("result")
end
"""
| 74778 | ##########################################################################
#
# INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL
# __________________
#
# (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE
# All Rights Reserved.
# Product / Project: Flint IT Automation Platform
# NOTICE: All information contained herein is, and remains
# the property of INFIVERVE TECHNOLOGIES PTE LIMITED.
# The intellectual and technical concepts contained
# herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED.
# Dissemination of this information or any form of reproduction of this material
# is strictly forbidden unless prior written permission is obtained
# from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE.
'.source.ruby':
'flint-ssh-connector-template':
'prefix': 'call-ssh-connector'
'body': """
@log.trace("Calling SSH Connector...")
${1:connector_name}_response = @call.connector("${1:connector_name}")
.set("target","${2:IP/hostname}") #Target machine hostname or ip address
.set("port",${3:22}) #Target machine port,default 22
.set("type","${4:exec}") #Shell execution type:shell or exec,default exec
.set("username","${5:username}") #Target machine username
.set("password","${6:password}") #Target machine password
.set("passphrase","${<PASSWORD>}") #Optional passphrase to be added to ssh key
.set("key-file","${8:id_rsa}") #Optional ssh key file absolute path
.set("command","${9:command}") #Command to be executed on target machine
.set("timeout",60000) #Optional timeout in milliseconds
.sync
if ${1:connector_name}_response.exitcode == 0
@log.info("Success")
${1:connector_name}_output = ${1:connector_name}_response.get("result")
end
"""
| true | ##########################################################################
#
# INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL
# __________________
#
# (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE
# All Rights Reserved.
# Product / Project: Flint IT Automation Platform
# NOTICE: All information contained herein is, and remains
# the property of INFIVERVE TECHNOLOGIES PTE LIMITED.
# The intellectual and technical concepts contained
# herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED.
# Dissemination of this information or any form of reproduction of this material
# is strictly forbidden unless prior written permission is obtained
# from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE.
'.source.ruby':
'flint-ssh-connector-template':
'prefix': 'call-ssh-connector'
'body': """
@log.trace("Calling SSH Connector...")
${1:connector_name}_response = @call.connector("${1:connector_name}")
.set("target","${2:IP/hostname}") #Target machine hostname or ip address
.set("port",${3:22}) #Target machine port,default 22
.set("type","${4:exec}") #Shell execution type:shell or exec,default exec
.set("username","${5:username}") #Target machine username
.set("password","${6:password}") #Target machine password
.set("passphrase","${PI:PASSWORD:<PASSWORD>END_PI}") #Optional passphrase to be added to ssh key
.set("key-file","${8:id_rsa}") #Optional ssh key file absolute path
.set("command","${9:command}") #Command to be executed on target machine
.set("timeout",60000) #Optional timeout in milliseconds
.sync
if ${1:connector_name}_response.exitcode == 0
@log.info("Success")
${1:connector_name}_output = ${1:connector_name}_response.get("result")
end
"""
|
[
{
"context": "ptions', 4, ->\n product1 = new @Product(name: \"testA\", cost: 20)\n product2 = new @Product(name: \"te",
"end": 605,
"score": 0.9785475730895996,
"start": 600,
"tag": "NAME",
"value": "testA"
},
{
"context": "tA\", cost: 20)\n product2 = new @Product(name: \"testB\", cost: 10)\n @adapter.perform 'create', produc",
"end": 658,
"score": 0.9641242027282715,
"start": 653,
"tag": "NAME",
"value": "testB"
},
{
"context": "ly`', ->\n\n product = new @Product\n name: 'foo'\n cost: 50\n\n @adapter.perform 'create', p",
"end": 1466,
"score": 0.894357442855835,
"start": 1463,
"tag": "NAME",
"value": "foo"
},
{
"context": ", {name: 'foo'}\n\n foundRecord.set 'name', 'bar'\n foundRecord.set 'cost', 75\n\n @ada",
"end": 1770,
"score": 0.6055670976638794,
"start": 1767,
"tag": "NAME",
"value": "bar"
},
{
"context": "pt`', ->\n\n product = new @Product\n name: 'foo'\n cost: 50\n\n @adapter.perform 'create', p",
"end": 2216,
"score": 0.9876713752746582,
"start": 2213,
"tag": "NAME",
"value": "foo"
},
{
"context": ">\n deepEqual foundRecord.toJSON(), {name: 'foo'}\n\n foundRecord.set 'name', 'bar'\n ",
"end": 2476,
"score": 0.9102297425270081,
"start": 2473,
"tag": "NAME",
"value": "foo"
},
{
"context": ", {name: 'foo'}\n\n foundRecord.set 'name', 'bar'\n foundRecord.set 'cost', 75\n\n @ada",
"end": 2516,
"score": 0.9896050691604614,
"start": 2513,
"tag": "NAME",
"value": "bar"
}
] | tests/batman/storage_adapter/local_storage_test.coffee | davidcornu/batman | 0 | if typeof require isnt 'undefined'
{sharedStorageTestSuite} = require('./storage_adapter_helper')
else
{sharedStorageTestSuite} = window
if typeof window.localStorage isnt 'undefined'
QUnit.module "Batman.LocalStorage",
setup: ->
window.localStorage.clear()
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new Batman.LocalStorage(@Product)
@Product.persist @adapter
sharedStorageTestSuite({})
asyncTest 'reading many from storage: should callback with only records matching the options', 4, ->
product1 = new @Product(name: "testA", cost: 20)
product2 = new @Product(name: "testB", cost: 10)
@adapter.perform 'create', product1, {}, (err, createdRecord1) =>
throw err if err
@adapter.perform 'create', product2, {}, (err, createdRecord2) =>
throw err if err
@adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) =>
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testB"
@adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) ->
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testA"
QUnit.start()
asyncTest 'create or update whitelists attributes when supplied `only`', ->
product = new @Product
name: 'foo'
cost: 50
@adapter.perform 'create', product, {only: ['id', 'name']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: 'foo'}
foundRecord.set 'name', 'bar'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {only: ['cost']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
asyncTest 'create or update blacklists attributes when supplied `except`', ->
product = new @Product
name: 'foo'
cost: 50
@adapter.perform 'create', product, {except: ['cost']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: 'foo'}
foundRecord.set 'name', 'bar'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {except: ['name']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
| 117612 | if typeof require isnt 'undefined'
{sharedStorageTestSuite} = require('./storage_adapter_helper')
else
{sharedStorageTestSuite} = window
if typeof window.localStorage isnt 'undefined'
QUnit.module "Batman.LocalStorage",
setup: ->
window.localStorage.clear()
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new Batman.LocalStorage(@Product)
@Product.persist @adapter
sharedStorageTestSuite({})
asyncTest 'reading many from storage: should callback with only records matching the options', 4, ->
product1 = new @Product(name: "<NAME>", cost: 20)
product2 = new @Product(name: "<NAME>", cost: 10)
@adapter.perform 'create', product1, {}, (err, createdRecord1) =>
throw err if err
@adapter.perform 'create', product2, {}, (err, createdRecord2) =>
throw err if err
@adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) =>
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testB"
@adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) ->
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testA"
QUnit.start()
asyncTest 'create or update whitelists attributes when supplied `only`', ->
product = new @Product
name: '<NAME>'
cost: 50
@adapter.perform 'create', product, {only: ['id', 'name']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: 'foo'}
foundRecord.set 'name', '<NAME>'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {only: ['cost']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
asyncTest 'create or update blacklists attributes when supplied `except`', ->
product = new @Product
name: '<NAME>'
cost: 50
@adapter.perform 'create', product, {except: ['cost']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: '<NAME>'}
foundRecord.set 'name', '<NAME>'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {except: ['name']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
| true | if typeof require isnt 'undefined'
{sharedStorageTestSuite} = require('./storage_adapter_helper')
else
{sharedStorageTestSuite} = window
if typeof window.localStorage isnt 'undefined'
QUnit.module "Batman.LocalStorage",
setup: ->
window.localStorage.clear()
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new Batman.LocalStorage(@Product)
@Product.persist @adapter
sharedStorageTestSuite({})
asyncTest 'reading many from storage: should callback with only records matching the options', 4, ->
product1 = new @Product(name: "PI:NAME:<NAME>END_PI", cost: 20)
product2 = new @Product(name: "PI:NAME:<NAME>END_PI", cost: 10)
@adapter.perform 'create', product1, {}, (err, createdRecord1) =>
throw err if err
@adapter.perform 'create', product2, {}, (err, createdRecord2) =>
throw err if err
@adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) =>
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testB"
@adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) ->
throw err if err
equal readProducts.length, 1
deepEqual readProducts[0].get('name'), "testA"
QUnit.start()
asyncTest 'create or update whitelists attributes when supplied `only`', ->
product = new @Product
name: 'PI:NAME:<NAME>END_PI'
cost: 50
@adapter.perform 'create', product, {only: ['id', 'name']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: 'foo'}
foundRecord.set 'name', 'PI:NAME:<NAME>END_PI'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {only: ['cost']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
asyncTest 'create or update blacklists attributes when supplied `except`', ->
product = new @Product
name: 'PI:NAME:<NAME>END_PI'
cost: 50
@adapter.perform 'create', product, {except: ['cost']}, (err, createdRecord) =>
@adapter.perform 'read', new product.constructor(createdRecord.get('id')), {}, (err, foundRecord) =>
deepEqual foundRecord.toJSON(), {name: 'PI:NAME:<NAME>END_PI'}
foundRecord.set 'name', 'PI:NAME:<NAME>END_PI'
foundRecord.set 'cost', 75
@adapter.perform 'update', foundRecord, {except: ['name']}, (err, updatedRecord) =>
@adapter.perform 'read', new product.constructor(updatedRecord.get('id')), {}, (err, foundRecord) ->
deepEqual foundRecord.toJSON(), {cost: 75}
QUnit.start()
|
[
{
"context": "sigchains, with\n# sibkeys and multiple PGP keys. \"t_frank\" is a user who started with a PGP key\n# generated",
"end": 438,
"score": 0.9297051429748535,
"start": 431,
"tag": "USERNAME",
"value": "t_frank"
},
{
"context": "th the Go client to generate a\n# second PGP key. \"t_george\" is a user who signed up on the Go client and jus",
"end": 580,
"score": 0.9561238288879395,
"start": 572,
"tag": "USERNAME",
"value": "t_george"
},
{
"context": "gerprint://DEFA06E52543544F'\nfrank_subkeys = [\n '5BDED63232F876C7'\n '15B45E78C3852457'\n]\n\ngeorge_assertions = 'fin",
"end": 926,
"score": 0.999606728553772,
"start": 910,
"tag": "KEY",
"value": "5BDED63232F876C7"
},
{
"context": "43544F'\nfrank_subkeys = [\n '5BDED63232F876C7'\n '15B45E78C3852457'\n]\n\ngeorge_assertions = 'fingerprint://84C091DD53",
"end": 947,
"score": 0.9995930194854736,
"start": 931,
"tag": "KEY",
"value": "15B45E78C3852457"
},
{
"context": "erprint://604556E877D86C22'\ngeorge_subkeys = [\n 'A7F041D5A5F18962'\n 'B7C24335E23D3320'\n]\n\nme = null\n\nexports.init ",
"end": 1077,
"score": 0.9996210932731628,
"start": 1061,
"tag": "KEY",
"value": "A7F041D5A5F18962"
},
{
"context": "86C22'\ngeorge_subkeys = [\n 'A7F041D5A5F18962'\n 'B7C24335E23D3320'\n]\n\nme = null\n\nexports.init = (T,cb) ->\n await s",
"end": 1098,
"score": 0.9995805025100708,
"start": 1082,
"tag": "KEY",
"value": "B7C24335E23D3320"
},
{
"context": "ey_id?\n recipient_key_ids.push(packet.key_id.toString('hex').toUpperCase())\n T.equal subkeys.sort(), recipient_key_ids.sort(",
"end": 3122,
"score": 0.9392253756523132,
"start": 3092,
"tag": "KEY",
"value": "toString('hex').toUpperCase())"
},
{
"context": " await encrypt_test {\n T,\n recipient: \"t_frank\",\n assertions: frank_assertions,\n subke",
"end": 3277,
"score": 0.9845798015594482,
"start": 3270,
"tag": "USERNAME",
"value": "t_frank"
},
{
"context": " await encrypt_test {\n T,\n recipient: \"t_george\",\n assertions: george_assertions,\n subk",
"end": 3465,
"score": 0.9617624878883362,
"start": 3457,
"tag": "USERNAME",
"value": "t_george"
}
] | test/files/8_multikey.iced | AngelKey/Angelkey.nodeclient | 151 | fs = require 'fs'
path = require 'path'
child_process = require 'child_process'
{User, signup} = require '../lib/user'
{prng} = require 'crypto'
{make_esc} = require 'iced-error'
kbpgp = require 'kbpgp'
libkeybase = require 'libkeybase'
# These tests are for exercising compatibility with the Go client. In
# particular, we want to interact with users who have new-style sigchains, with
# sibkeys and multiple PGP keys. "t_frank" is a user who started with a PGP key
# generated on the site but then logged in with the Go client to generate a
# second PGP key. "t_george" is a user who signed up on the Go client and just
# used that to generate two PGP keys. We check that encrypt works against all
# the recipient's keys, and that the implicit `id` passes against fingerprint
# assertions.
frank_assertions = 'fingerprint://C6759000770E0C4D && fingerprint://DEFA06E52543544F'
frank_subkeys = [
'5BDED63232F876C7'
'15B45E78C3852457'
]
george_assertions = 'fingerprint://84C091DD53BF666B && fingerprint://604556E877D86C22'
george_subkeys = [
'A7F041D5A5F18962'
'B7C24335E23D3320'
]
me = null
exports.init = (T,cb) ->
await signup T, "multi", {}, defer _me
me = _me
cb()
exports.cache_test = (T, cb) ->
# Make sure we're caching signatures properly by getting some debug info
# about how many unboxes we do. libkeybase provides a global counter of all
# unboxes, and we've added some code to the node client to write that counter
# to a file pointed to by KEYBASE_DEBUG_UNBOX_COUNT_FILE.
# First, clear any existing cache.
cache_path = path.join me.homedir, '.local/share/keybase/keybase.idb'
await child_process.exec "rm -rf #{cache_path}", defer()
# Now set the debug file var and run an id.
count_file = path.join me.homedir, 'debug_unbox_count'
process.env.KEYBASE_DEBUG_UNBOX_COUNT_FILE = count_file
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "5", unbox_count, "expecting 5 unboxes"
# Do it again. This time there should be no unboxes.
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "0", unbox_count, "expecting no more unboxes"
cb()
exports.colon_slash_slash_test = (T, cb) ->
# My changes to user loading broke commands of the form
# keybase id foo://bar
# Exercise those to make sure they stay unbroken, in this case using
# t_alice's PGP fingerprint.
await me.keybase {args: ["id", "fingerprint://9C7927C0BDFDADF9"]}, defer err, out
T.no_error err
cb()
encrypt_test = ({T, recipient, assertions, subkeys}, cb) ->
args = ["encrypt", recipient, "-m", "foo", "--batch", "--assert", assertions]
await me.keybase {args}, defer err, out
T.no_error err
armored = out.toString()
[err, msg] = kbpgp.armor.decode armored
T.no_error err
[err, packets] = kbpgp.parser.parse msg.body
T.no_error err
recipient_key_ids = []
for packet in packets
if packet.key_id?
recipient_key_ids.push(packet.key_id.toString('hex').toUpperCase())
T.equal subkeys.sort(), recipient_key_ids.sort()
cb()
exports.encrypt_to_frank = (T, cb) ->
await encrypt_test {
T,
recipient: "t_frank",
assertions: frank_assertions,
subkeys: frank_subkeys
}, defer()
cb()
exports.encrypt_to_george = (T, cb) ->
await encrypt_test {
T,
recipient: "t_george",
assertions: george_assertions,
subkeys: george_subkeys
}, defer()
cb()
| 102429 | fs = require 'fs'
path = require 'path'
child_process = require 'child_process'
{User, signup} = require '../lib/user'
{prng} = require 'crypto'
{make_esc} = require 'iced-error'
kbpgp = require 'kbpgp'
libkeybase = require 'libkeybase'
# These tests are for exercising compatibility with the Go client. In
# particular, we want to interact with users who have new-style sigchains, with
# sibkeys and multiple PGP keys. "t_frank" is a user who started with a PGP key
# generated on the site but then logged in with the Go client to generate a
# second PGP key. "t_george" is a user who signed up on the Go client and just
# used that to generate two PGP keys. We check that encrypt works against all
# the recipient's keys, and that the implicit `id` passes against fingerprint
# assertions.
frank_assertions = 'fingerprint://C6759000770E0C4D && fingerprint://DEFA06E52543544F'
frank_subkeys = [
'<KEY>'
'<KEY>'
]
george_assertions = 'fingerprint://84C091DD53BF666B && fingerprint://604556E877D86C22'
george_subkeys = [
'<KEY>'
'<KEY>'
]
me = null
exports.init = (T,cb) ->
await signup T, "multi", {}, defer _me
me = _me
cb()
exports.cache_test = (T, cb) ->
# Make sure we're caching signatures properly by getting some debug info
# about how many unboxes we do. libkeybase provides a global counter of all
# unboxes, and we've added some code to the node client to write that counter
# to a file pointed to by KEYBASE_DEBUG_UNBOX_COUNT_FILE.
# First, clear any existing cache.
cache_path = path.join me.homedir, '.local/share/keybase/keybase.idb'
await child_process.exec "rm -rf #{cache_path}", defer()
# Now set the debug file var and run an id.
count_file = path.join me.homedir, 'debug_unbox_count'
process.env.KEYBASE_DEBUG_UNBOX_COUNT_FILE = count_file
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "5", unbox_count, "expecting 5 unboxes"
# Do it again. This time there should be no unboxes.
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "0", unbox_count, "expecting no more unboxes"
cb()
exports.colon_slash_slash_test = (T, cb) ->
# My changes to user loading broke commands of the form
# keybase id foo://bar
# Exercise those to make sure they stay unbroken, in this case using
# t_alice's PGP fingerprint.
await me.keybase {args: ["id", "fingerprint://9C7927C0BDFDADF9"]}, defer err, out
T.no_error err
cb()
encrypt_test = ({T, recipient, assertions, subkeys}, cb) ->
args = ["encrypt", recipient, "-m", "foo", "--batch", "--assert", assertions]
await me.keybase {args}, defer err, out
T.no_error err
armored = out.toString()
[err, msg] = kbpgp.armor.decode armored
T.no_error err
[err, packets] = kbpgp.parser.parse msg.body
T.no_error err
recipient_key_ids = []
for packet in packets
if packet.key_id?
recipient_key_ids.push(packet.key_id.<KEY>
T.equal subkeys.sort(), recipient_key_ids.sort()
cb()
exports.encrypt_to_frank = (T, cb) ->
await encrypt_test {
T,
recipient: "t_frank",
assertions: frank_assertions,
subkeys: frank_subkeys
}, defer()
cb()
exports.encrypt_to_george = (T, cb) ->
await encrypt_test {
T,
recipient: "t_george",
assertions: george_assertions,
subkeys: george_subkeys
}, defer()
cb()
| true | fs = require 'fs'
path = require 'path'
child_process = require 'child_process'
{User, signup} = require '../lib/user'
{prng} = require 'crypto'
{make_esc} = require 'iced-error'
kbpgp = require 'kbpgp'
libkeybase = require 'libkeybase'
# These tests are for exercising compatibility with the Go client. In
# particular, we want to interact with users who have new-style sigchains, with
# sibkeys and multiple PGP keys. "t_frank" is a user who started with a PGP key
# generated on the site but then logged in with the Go client to generate a
# second PGP key. "t_george" is a user who signed up on the Go client and just
# used that to generate two PGP keys. We check that encrypt works against all
# the recipient's keys, and that the implicit `id` passes against fingerprint
# assertions.
frank_assertions = 'fingerprint://C6759000770E0C4D && fingerprint://DEFA06E52543544F'
frank_subkeys = [
'PI:KEY:<KEY>END_PI'
'PI:KEY:<KEY>END_PI'
]
george_assertions = 'fingerprint://84C091DD53BF666B && fingerprint://604556E877D86C22'
george_subkeys = [
'PI:KEY:<KEY>END_PI'
'PI:KEY:<KEY>END_PI'
]
me = null
exports.init = (T,cb) ->
await signup T, "multi", {}, defer _me
me = _me
cb()
exports.cache_test = (T, cb) ->
# Make sure we're caching signatures properly by getting some debug info
# about how many unboxes we do. libkeybase provides a global counter of all
# unboxes, and we've added some code to the node client to write that counter
# to a file pointed to by KEYBASE_DEBUG_UNBOX_COUNT_FILE.
# First, clear any existing cache.
cache_path = path.join me.homedir, '.local/share/keybase/keybase.idb'
await child_process.exec "rm -rf #{cache_path}", defer()
# Now set the debug file var and run an id.
count_file = path.join me.homedir, 'debug_unbox_count'
process.env.KEYBASE_DEBUG_UNBOX_COUNT_FILE = count_file
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "5", unbox_count, "expecting 5 unboxes"
# Do it again. This time there should be no unboxes.
await me.keybase {args: ["id", "t_frank"]}, defer err, out
T.no_error err
unbox_count = fs.readFileSync(count_file).toString()
T.equal "0", unbox_count, "expecting no more unboxes"
cb()
exports.colon_slash_slash_test = (T, cb) ->
# My changes to user loading broke commands of the form
# keybase id foo://bar
# Exercise those to make sure they stay unbroken, in this case using
# t_alice's PGP fingerprint.
await me.keybase {args: ["id", "fingerprint://9C7927C0BDFDADF9"]}, defer err, out
T.no_error err
cb()
encrypt_test = ({T, recipient, assertions, subkeys}, cb) ->
args = ["encrypt", recipient, "-m", "foo", "--batch", "--assert", assertions]
await me.keybase {args}, defer err, out
T.no_error err
armored = out.toString()
[err, msg] = kbpgp.armor.decode armored
T.no_error err
[err, packets] = kbpgp.parser.parse msg.body
T.no_error err
recipient_key_ids = []
for packet in packets
if packet.key_id?
recipient_key_ids.push(packet.key_id.PI:KEY:<KEY>END_PI
T.equal subkeys.sort(), recipient_key_ids.sort()
cb()
exports.encrypt_to_frank = (T, cb) ->
await encrypt_test {
T,
recipient: "t_frank",
assertions: frank_assertions,
subkeys: frank_subkeys
}, defer()
cb()
exports.encrypt_to_george = (T, cb) ->
await encrypt_test {
T,
recipient: "t_george",
assertions: george_assertions,
subkeys: george_subkeys
}, defer()
cb()
|
[
{
"context": "then state else Person.state\n @name = 'nick'\n @state = 'fl'\n @defaultUs",
"end": 919,
"score": 0.9604515433311462,
"start": 915,
"tag": "NAME",
"value": "nick"
},
{
"context": "rect ', ->\n expect(@usage.name).toEqual(@name)\n expect(@usage.state).toEqual(@state)",
"end": 1605,
"score": 0.6489640474319458,
"start": 1600,
"tag": "USERNAME",
"value": "@name"
}
] | SafetyNet_Mobile/www/lib/angular-google-maps-master/spec/coffee/directives/api/utils/base-object.spec.coffee | donh/pheonix | 1 | describe 'oo.BaseObject', ->
beforeEach ->
module 'uiGmapgoogle-maps.directives.api.utils'
inject ['uiGmapBaseObject', (BaseObject) =>
@subject = BaseObject
PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
PersonAttributes =
p_name: 'no_name'
state: 'no_state'
@PersonAttributes = PersonAttributes
class Person extends BaseObject
@include PersonModule
@extend PersonAttributes
constructor: (name, state)->
@name = if name? then name else Person.p_name
@state = if state? then state else Person.state
@name = 'nick'
@state = 'fl'
@defaultUsage = new Person()
@usage = new Person(@name, @state)
]
it 'exists ~ you loaded the script!', ->
expect(@subject?).toEqual(true)
describe 'include specs', ->
it 'defaults attributes exist', ->
expect(@defaultUsage.name?).toEqual(true)
expect(@defaultUsage.name?).toEqual(true)
it 'defaults attributes are correct', ->
expect(@defaultUsage.name).toEqual(@PersonAttributes.p_name)
expect(@defaultUsage.state).toEqual(@PersonAttributes.state)
it 'subject attributes are correct ', ->
expect(@usage.name).toEqual(@name)
expect(@usage.state).toEqual(@state)
describe 'extend specs', ->
it 'defaults functions exist', ->
expect(@defaultUsage.changePersonName?).toEqual(true)
expect(@defaultUsage.killPersonsName?).toEqual(true)
it 'subject functions act correctly', ->
p = @defaultUsage.changePersonName(angular.copy(@defaultUsage), 'john')
p2 = @defaultUsage.killPersonsName(@defaultUsage)
expect(p.name).toEqual('john')
expect(p2.name).toEqual(undefined)
| 55780 | describe 'oo.BaseObject', ->
beforeEach ->
module 'uiGmapgoogle-maps.directives.api.utils'
inject ['uiGmapBaseObject', (BaseObject) =>
@subject = BaseObject
PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
PersonAttributes =
p_name: 'no_name'
state: 'no_state'
@PersonAttributes = PersonAttributes
class Person extends BaseObject
@include PersonModule
@extend PersonAttributes
constructor: (name, state)->
@name = if name? then name else Person.p_name
@state = if state? then state else Person.state
@name = '<NAME>'
@state = 'fl'
@defaultUsage = new Person()
@usage = new Person(@name, @state)
]
it 'exists ~ you loaded the script!', ->
expect(@subject?).toEqual(true)
describe 'include specs', ->
it 'defaults attributes exist', ->
expect(@defaultUsage.name?).toEqual(true)
expect(@defaultUsage.name?).toEqual(true)
it 'defaults attributes are correct', ->
expect(@defaultUsage.name).toEqual(@PersonAttributes.p_name)
expect(@defaultUsage.state).toEqual(@PersonAttributes.state)
it 'subject attributes are correct ', ->
expect(@usage.name).toEqual(@name)
expect(@usage.state).toEqual(@state)
describe 'extend specs', ->
it 'defaults functions exist', ->
expect(@defaultUsage.changePersonName?).toEqual(true)
expect(@defaultUsage.killPersonsName?).toEqual(true)
it 'subject functions act correctly', ->
p = @defaultUsage.changePersonName(angular.copy(@defaultUsage), 'john')
p2 = @defaultUsage.killPersonsName(@defaultUsage)
expect(p.name).toEqual('john')
expect(p2.name).toEqual(undefined)
| true | describe 'oo.BaseObject', ->
beforeEach ->
module 'uiGmapgoogle-maps.directives.api.utils'
inject ['uiGmapBaseObject', (BaseObject) =>
@subject = BaseObject
PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
PersonAttributes =
p_name: 'no_name'
state: 'no_state'
@PersonAttributes = PersonAttributes
class Person extends BaseObject
@include PersonModule
@extend PersonAttributes
constructor: (name, state)->
@name = if name? then name else Person.p_name
@state = if state? then state else Person.state
@name = 'PI:NAME:<NAME>END_PI'
@state = 'fl'
@defaultUsage = new Person()
@usage = new Person(@name, @state)
]
it 'exists ~ you loaded the script!', ->
expect(@subject?).toEqual(true)
describe 'include specs', ->
it 'defaults attributes exist', ->
expect(@defaultUsage.name?).toEqual(true)
expect(@defaultUsage.name?).toEqual(true)
it 'defaults attributes are correct', ->
expect(@defaultUsage.name).toEqual(@PersonAttributes.p_name)
expect(@defaultUsage.state).toEqual(@PersonAttributes.state)
it 'subject attributes are correct ', ->
expect(@usage.name).toEqual(@name)
expect(@usage.state).toEqual(@state)
describe 'extend specs', ->
it 'defaults functions exist', ->
expect(@defaultUsage.changePersonName?).toEqual(true)
expect(@defaultUsage.killPersonsName?).toEqual(true)
it 'subject functions act correctly', ->
p = @defaultUsage.changePersonName(angular.copy(@defaultUsage), 'john')
p2 = @defaultUsage.killPersonsName(@defaultUsage)
expect(p.name).toEqual('john')
expect(p2.name).toEqual(undefined)
|
[
{
"context": "more details about restler see https://github.com/danwrong/restler.\n#\n# It also adds `.fromRest` method to p",
"end": 202,
"score": 0.9996769428253174,
"start": 194,
"tag": "USERNAME",
"value": "danwrong"
},
{
"context": "json',\n# multipart: true\n# username: 'danwrong'\n# password: 'wouldntyouliketoknow'\n# ",
"end": 2452,
"score": 0.9996568560600281,
"start": 2444,
"tag": "USERNAME",
"value": "danwrong"
},
{
"context": "e\n# username: 'danwrong'\n# password: 'wouldntyouliketoknow'\n# data:\n# 'sound[message]': 'hello",
"end": 2493,
"score": 0.9989636540412903,
"start": 2473,
"tag": "PASSWORD",
"value": "wouldntyouliketoknow"
}
] | src/mixin/RestMixin.coffee | tetrapi/node-datapumps | 300 | # Mixin to interact with REST services.
#
# This mixin wraps and promisifies the restler library methods, like .get(), .post() or
# .del(). For more details about restler see https://github.com/danwrong/restler.
#
# It also adds `.fromRest` method to pump, which fills input buffer from results of a REST service
# query.
#
# Use case 1: filling pump from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .fromRest
# query: -> @get 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# .process (user) ->
# # ...
# ```
#
# `.fromRest()` has an object argument. The `query` key is required, it must be a callback function
# which returns a promise that fulfills when the query is completed and returns with the query
# results. The query results must be an array. Most of the times, `.get()` or `.post()` method will
# be sufficient combined with mapping of query results (`resultMapping` key).
#
# Use `resultMapping` key when you need to map a results of the REST service to an array. The value
# of the key should be a function that receives REST query result in the first argument and returns
# array to be filled in the input buffer.
#
# REST service may be paginated, you can query those like this:
# ```js
# pump
# .mixin RestMixin
# .fromRest
# query: (nextPage) -> @get nextPage ? 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# nextPage: (response) -> response.result.paging.nextPage
# ```
# Only two things to note when using paginated REST service:
# * `nextPage` key is a callback which may return anything other than undefined or null to continue
# to next page.
# * `query` will receive the return value of `nextPage` callback. It will receive undefined on the
# first call.
#
# Use case 2: enriching content from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) =>
# @get 'http://someservice.io/api/v1/user/' + data.username
# .then (response) =>
# data.email = response.result.email
# @copy data
# ```
#
# Use case 3: output to a REST service
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) ->
# @post 'https://twaud.io/api/v1/upload.json',
# multipart: true
# username: 'danwrong'
# password: 'wouldntyouliketoknow'
# data:
# 'sound[message]': 'hello from restler!'
# 'sound[file]': @file('doug-e-fresh_the-show.mp3', null, 321567, null, 'audio/mpeg')
# ```
#
Promise = require 'bluebird'
restler = require 'restler'
module.exports = RestMixin = (target) ->
_wrapMethod target, 'get'
_wrapMethod target, 'post'
_wrapMethod target, 'put'
_wrapMethod target, 'del'
_wrapMethod target, 'head'
_wrapMethod target, 'patch'
_wrapMethod target, 'json'
_wrapMethod target, 'postJson'
_wrapMethod target, 'putJson'
target.file = ->
restler.file.apply restler, arguments
target.fromRest = (config) ->
throw new Error 'query key is required' if !config?.query
config.resultMapping ?= (result) -> result
config.nextPage ?= -> undefined
@from @createBuffer()
queryAndWriteInputBuffer = (nextPage) =>
config.query.apply @, [ nextPage ]
.then (response) =>
@from().writeArrayAsync(config.resultMapping(response))
.done =>
nextPage = config.nextPage(response)
if (nextPage is undefined) or (nextPage is null)
@from().seal()
else
queryAndWriteInputBuffer(nextPage)
queryAndWriteInputBuffer(undefined)
@
_wrapMethod = (target, methodName) ->
target[methodName] = ->
methodArgs = arguments
new Promise (resolve, reject) ->
restler[methodName].apply(restler, methodArgs)
.on 'complete', (result, response) ->
if result instanceof Error
reject result
else
response.result = result
resolve response
| 81652 | # Mixin to interact with REST services.
#
# This mixin wraps and promisifies the restler library methods, like .get(), .post() or
# .del(). For more details about restler see https://github.com/danwrong/restler.
#
# It also adds `.fromRest` method to pump, which fills input buffer from results of a REST service
# query.
#
# Use case 1: filling pump from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .fromRest
# query: -> @get 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# .process (user) ->
# # ...
# ```
#
# `.fromRest()` has an object argument. The `query` key is required, it must be a callback function
# which returns a promise that fulfills when the query is completed and returns with the query
# results. The query results must be an array. Most of the times, `.get()` or `.post()` method will
# be sufficient combined with mapping of query results (`resultMapping` key).
#
# Use `resultMapping` key when you need to map a results of the REST service to an array. The value
# of the key should be a function that receives REST query result in the first argument and returns
# array to be filled in the input buffer.
#
# REST service may be paginated, you can query those like this:
# ```js
# pump
# .mixin RestMixin
# .fromRest
# query: (nextPage) -> @get nextPage ? 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# nextPage: (response) -> response.result.paging.nextPage
# ```
# Only two things to note when using paginated REST service:
# * `nextPage` key is a callback which may return anything other than undefined or null to continue
# to next page.
# * `query` will receive the return value of `nextPage` callback. It will receive undefined on the
# first call.
#
# Use case 2: enriching content from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) =>
# @get 'http://someservice.io/api/v1/user/' + data.username
# .then (response) =>
# data.email = response.result.email
# @copy data
# ```
#
# Use case 3: output to a REST service
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) ->
# @post 'https://twaud.io/api/v1/upload.json',
# multipart: true
# username: 'danwrong'
# password: '<PASSWORD>'
# data:
# 'sound[message]': 'hello from restler!'
# 'sound[file]': @file('doug-e-fresh_the-show.mp3', null, 321567, null, 'audio/mpeg')
# ```
#
Promise = require 'bluebird'
restler = require 'restler'
module.exports = RestMixin = (target) ->
_wrapMethod target, 'get'
_wrapMethod target, 'post'
_wrapMethod target, 'put'
_wrapMethod target, 'del'
_wrapMethod target, 'head'
_wrapMethod target, 'patch'
_wrapMethod target, 'json'
_wrapMethod target, 'postJson'
_wrapMethod target, 'putJson'
target.file = ->
restler.file.apply restler, arguments
target.fromRest = (config) ->
throw new Error 'query key is required' if !config?.query
config.resultMapping ?= (result) -> result
config.nextPage ?= -> undefined
@from @createBuffer()
queryAndWriteInputBuffer = (nextPage) =>
config.query.apply @, [ nextPage ]
.then (response) =>
@from().writeArrayAsync(config.resultMapping(response))
.done =>
nextPage = config.nextPage(response)
if (nextPage is undefined) or (nextPage is null)
@from().seal()
else
queryAndWriteInputBuffer(nextPage)
queryAndWriteInputBuffer(undefined)
@
_wrapMethod = (target, methodName) ->
target[methodName] = ->
methodArgs = arguments
new Promise (resolve, reject) ->
restler[methodName].apply(restler, methodArgs)
.on 'complete', (result, response) ->
if result instanceof Error
reject result
else
response.result = result
resolve response
| true | # Mixin to interact with REST services.
#
# This mixin wraps and promisifies the restler library methods, like .get(), .post() or
# .del(). For more details about restler see https://github.com/danwrong/restler.
#
# It also adds `.fromRest` method to pump, which fills input buffer from results of a REST service
# query.
#
# Use case 1: filling pump from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .fromRest
# query: -> @get 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# .process (user) ->
# # ...
# ```
#
# `.fromRest()` has an object argument. The `query` key is required, it must be a callback function
# which returns a promise that fulfills when the query is completed and returns with the query
# results. The query results must be an array. Most of the times, `.get()` or `.post()` method will
# be sufficient combined with mapping of query results (`resultMapping` key).
#
# Use `resultMapping` key when you need to map a results of the REST service to an array. The value
# of the key should be a function that receives REST query result in the first argument and returns
# array to be filled in the input buffer.
#
# REST service may be paginated, you can query those like this:
# ```js
# pump
# .mixin RestMixin
# .fromRest
# query: (nextPage) -> @get nextPage ? 'http://someservice.io/api/v1/users'
# resultMapping: (response) -> response.result.users
# nextPage: (response) -> response.result.paging.nextPage
# ```
# Only two things to note when using paginated REST service:
# * `nextPage` key is a callback which may return anything other than undefined or null to continue
# to next page.
# * `query` will receive the return value of `nextPage` callback. It will receive undefined on the
# first call.
#
# Use case 2: enriching content from result of rest GET
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) =>
# @get 'http://someservice.io/api/v1/user/' + data.username
# .then (response) =>
# data.email = response.result.email
# @copy data
# ```
#
# Use case 3: output to a REST service
# ```coffee
# { RestMixin } = require('datapumps/mixins')
# pump
# .mixin RestMixin
# .process (data) ->
# @post 'https://twaud.io/api/v1/upload.json',
# multipart: true
# username: 'danwrong'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# data:
# 'sound[message]': 'hello from restler!'
# 'sound[file]': @file('doug-e-fresh_the-show.mp3', null, 321567, null, 'audio/mpeg')
# ```
#
Promise = require 'bluebird'
restler = require 'restler'
module.exports = RestMixin = (target) ->
_wrapMethod target, 'get'
_wrapMethod target, 'post'
_wrapMethod target, 'put'
_wrapMethod target, 'del'
_wrapMethod target, 'head'
_wrapMethod target, 'patch'
_wrapMethod target, 'json'
_wrapMethod target, 'postJson'
_wrapMethod target, 'putJson'
target.file = ->
restler.file.apply restler, arguments
target.fromRest = (config) ->
throw new Error 'query key is required' if !config?.query
config.resultMapping ?= (result) -> result
config.nextPage ?= -> undefined
@from @createBuffer()
queryAndWriteInputBuffer = (nextPage) =>
config.query.apply @, [ nextPage ]
.then (response) =>
@from().writeArrayAsync(config.resultMapping(response))
.done =>
nextPage = config.nextPage(response)
if (nextPage is undefined) or (nextPage is null)
@from().seal()
else
queryAndWriteInputBuffer(nextPage)
queryAndWriteInputBuffer(undefined)
@
_wrapMethod = (target, methodName) ->
target[methodName] = ->
methodArgs = arguments
new Promise (resolve, reject) ->
restler[methodName].apply(restler, methodArgs)
.on 'complete', (result, response) ->
if result instanceof Error
reject result
else
response.result = result
resolve response
|
[
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ",
"end": 385,
"score": 0.9626885652542114,
"start": 381,
"tag": "NAME",
"value": "Test"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 746,
"score": 0.9760805368423462,
"start": 739,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"Nil\",\n \"context\" : \"Patient\",\n ",
"end": 1102,
"score": 0.9825040698051453,
"start": 1099,
"tag": "NAME",
"value": "Nil"
},
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ",
"end": 1581,
"score": 0.9493449926376343,
"start": 1577,
"tag": "NAME",
"value": "Test"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 1942,
"score": 0.946943461894989,
"start": 1935,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"Nil\",\n \"context\" : \"Patient\",\n ",
"end": 2298,
"score": 0.8319149613380432,
"start": 2295,
"tag": "NAME",
"value": "Nil"
},
{
"context": " }\n }, {\n \"name\" : \"One\",\n \"context\" : \"Patient\",\n ",
"end": 2449,
"score": 0.6568042039871216,
"start": 2446,
"tag": "NAME",
"value": "One"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 4670,
"score": 0.8614623546600342,
"start": 4663,
"tag": "NAME",
"value": "Patient"
}
] | Src/coffeescript/cql-execution/test/elm/nullological/data.coffee | esteban-aliverti/clinical_quality_language | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Nil
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
###
module.exports['Nil'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "Nil",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
} ]
}
}
}
### IsNull
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
define One = 1
define NullIsNull = IsNull(null)
define NullVarIsNull = IsNull(Nil)
define StringIsNull = IsNull('')
define NonNullVarIsNull = IsNull(One)
###
module.exports['IsNull'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "Nil",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
}, {
"name" : "One",
"context" : "Patient",
"expression" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "NullIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
} ]
}
}, {
"name" : "NullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "Nil",
"type" : "ExpressionRef"
} ]
}
}, {
"name" : "StringIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "",
"type" : "Literal"
} ]
}
}, {
"name" : "NonNullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "One",
"type" : "ExpressionRef"
} ]
}
} ]
}
}
}
### IfNull
library TestSnippet version '1'
using QUICK
context Patient
define NullAndA = IfNull(null, 'a')
define ZeroAndB = IfNull(0, 'b')
define BothNull = IfNull(null, null)
###
module.exports['IfNull'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullAndA",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "a",
"type" : "Literal"
} ]
}
}, {
"name" : "ZeroAndB",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "0",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "b",
"type" : "Literal"
} ]
}
}, {
"name" : "BothNull",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
### Coalesce
library TestSnippet version '1'
using QUICK
context Patient
define NullNullHelloNullWorld = Coalesce(null, null, 'Hello', null, 'World')
define FooNullNullBar = Coalesce('Foo', null, null, 'Bar')
define AllNull = Coalesce(null, null, null)
###
module.exports['Coalesce'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullNullHelloNullWorld",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Hello",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "World",
"type" : "Literal"
} ]
}
}, {
"name" : "FooNullNullBar",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Foo",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
} ]
}
}, {
"name" : "AllNull",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
| 199592 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Nil
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
###
module.exports['Nil'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
} ]
}
}
}
### IsNull
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
define One = 1
define NullIsNull = IsNull(null)
define NullVarIsNull = IsNull(Nil)
define StringIsNull = IsNull('')
define NonNullVarIsNull = IsNull(One)
###
module.exports['IsNull'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "NullIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
} ]
}
}, {
"name" : "NullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "Nil",
"type" : "ExpressionRef"
} ]
}
}, {
"name" : "StringIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "",
"type" : "Literal"
} ]
}
}, {
"name" : "NonNullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "One",
"type" : "ExpressionRef"
} ]
}
} ]
}
}
}
### IfNull
library TestSnippet version '1'
using QUICK
context Patient
define NullAndA = IfNull(null, 'a')
define ZeroAndB = IfNull(0, 'b')
define BothNull = IfNull(null, null)
###
module.exports['IfNull'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullAndA",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "a",
"type" : "Literal"
} ]
}
}, {
"name" : "ZeroAndB",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "0",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "b",
"type" : "Literal"
} ]
}
}, {
"name" : "BothNull",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
### Coalesce
library TestSnippet version '1'
using QUICK
context Patient
define NullNullHelloNullWorld = Coalesce(null, null, 'Hello', null, 'World')
define FooNullNullBar = Coalesce('Foo', null, null, 'Bar')
define AllNull = Coalesce(null, null, null)
###
module.exports['Coalesce'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullNullHelloNullWorld",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Hello",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "World",
"type" : "Literal"
} ]
}
}, {
"name" : "FooNullNullBar",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Foo",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
} ]
}
}, {
"name" : "AllNull",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Nil
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
###
module.exports['Nil'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
} ]
}
}
}
### IsNull
library TestSnippet version '1'
using QUICK
context Patient
define Nil = null
define One = 1
define NullIsNull = IsNull(null)
define NullVarIsNull = IsNull(Nil)
define StringIsNull = IsNull('')
define NonNullVarIsNull = IsNull(One)
###
module.exports['IsNull'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Null"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "NullIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
} ]
}
}, {
"name" : "NullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "Nil",
"type" : "ExpressionRef"
} ]
}
}, {
"name" : "StringIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "",
"type" : "Literal"
} ]
}
}, {
"name" : "NonNullVarIsNull",
"context" : "Patient",
"expression" : {
"name" : "IsNull",
"type" : "FunctionRef",
"operand" : [ {
"name" : "One",
"type" : "ExpressionRef"
} ]
}
} ]
}
}
}
### IfNull
library TestSnippet version '1'
using QUICK
context Patient
define NullAndA = IfNull(null, 'a')
define ZeroAndB = IfNull(0, 'b')
define BothNull = IfNull(null, null)
###
module.exports['IfNull'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullAndA",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "a",
"type" : "Literal"
} ]
}
}, {
"name" : "ZeroAndB",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "0",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "b",
"type" : "Literal"
} ]
}
}, {
"name" : "BothNull",
"context" : "Patient",
"expression" : {
"name" : "IfNull",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
### Coalesce
library TestSnippet version '1'
using QUICK
context Patient
define NullNullHelloNullWorld = Coalesce(null, null, 'Hello', null, 'World')
define FooNullNullBar = Coalesce('Foo', null, null, 'Bar')
define AllNull = Coalesce(null, null, null)
###
module.exports['Coalesce'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NullNullHelloNullWorld",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Hello",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "World",
"type" : "Literal"
} ]
}
}, {
"name" : "FooNullNullBar",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Foo",
"type" : "Literal"
}, {
"type" : "Null"
}, {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "Bar",
"type" : "Literal"
} ]
}
}, {
"name" : "AllNull",
"context" : "Patient",
"expression" : {
"name" : "Coalesce",
"type" : "FunctionRef",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
} ]
}
}
}
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9927714467048645,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/dialog.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A generic bootstrap dialog component
# Props:
# containerClasses: []
# disableBackgroundClick: boolean
# disableCancel: boolean
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
Spinner = require('./spinner').load(win)
{FaIcon} = require('./utils').load(win)
Dialog = React.createFactory React.createClass
displayName: 'Dialog'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isLoading: false
}
getDefaultProps: ->
return {
containerClasses: [] # TODO: Change for pre-joined string
onClose: ->
disableCancel: false
}
propTypes: {
containerClasses: React.PropTypes.array
onClose: React.PropTypes.func
disableCancel: React.PropTypes.bool
}
render: ->
return R.div({
className: [
'dialogContainer'
@props.containerClasses.join(' ')
].join(' ')
},
Spinner({
isVisible: @state.isLoading
isOverlay: true
})
R.div({className: 'dialog panel panel-primary animated fadeIn'},
R.div({className: 'panel-heading'},
R.h3({className: 'panel-title'}, @props.title)
(unless @props.disableCancel
R.span({
className: 'panel-quit'
onClick: @props.onClose
}, FaIcon('times'))
)
)
R.div({className: 'panel-body'},
@props.children
)
)
)
setIsLoading: (isLoading) ->
@setState -> {isLoading}
isLoading: -> @state.isLoading
return Dialog
module.exports = {load}
| 193828 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A generic bootstrap dialog component
# Props:
# containerClasses: []
# disableBackgroundClick: boolean
# disableCancel: boolean
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
Spinner = require('./spinner').load(win)
{FaIcon} = require('./utils').load(win)
Dialog = React.createFactory React.createClass
displayName: 'Dialog'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isLoading: false
}
getDefaultProps: ->
return {
containerClasses: [] # TODO: Change for pre-joined string
onClose: ->
disableCancel: false
}
propTypes: {
containerClasses: React.PropTypes.array
onClose: React.PropTypes.func
disableCancel: React.PropTypes.bool
}
render: ->
return R.div({
className: [
'dialogContainer'
@props.containerClasses.join(' ')
].join(' ')
},
Spinner({
isVisible: @state.isLoading
isOverlay: true
})
R.div({className: 'dialog panel panel-primary animated fadeIn'},
R.div({className: 'panel-heading'},
R.h3({className: 'panel-title'}, @props.title)
(unless @props.disableCancel
R.span({
className: 'panel-quit'
onClick: @props.onClose
}, FaIcon('times'))
)
)
R.div({className: 'panel-body'},
@props.children
)
)
)
setIsLoading: (isLoading) ->
@setState -> {isLoading}
isLoading: -> @state.isLoading
return Dialog
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A generic bootstrap dialog component
# Props:
# containerClasses: []
# disableBackgroundClick: boolean
# disableCancel: boolean
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
Spinner = require('./spinner').load(win)
{FaIcon} = require('./utils').load(win)
Dialog = React.createFactory React.createClass
displayName: 'Dialog'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isLoading: false
}
getDefaultProps: ->
return {
containerClasses: [] # TODO: Change for pre-joined string
onClose: ->
disableCancel: false
}
propTypes: {
containerClasses: React.PropTypes.array
onClose: React.PropTypes.func
disableCancel: React.PropTypes.bool
}
render: ->
return R.div({
className: [
'dialogContainer'
@props.containerClasses.join(' ')
].join(' ')
},
Spinner({
isVisible: @state.isLoading
isOverlay: true
})
R.div({className: 'dialog panel panel-primary animated fadeIn'},
R.div({className: 'panel-heading'},
R.h3({className: 'panel-title'}, @props.title)
(unless @props.disableCancel
R.span({
className: 'panel-quit'
onClick: @props.onClose
}, FaIcon('times'))
)
)
R.div({className: 'panel-body'},
@props.children
)
)
)
setIsLoading: (isLoading) ->
@setState -> {isLoading}
isLoading: -> @state.isLoading
return Dialog
module.exports = {load}
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998478293418884,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ",
"end": 60,
"score": 0.9999294281005859,
"start": 44,
"tag": "EMAIL",
"value": "ts33kr@gmail.com"
}
] | library/shipped/fonting.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
asciify = require "asciify"
connect = require "connect"
request = require "request"
logger = require "winston"
colors = require "colors"
async = require "async"
nconf = require "nconf"
https = require "https"
http = require "http"
util = require "util"
{format} = require "util"
{external} = require "../membrane/remote"
{Barebones} = require "../membrane/skeleton"
{Preflight} = require "../membrane/preflight"
# This abstract compound provides the internal service API for the
# automatic generation of necessary links and then inclusion of the
# required tags to use the confgured fonts provided by the Google
# Fonts service that generates the CSS stylesheets with settings.
# Please refer to the Google docs to get info on the fonts format.
module.exports.GoogleFonts = class GoogleFonts extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: googlefonts: yes
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
googlefonts = @constructor.googlefonts or []
assert _.isArray(googlefonts), "invalid fonts"
assert googlefonts = try googlefonts.reverse()
j = (strc) -> return strc.typographs.join ","
t = "https://fonts.googleapis.com/css?family=%s"
try t += "&subset=latin,cyrillic,cyrillic-ext"
foldtyp = (x) -> family: x.family, joined: j(x)
infusor = (fx) -> "#{fx.family}:#{fx.joined}"
extract = (record) -> try return record.family
googlefonts = _.unique googlefonts, extract
assert prepped = _.map googlefonts, foldtyp
assert infused = try _.map prepped, infusor
assert not _.isEmpty blob = infused.join "|"
context.sheets.push format t, blob; next()
# Add the described font to the font request that is going to be
# compiled and emited when the context is assembled. Description
# of a font is formed of a font family name and a vector of the
# typographic descriptions, such as sizes and styles. Values in
# the vector can be strings or any others - all are stringified.
@googlefont: (family, typographs...) ->
string = (val) -> return val.toString()
isntEmpty = -> not _.isEmpty arguments...
assert previous = @googlefonts or Array()
assert previous = try _.unique previous or []
empty = "got an empty font typograph handler"
assert _.isString(family), "no valid family"
assert _.isArray(typographs), "no typographs"
assert typographs = _.map typographs, string
assert _.all(typographs, isntEmpty), empty
@googlefonts = previous.concat new Object
family: family.replace /\s/g, "+"
typographs: _.toArray typographs
| 76156 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
asciify = require "asciify"
connect = require "connect"
request = require "request"
logger = require "winston"
colors = require "colors"
async = require "async"
nconf = require "nconf"
https = require "https"
http = require "http"
util = require "util"
{format} = require "util"
{external} = require "../membrane/remote"
{Barebones} = require "../membrane/skeleton"
{Preflight} = require "../membrane/preflight"
# This abstract compound provides the internal service API for the
# automatic generation of necessary links and then inclusion of the
# required tags to use the confgured fonts provided by the Google
# Fonts service that generates the CSS stylesheets with settings.
# Please refer to the Google docs to get info on the fonts format.
module.exports.GoogleFonts = class GoogleFonts extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: googlefonts: yes
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
googlefonts = @constructor.googlefonts or []
assert _.isArray(googlefonts), "invalid fonts"
assert googlefonts = try googlefonts.reverse()
j = (strc) -> return strc.typographs.join ","
t = "https://fonts.googleapis.com/css?family=%s"
try t += "&subset=latin,cyrillic,cyrillic-ext"
foldtyp = (x) -> family: x.family, joined: j(x)
infusor = (fx) -> "#{fx.family}:#{fx.joined}"
extract = (record) -> try return record.family
googlefonts = _.unique googlefonts, extract
assert prepped = _.map googlefonts, foldtyp
assert infused = try _.map prepped, infusor
assert not _.isEmpty blob = infused.join "|"
context.sheets.push format t, blob; next()
# Add the described font to the font request that is going to be
# compiled and emited when the context is assembled. Description
# of a font is formed of a font family name and a vector of the
# typographic descriptions, such as sizes and styles. Values in
# the vector can be strings or any others - all are stringified.
@googlefont: (family, typographs...) ->
string = (val) -> return val.toString()
isntEmpty = -> not _.isEmpty arguments...
assert previous = @googlefonts or Array()
assert previous = try _.unique previous or []
empty = "got an empty font typograph handler"
assert _.isString(family), "no valid family"
assert _.isArray(typographs), "no typographs"
assert typographs = _.map typographs, string
assert _.all(typographs, isntEmpty), empty
@googlefonts = previous.concat new Object
family: family.replace /\s/g, "+"
typographs: _.toArray typographs
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
asciify = require "asciify"
connect = require "connect"
request = require "request"
logger = require "winston"
colors = require "colors"
async = require "async"
nconf = require "nconf"
https = require "https"
http = require "http"
util = require "util"
{format} = require "util"
{external} = require "../membrane/remote"
{Barebones} = require "../membrane/skeleton"
{Preflight} = require "../membrane/preflight"
# This abstract compound provides the internal service API for the
# automatic generation of necessary links and then inclusion of the
# required tags to use the confgured fonts provided by the Google
# Fonts service that generates the CSS stylesheets with settings.
# Please refer to the Google docs to get info on the fonts format.
module.exports.GoogleFonts = class GoogleFonts extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: googlefonts: yes
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
googlefonts = @constructor.googlefonts or []
assert _.isArray(googlefonts), "invalid fonts"
assert googlefonts = try googlefonts.reverse()
j = (strc) -> return strc.typographs.join ","
t = "https://fonts.googleapis.com/css?family=%s"
try t += "&subset=latin,cyrillic,cyrillic-ext"
foldtyp = (x) -> family: x.family, joined: j(x)
infusor = (fx) -> "#{fx.family}:#{fx.joined}"
extract = (record) -> try return record.family
googlefonts = _.unique googlefonts, extract
assert prepped = _.map googlefonts, foldtyp
assert infused = try _.map prepped, infusor
assert not _.isEmpty blob = infused.join "|"
context.sheets.push format t, blob; next()
# Add the described font to the font request that is going to be
# compiled and emited when the context is assembled. Description
# of a font is formed of a font family name and a vector of the
# typographic descriptions, such as sizes and styles. Values in
# the vector can be strings or any others - all are stringified.
@googlefont: (family, typographs...) ->
string = (val) -> return val.toString()
isntEmpty = -> not _.isEmpty arguments...
assert previous = @googlefonts or Array()
assert previous = try _.unique previous or []
empty = "got an empty font typograph handler"
assert _.isString(family), "no valid family"
assert _.isArray(typographs), "no typographs"
assert typographs = _.map typographs, string
assert _.all(typographs, isntEmpty), empty
@googlefonts = previous.concat new Object
family: family.replace /\s/g, "+"
typographs: _.toArray typographs
|
[
{
"context": "ade by 3 months of age.\n '''\n\n scientificName: 'Panthera leo'\n mainImage: 'assets/fieldguide-content/mammals/",
"end": 528,
"score": 0.9997463226318359,
"start": 516,
"tag": "NAME",
"value": "Panthera leo"
}
] | app/lib/field-guide-content/lion_female.coffee | zooniverse/wildcam-gorongosa-facebook | 7 | module.exports =
label: 'Lion'
description: '''
Lions are iconic African large cats, built to prey on animals many times their size. Their coat is a smooth tawny color with whitish underparts. They have a muscular build, heavy muzzle, strong jaws, large paws, and a long tail that ends in a black tassel. They are sexually dimorphic, with males being larger in size and having full manes that vary in color from blond to black. Cubs have spots that tend to fade by 3 months of age.
'''
scientificName: 'Panthera leo'
mainImage: 'assets/fieldguide-content/mammals/lion/lion-feature.jpg'#
conservationStatus: 'Near Threatened' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.#
information: [{
label: 'Length'
value: '2.4-3.3 m'
}, {
label: 'Height'
value: '1.1-1.2 m'
}, {
label: 'Weight'
value: '120-200 kg'
}, {
label: 'Lifespan'
value: '10-14 years in the wild; up to 20 years in captivity'
}, {
label: 'Gestation'
value: '3.5 months'
}, {
label: 'Avg. number of offspring'
value: '1-6'
}]
sections: [{
title: 'Habitat'
content: 'Lions have a broad habitat tolerance; they are able to thrive in plains or savanna habitats that have a sufficient prey base and available cover present. They are absent from tropical rainforests and the interior of the Sahara desert but can thrive in most other habitats found throughout Africa.'
}, {
title: 'Diet'
content: 'Anything from tortoises to giraffes; will hunt what they grew up eating, and different prides specialize in or prefer different prey types. Can take down prey as large as buffalo, rhinos, hippos, and giraffes by hunting cooperatively.'
}, {
title: 'Predators'
content: 'Adult lions have no natural predators, except humans. Lion cubs, however, if left alone, are vulnerable to other large predators.'
}, {
title: 'Behavior'
content: '''
<p>Lions are social animals that live in groups called prides. Prides can be as small as three or as big as 40 animals. Generally, the females in the pride are related—mothers, daughters, grandmothers, and sisters. Prides hunt, raise young, and defend their territory together. Pride members perform a greeting ritual upon meeting; they rub their heads and sides together, with their tails raised high, while making friendly vocal noises. The females in the pride generally do most of the hunting, going out in groups of two or three to kill their prey. Males only join after successful kills. Females will generally stay in the pride they are born into for life, while adolescent males are forced to depart when they become sexually mature and are seen as rivals. After being kicked out, adolescent males will typically spend a few years as nomads until they mature and take over a pride. Males will lead a pride until challenged and defeated.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>After a 3.5-month gestation period, a lion will typically give birth to a litter of one to four (up to six) cubs. Females within the same pride tend to reproduce in synchrony, cross-suckling their offspring and engaging in cooperative rearing of the young.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Male lions are unique among the cat species for their thick mane.</li>
<li>Lions are the only truly social cats.</li>
<li>It is believed that lions copulate 3,000 times for every cub that survives over one year.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/lion/lion-map.jpg"/>'
}]
| 58889 | module.exports =
label: 'Lion'
description: '''
Lions are iconic African large cats, built to prey on animals many times their size. Their coat is a smooth tawny color with whitish underparts. They have a muscular build, heavy muzzle, strong jaws, large paws, and a long tail that ends in a black tassel. They are sexually dimorphic, with males being larger in size and having full manes that vary in color from blond to black. Cubs have spots that tend to fade by 3 months of age.
'''
scientificName: '<NAME>'
mainImage: 'assets/fieldguide-content/mammals/lion/lion-feature.jpg'#
conservationStatus: 'Near Threatened' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.#
information: [{
label: 'Length'
value: '2.4-3.3 m'
}, {
label: 'Height'
value: '1.1-1.2 m'
}, {
label: 'Weight'
value: '120-200 kg'
}, {
label: 'Lifespan'
value: '10-14 years in the wild; up to 20 years in captivity'
}, {
label: 'Gestation'
value: '3.5 months'
}, {
label: 'Avg. number of offspring'
value: '1-6'
}]
sections: [{
title: 'Habitat'
content: 'Lions have a broad habitat tolerance; they are able to thrive in plains or savanna habitats that have a sufficient prey base and available cover present. They are absent from tropical rainforests and the interior of the Sahara desert but can thrive in most other habitats found throughout Africa.'
}, {
title: 'Diet'
content: 'Anything from tortoises to giraffes; will hunt what they grew up eating, and different prides specialize in or prefer different prey types. Can take down prey as large as buffalo, rhinos, hippos, and giraffes by hunting cooperatively.'
}, {
title: 'Predators'
content: 'Adult lions have no natural predators, except humans. Lion cubs, however, if left alone, are vulnerable to other large predators.'
}, {
title: 'Behavior'
content: '''
<p>Lions are social animals that live in groups called prides. Prides can be as small as three or as big as 40 animals. Generally, the females in the pride are related—mothers, daughters, grandmothers, and sisters. Prides hunt, raise young, and defend their territory together. Pride members perform a greeting ritual upon meeting; they rub their heads and sides together, with their tails raised high, while making friendly vocal noises. The females in the pride generally do most of the hunting, going out in groups of two or three to kill their prey. Males only join after successful kills. Females will generally stay in the pride they are born into for life, while adolescent males are forced to depart when they become sexually mature and are seen as rivals. After being kicked out, adolescent males will typically spend a few years as nomads until they mature and take over a pride. Males will lead a pride until challenged and defeated.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>After a 3.5-month gestation period, a lion will typically give birth to a litter of one to four (up to six) cubs. Females within the same pride tend to reproduce in synchrony, cross-suckling their offspring and engaging in cooperative rearing of the young.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Male lions are unique among the cat species for their thick mane.</li>
<li>Lions are the only truly social cats.</li>
<li>It is believed that lions copulate 3,000 times for every cub that survives over one year.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/lion/lion-map.jpg"/>'
}]
| true | module.exports =
label: 'Lion'
description: '''
Lions are iconic African large cats, built to prey on animals many times their size. Their coat is a smooth tawny color with whitish underparts. They have a muscular build, heavy muzzle, strong jaws, large paws, and a long tail that ends in a black tassel. They are sexually dimorphic, with males being larger in size and having full manes that vary in color from blond to black. Cubs have spots that tend to fade by 3 months of age.
'''
scientificName: 'PI:NAME:<NAME>END_PI'
mainImage: 'assets/fieldguide-content/mammals/lion/lion-feature.jpg'#
conservationStatus: 'Near Threatened' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.#
information: [{
label: 'Length'
value: '2.4-3.3 m'
}, {
label: 'Height'
value: '1.1-1.2 m'
}, {
label: 'Weight'
value: '120-200 kg'
}, {
label: 'Lifespan'
value: '10-14 years in the wild; up to 20 years in captivity'
}, {
label: 'Gestation'
value: '3.5 months'
}, {
label: 'Avg. number of offspring'
value: '1-6'
}]
sections: [{
title: 'Habitat'
content: 'Lions have a broad habitat tolerance; they are able to thrive in plains or savanna habitats that have a sufficient prey base and available cover present. They are absent from tropical rainforests and the interior of the Sahara desert but can thrive in most other habitats found throughout Africa.'
}, {
title: 'Diet'
content: 'Anything from tortoises to giraffes; will hunt what they grew up eating, and different prides specialize in or prefer different prey types. Can take down prey as large as buffalo, rhinos, hippos, and giraffes by hunting cooperatively.'
}, {
title: 'Predators'
content: 'Adult lions have no natural predators, except humans. Lion cubs, however, if left alone, are vulnerable to other large predators.'
}, {
title: 'Behavior'
content: '''
<p>Lions are social animals that live in groups called prides. Prides can be as small as three or as big as 40 animals. Generally, the females in the pride are related—mothers, daughters, grandmothers, and sisters. Prides hunt, raise young, and defend their territory together. Pride members perform a greeting ritual upon meeting; they rub their heads and sides together, with their tails raised high, while making friendly vocal noises. The females in the pride generally do most of the hunting, going out in groups of two or three to kill their prey. Males only join after successful kills. Females will generally stay in the pride they are born into for life, while adolescent males are forced to depart when they become sexually mature and are seen as rivals. After being kicked out, adolescent males will typically spend a few years as nomads until they mature and take over a pride. Males will lead a pride until challenged and defeated.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>After a 3.5-month gestation period, a lion will typically give birth to a litter of one to four (up to six) cubs. Females within the same pride tend to reproduce in synchrony, cross-suckling their offspring and engaging in cooperative rearing of the young.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>Male lions are unique among the cat species for their thick mane.</li>
<li>Lions are the only truly social cats.</li>
<li>It is believed that lions copulate 3,000 times for every cub that survives over one year.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/lion/lion-map.jpg"/>'
}]
|
[
{
"context": "sut = new LogentriesWebhookAuthExpress password: 'pre-shared-key'\n @next = sinon.spy()\n @request =\n ",
"end": 409,
"score": 0.9992863535881042,
"start": 395,
"tag": "PASSWORD",
"value": "pre-shared-key"
},
{
"context": "sut = new LogentriesWebhookAuthExpress password: 'shared-key-pre'\n @next = sinon.spy()\n @request =\n ",
"end": 1206,
"score": 0.9990930557250977,
"start": 1192,
"tag": "PASSWORD",
"value": "shared-key-pre"
},
{
"context": "quest.logentriesWebhookAuth).to.deep.equal user: 'super-pink', hash: 'uHvt/OOVkCqV58aFIDaPNsHZRtg='\n\n descr",
"end": 1803,
"score": 0.9984793663024902,
"start": 1793,
"tag": "USERNAME",
"value": "super-pink"
},
{
"context": "sut = new LogentriesWebhookAuthExpress password: 'shared'\n @next = sinon.spy()\n @request =\n ",
"end": 1972,
"score": 0.9994977712631226,
"start": 1966,
"tag": "PASSWORD",
"value": "shared"
}
] | test/logentries-webhook-auth-express-spec.coffee | octoblu/express-logentries-webhook-auth | 0 | LogentriesWebhookAuthExpress = require '../src/logentries-webhook-auth-express'
describe 'LogentriesWebhookAuthExpress', ->
describe '->getFromAuthorizationHeader', ->
beforeEach ->
@makeFakeGet = (request) =>
return (header) => request.headers[header]
describe 'with a valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'pre-shared-key'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE greenish-yellow:+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
body: 'abcdeft'
path: '/somewhere'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'greenish-yellow', hash: '+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
describe 'with a different valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'shared-key-pre'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE super-pink:uHvt/OOVkCqV58aFIDaPNsHZRtg='
body: 'fobar'
path: '/b0rked'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'super-pink', hash: 'uHvt/OOVkCqV58aFIDaPNsHZRtg='
describe 'with a invalid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'shared'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE user:zpwaW5raXNoLBAD'
body: 'totally haxxored'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.not.exist
| 2149 | LogentriesWebhookAuthExpress = require '../src/logentries-webhook-auth-express'
describe 'LogentriesWebhookAuthExpress', ->
describe '->getFromAuthorizationHeader', ->
beforeEach ->
@makeFakeGet = (request) =>
return (header) => request.headers[header]
describe 'with a valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: '<PASSWORD>'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE greenish-yellow:+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
body: 'abcdeft'
path: '/somewhere'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'greenish-yellow', hash: '+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
describe 'with a different valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: '<PASSWORD>'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE super-pink:uHvt/OOVkCqV58aFIDaPNsHZRtg='
body: 'fobar'
path: '/b0rked'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'super-pink', hash: 'uHvt/OOVkCqV58aFIDaPNsHZRtg='
describe 'with a invalid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: '<PASSWORD>'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE user:zpwaW5raXNoLBAD'
body: 'totally haxxored'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.not.exist
| true | LogentriesWebhookAuthExpress = require '../src/logentries-webhook-auth-express'
describe 'LogentriesWebhookAuthExpress', ->
describe '->getFromAuthorizationHeader', ->
beforeEach ->
@makeFakeGet = (request) =>
return (header) => request.headers[header]
describe 'with a valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'PI:PASSWORD:<PASSWORD>END_PI'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE greenish-yellow:+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
body: 'abcdeft'
path: '/somewhere'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'greenish-yellow', hash: '+x/QCSqyGmY0XmxQ5tq8qUWGGDc='
describe 'with a different valid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'PI:PASSWORD:<PASSWORD>END_PI'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE super-pink:uHvt/OOVkCqV58aFIDaPNsHZRtg='
body: 'fobar'
path: '/b0rked'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.deep.equal user: 'super-pink', hash: 'uHvt/OOVkCqV58aFIDaPNsHZRtg='
describe 'with a invalid LE token', ->
beforeEach ->
@sut = new LogentriesWebhookAuthExpress password: 'PI:PASSWORD:<PASSWORD>END_PI'
@next = sinon.spy()
@request =
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Date': 'Tue, 18 Aug 2015 18:14:29 GMT'
'X-Le-Nonce': 'kzaWhO5P5yHYkUZRhbTDNEkG'
authorization: 'LE user:zpwaW5raXNoLBAD'
body: 'totally haxxored'
@request.get = @makeFakeGet @request
@sut.getFromAuthorizationHeader(@request)
it 'should set logentriesWebhookAuth on the request', ->
expect(@request.logentriesWebhookAuth).to.not.exist
|
[
{
"context": "y for storing webhooks\n\twebhookKey: (entryId) -> \"asana-#{entryId}-webhook-id\"\n\n\t# Find a task given it's id\n\tgetTask: (id) ->\n",
"end": 1814,
"score": 0.8833834528923035,
"start": 1787,
"tag": "KEY",
"value": "asana-#{entryId}-webhook-id"
},
{
"context": "mate notification\n\testimateMessageKey: (task) -> \"asana-#{task.gid}-estimate-message\" \n\t\n\t# Make the URL t",
"end": 4235,
"score": 0.9328295588493347,
"start": 4229,
"tag": "KEY",
"value": "asana-"
},
{
"context": "n\n\testimateMessageKey: (task) -> \"asana-#{task.gid}-estimate-message\" \n\t\n\t# Make the URL to a task\n\ttaskUrl: (task) ->",
"end": 4263,
"score": 0.9079919457435608,
"start": 4247,
"tag": "KEY",
"value": "estimate-message"
},
{
"context": "\n\t\t# Return payload\n\t\turl: url\n\t\tauthor: \n\t\t\tname: author.name\n\t\t\turl: \"https://app.asana.com/0/#{author.gid}\"\n\t",
"end": 6748,
"score": 0.8217432498931885,
"start": 6737,
"tag": "NAME",
"value": "author.name"
}
] | functions/services/asana.coffee | BKWLD/asana-gitlab-bridge | 2 | # Deps
axios = require 'axios'
_ = require 'lodash'
db = new (require './db')
# Constants that are used in multiple places
PRIORITY_FIELD = 'Priority'
STATUS_FIELD = 'Dev status'
DEPLOYED_STATUS = 'Deployed'
# Define the service
module.exports = class Asana
# Constants for custom field names
PRIORITY_FIELD: PRIORITY_FIELD
STATUS_FIELD: STATUS_FIELD
ESTIMATE_FIELD: 'Est'
ISSUE_FIELD: 'GitLab'
# Constants for Statuses
ESTIMATE_STATUS: 'Estimating'
SCHEDULE_STATUS: 'Scheduling'
PENDING_STATUS: 'Pending'
DEPLOYED_STATUS: DEPLOYED_STATUS
# Status lables organized by custom fields and ordered intentionally
labels:
"#{PRIORITY_FIELD}": [
'Critical'
'High'
'Medium'
'Low'
]
"#{STATUS_FIELD}": [ # Only those that get synced
DEPLOYED_STATUS
'Approved'
'Staged'
'Addressed'
]
# Build Axios client
constructor: -> @client = axios.create
baseURL: 'https://app.asana.com/api/1.0'
headers: Authorization: "Bearer #{process.env.ASANA_ACCESS_TOKEN}"
# Fetch list of projects for access token
getProjects: ->
{ data } = await @client.get '/projects'
projects = data.data.map (project) ->
id: project.gid
name: project.name
return _.sortBy projects, 'name'
# Create a webhook for a given project id
createWebhook: (entryId, projectId) ->
{ data } = await @client.post '/webhooks', data:
resource: projectId
target: "#{process.env.GATEWAY_URL}/asana/webhook?entry=#{entryId}"
await db.put @webhookKey(entryId), data.data.gid
# Delete a webhook for a given project id
deleteWebhook: (entryId) ->
if webhookId = await db.get @webhookKey entryId
await @client.delete "/webhooks/#{webhookId}"
await db.delete @webhookKey entryId
# Make the key for storing webhooks
webhookKey: (entryId) -> "asana-#{entryId}-webhook-id"
# Find a task given it's id
getTask: (id) ->
{ data } = await @client.get "/tasks/#{id}"
return data?.data
# Get the count of task stories
getTaskStories: (id) ->
{ data } = await @client.get "/tasks/#{id}/stories"
return data?.data
# Check if the status is a particular status
hasStatus: (task, status) ->
status == @getStatus task, status
# Check if the status is also a GitLab label or is pendinh
hasStatusLabelOrIsPending: (task) ->
@hasStatusLabel(task) or @getStatus(task) == @PENDING_STATUS
# Check if the status is also a GitLab label
hasStatusLabel: (task) -> @getStatus(task) in @labels[@STATUS_FIELD]
# Get the status for a task
getStatus: (task) -> @customFieldValue task, @STATUS_FIELD
# Get a custom field value
customFieldValue: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.enum_value?.name || field?.number_value || field?.text_value
# Get the id of a custom field
customFieldId: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.gid
# For an enum field, find the id of the particular opion
customFieldEnumId: (task, fieldName, enumName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
option = field?.enum_options?.find (option) -> option.name == enumName
return option?.gid || null
# Lookup the creator user of a story (like a note on a task)
getStoryCreator: (story) ->
{ data } = await @client.get "/users/#{story.created_by.gid}"
return data.data
# Check if the task is in the estimating phase but has no estimate
needsEstimate: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
not @customFieldValue(task, @ESTIMATE_FIELD)
# Check if we need and estimate and a message hasn't already been sent
needsEstimateAndNotSent: (task) ->
@needsEstimate(task) and not await db.get @estimateMessageKey(task)
# Check if the estimate message can be updated from slack
getEstimateMessageIfEstimateComplete: (task) ->
return if @needsEstimate task
return await db.get @estimateMessageKey(task)
# If we hvae an estimate but the status is still ON estimate
needsScheduleStatus: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
@customFieldValue(task, @ESTIMATE_FIELD)
# Build the key used to keep track of the estimate notification
estimateMessageKey: (task) -> "asana-#{task.gid}-estimate-message"
# Make the URL to a task
taskUrl: (task) -> "https://app.asana.com/0/0/#{task.gid}"
# Update the status custom field
updateStatus: (task, status) ->
@updateEnumCustomField task, @STATUS_FIELD, status
# Update the status custom field
updatePriority: (task, priority) ->
@updateEnumCustomField task, @PRIORITY_FIELD, priority
# Update an enum custom value
updateEnumCustomField: (task, fieldName, value) ->
fieldId = @customFieldId task, fieldName
valueId = @customFieldEnumId task, fieldName, value
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": valueId
# Update the status custom field
updateEstimate: (task, hours) ->
fieldId = @customFieldId task, @ESTIMATE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": hours
# A task is ticketable if it is in a milestone-like section but doesn't have
# an issue yet and isn't named like a milestone (Asana will return sections
# like tasks)
issueable: (task) ->
@inMilestone(task) and
not @issued(task) and
task.name and # Has a name
not @namedLikeMilestone(task.name) and
not @hasStatus(task, @ESTIMATE_STATUS)
# Add a issue reference to Asana
addIssue: (task, issueUrl) ->
fieldId = @customFieldId task, @ISSUE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": issueUrl
# Has the task had a issue created for it?
issued: (task) -> !!@customFieldValue task, @ISSUE_FIELD
# Check if a task is in a milestone by seeing if any of it's memberships have
# a milestone/sprint style name
inMilestone: (task) -> !!@milestoneName task
# Get the milestone of an issue by looping through the memberships and
# getting section ones that match the naming convention. Trim trailing colon
# and whitespace from the name.
milestoneName: (task) ->
membership = task.memberships.find (membership) =>
@namedLikeMilestone membership.section?.name
return membership?.section.name.replace /\s*:\s*$/, ''
# Test if something has a milestone-like name
namedLikeMilestone: (name) -> name?.match /^(Milestone|Sprint)/i
# Complete a task
completeTask: (taskId) ->
@client.put "/tasks/#{taskId}", data: completed: true
# Build meta info on a task
getMeta: (task) ->
# Muster data
url = @taskUrl task
stories = await @getTaskStories task.gid
author = await @getStoryCreator stories[0] if stories.length
# Return payload
url: url
author:
name: author.name
url: "https://app.asana.com/0/#{author.gid}"
icon: author.photo?.image_36x36
priority: switch @customFieldValue task, 'Priority'
when 'Critical' then '📕 Critical'
when 'High' then '📙 High'
when 'Medium' then '📒 Medium'
when 'Low' then '📘 Low'
comments: do ->
comments = stories.filter (story) -> story.type == 'comment'
return "💬 #{comments.length}"
date: '📅 '+(new Date(task.created_at)).toLocaleDateString 'en-US',
month:'short'
day:'numeric'
year: 'numeric'
# Make an array of the active value of "label" custom fields
getLabels: (task) ->
Object.keys(@labels).map (fieldName) =>
# Get the value of the field and return it if it's one of the values that
# get synced with GitLab
if value = @customFieldValue task, fieldName
if value in @labels[fieldName]
return value
# Remove labels that were empty
.filter (label) -> !!label
# Get a list of all the labels that are synced
syncedLabels: ->
Object.values(@labels).reduce (all, labels) -> all.concat labels
, []
# Take an array of labels from GitLab and return an object with keys for each
# fieldName and only one
normalizeLabels: (labels) ->
# Open a chain
_(labels)
# Group the incoming labels by Asana custom field names
.groupBy (label) =>
for fieldName, options of @labels
return fieldName if label in options
return '' # Default
# Remove null keys; these are labels that don't get synced to Asana
.pickBy (labels, fieldName) -> !!fieldName
# Reduce the labels to the highest priority or latest lifecycle label
# in the first index
.mapValues (labels, fieldName) =>
_(labels).orderBy (label) => @labels[fieldName].indexOf label
.first()
# Set emtpy strings for any fieldNames that weren't present in the list of
# labels so the value will clear if the label was removed in GitLab
.defaults _.mapValues @labels, -> null
# Return final object
.value() | 107486 | # Deps
axios = require 'axios'
_ = require 'lodash'
db = new (require './db')
# Constants that are used in multiple places
PRIORITY_FIELD = 'Priority'
STATUS_FIELD = 'Dev status'
DEPLOYED_STATUS = 'Deployed'
# Define the service
module.exports = class Asana
# Constants for custom field names
PRIORITY_FIELD: PRIORITY_FIELD
STATUS_FIELD: STATUS_FIELD
ESTIMATE_FIELD: 'Est'
ISSUE_FIELD: 'GitLab'
# Constants for Statuses
ESTIMATE_STATUS: 'Estimating'
SCHEDULE_STATUS: 'Scheduling'
PENDING_STATUS: 'Pending'
DEPLOYED_STATUS: DEPLOYED_STATUS
# Status lables organized by custom fields and ordered intentionally
labels:
"#{PRIORITY_FIELD}": [
'Critical'
'High'
'Medium'
'Low'
]
"#{STATUS_FIELD}": [ # Only those that get synced
DEPLOYED_STATUS
'Approved'
'Staged'
'Addressed'
]
# Build Axios client
constructor: -> @client = axios.create
baseURL: 'https://app.asana.com/api/1.0'
headers: Authorization: "Bearer #{process.env.ASANA_ACCESS_TOKEN}"
# Fetch list of projects for access token
getProjects: ->
{ data } = await @client.get '/projects'
projects = data.data.map (project) ->
id: project.gid
name: project.name
return _.sortBy projects, 'name'
# Create a webhook for a given project id
createWebhook: (entryId, projectId) ->
{ data } = await @client.post '/webhooks', data:
resource: projectId
target: "#{process.env.GATEWAY_URL}/asana/webhook?entry=#{entryId}"
await db.put @webhookKey(entryId), data.data.gid
# Delete a webhook for a given project id
deleteWebhook: (entryId) ->
if webhookId = await db.get @webhookKey entryId
await @client.delete "/webhooks/#{webhookId}"
await db.delete @webhookKey entryId
# Make the key for storing webhooks
webhookKey: (entryId) -> "<KEY>"
# Find a task given it's id
getTask: (id) ->
{ data } = await @client.get "/tasks/#{id}"
return data?.data
# Get the count of task stories
getTaskStories: (id) ->
{ data } = await @client.get "/tasks/#{id}/stories"
return data?.data
# Check if the status is a particular status
hasStatus: (task, status) ->
status == @getStatus task, status
# Check if the status is also a GitLab label or is pendinh
hasStatusLabelOrIsPending: (task) ->
@hasStatusLabel(task) or @getStatus(task) == @PENDING_STATUS
# Check if the status is also a GitLab label
hasStatusLabel: (task) -> @getStatus(task) in @labels[@STATUS_FIELD]
# Get the status for a task
getStatus: (task) -> @customFieldValue task, @STATUS_FIELD
# Get a custom field value
customFieldValue: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.enum_value?.name || field?.number_value || field?.text_value
# Get the id of a custom field
customFieldId: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.gid
# For an enum field, find the id of the particular opion
customFieldEnumId: (task, fieldName, enumName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
option = field?.enum_options?.find (option) -> option.name == enumName
return option?.gid || null
# Lookup the creator user of a story (like a note on a task)
getStoryCreator: (story) ->
{ data } = await @client.get "/users/#{story.created_by.gid}"
return data.data
# Check if the task is in the estimating phase but has no estimate
needsEstimate: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
not @customFieldValue(task, @ESTIMATE_FIELD)
# Check if we need and estimate and a message hasn't already been sent
needsEstimateAndNotSent: (task) ->
@needsEstimate(task) and not await db.get @estimateMessageKey(task)
# Check if the estimate message can be updated from slack
getEstimateMessageIfEstimateComplete: (task) ->
return if @needsEstimate task
return await db.get @estimateMessageKey(task)
# If we hvae an estimate but the status is still ON estimate
needsScheduleStatus: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
@customFieldValue(task, @ESTIMATE_FIELD)
# Build the key used to keep track of the estimate notification
estimateMessageKey: (task) -> "<KEY>#{task.gid}-<KEY>"
# Make the URL to a task
taskUrl: (task) -> "https://app.asana.com/0/0/#{task.gid}"
# Update the status custom field
updateStatus: (task, status) ->
@updateEnumCustomField task, @STATUS_FIELD, status
# Update the status custom field
updatePriority: (task, priority) ->
@updateEnumCustomField task, @PRIORITY_FIELD, priority
# Update an enum custom value
updateEnumCustomField: (task, fieldName, value) ->
fieldId = @customFieldId task, fieldName
valueId = @customFieldEnumId task, fieldName, value
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": valueId
# Update the status custom field
updateEstimate: (task, hours) ->
fieldId = @customFieldId task, @ESTIMATE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": hours
# A task is ticketable if it is in a milestone-like section but doesn't have
# an issue yet and isn't named like a milestone (Asana will return sections
# like tasks)
issueable: (task) ->
@inMilestone(task) and
not @issued(task) and
task.name and # Has a name
not @namedLikeMilestone(task.name) and
not @hasStatus(task, @ESTIMATE_STATUS)
# Add a issue reference to Asana
addIssue: (task, issueUrl) ->
fieldId = @customFieldId task, @ISSUE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": issueUrl
# Has the task had a issue created for it?
issued: (task) -> !!@customFieldValue task, @ISSUE_FIELD
# Check if a task is in a milestone by seeing if any of it's memberships have
# a milestone/sprint style name
inMilestone: (task) -> !!@milestoneName task
# Get the milestone of an issue by looping through the memberships and
# getting section ones that match the naming convention. Trim trailing colon
# and whitespace from the name.
milestoneName: (task) ->
membership = task.memberships.find (membership) =>
@namedLikeMilestone membership.section?.name
return membership?.section.name.replace /\s*:\s*$/, ''
# Test if something has a milestone-like name
namedLikeMilestone: (name) -> name?.match /^(Milestone|Sprint)/i
# Complete a task
completeTask: (taskId) ->
@client.put "/tasks/#{taskId}", data: completed: true
# Build meta info on a task
getMeta: (task) ->
# Muster data
url = @taskUrl task
stories = await @getTaskStories task.gid
author = await @getStoryCreator stories[0] if stories.length
# Return payload
url: url
author:
name: <NAME>
url: "https://app.asana.com/0/#{author.gid}"
icon: author.photo?.image_36x36
priority: switch @customFieldValue task, 'Priority'
when 'Critical' then '📕 Critical'
when 'High' then '📙 High'
when 'Medium' then '📒 Medium'
when 'Low' then '📘 Low'
comments: do ->
comments = stories.filter (story) -> story.type == 'comment'
return "💬 #{comments.length}"
date: '📅 '+(new Date(task.created_at)).toLocaleDateString 'en-US',
month:'short'
day:'numeric'
year: 'numeric'
# Make an array of the active value of "label" custom fields
getLabels: (task) ->
Object.keys(@labels).map (fieldName) =>
# Get the value of the field and return it if it's one of the values that
# get synced with GitLab
if value = @customFieldValue task, fieldName
if value in @labels[fieldName]
return value
# Remove labels that were empty
.filter (label) -> !!label
# Get a list of all the labels that are synced
syncedLabels: ->
Object.values(@labels).reduce (all, labels) -> all.concat labels
, []
# Take an array of labels from GitLab and return an object with keys for each
# fieldName and only one
normalizeLabels: (labels) ->
# Open a chain
_(labels)
# Group the incoming labels by Asana custom field names
.groupBy (label) =>
for fieldName, options of @labels
return fieldName if label in options
return '' # Default
# Remove null keys; these are labels that don't get synced to Asana
.pickBy (labels, fieldName) -> !!fieldName
# Reduce the labels to the highest priority or latest lifecycle label
# in the first index
.mapValues (labels, fieldName) =>
_(labels).orderBy (label) => @labels[fieldName].indexOf label
.first()
# Set emtpy strings for any fieldNames that weren't present in the list of
# labels so the value will clear if the label was removed in GitLab
.defaults _.mapValues @labels, -> null
# Return final object
.value() | true | # Deps
axios = require 'axios'
_ = require 'lodash'
db = new (require './db')
# Constants that are used in multiple places
PRIORITY_FIELD = 'Priority'
STATUS_FIELD = 'Dev status'
DEPLOYED_STATUS = 'Deployed'
# Define the service
module.exports = class Asana
# Constants for custom field names
PRIORITY_FIELD: PRIORITY_FIELD
STATUS_FIELD: STATUS_FIELD
ESTIMATE_FIELD: 'Est'
ISSUE_FIELD: 'GitLab'
# Constants for Statuses
ESTIMATE_STATUS: 'Estimating'
SCHEDULE_STATUS: 'Scheduling'
PENDING_STATUS: 'Pending'
DEPLOYED_STATUS: DEPLOYED_STATUS
# Status lables organized by custom fields and ordered intentionally
labels:
"#{PRIORITY_FIELD}": [
'Critical'
'High'
'Medium'
'Low'
]
"#{STATUS_FIELD}": [ # Only those that get synced
DEPLOYED_STATUS
'Approved'
'Staged'
'Addressed'
]
# Build Axios client
constructor: -> @client = axios.create
baseURL: 'https://app.asana.com/api/1.0'
headers: Authorization: "Bearer #{process.env.ASANA_ACCESS_TOKEN}"
# Fetch list of projects for access token
getProjects: ->
{ data } = await @client.get '/projects'
projects = data.data.map (project) ->
id: project.gid
name: project.name
return _.sortBy projects, 'name'
# Create a webhook for a given project id
createWebhook: (entryId, projectId) ->
{ data } = await @client.post '/webhooks', data:
resource: projectId
target: "#{process.env.GATEWAY_URL}/asana/webhook?entry=#{entryId}"
await db.put @webhookKey(entryId), data.data.gid
# Delete a webhook for a given project id
deleteWebhook: (entryId) ->
if webhookId = await db.get @webhookKey entryId
await @client.delete "/webhooks/#{webhookId}"
await db.delete @webhookKey entryId
# Make the key for storing webhooks
webhookKey: (entryId) -> "PI:KEY:<KEY>END_PI"
# Find a task given it's id
getTask: (id) ->
{ data } = await @client.get "/tasks/#{id}"
return data?.data
# Get the count of task stories
getTaskStories: (id) ->
{ data } = await @client.get "/tasks/#{id}/stories"
return data?.data
# Check if the status is a particular status
hasStatus: (task, status) ->
status == @getStatus task, status
# Check if the status is also a GitLab label or is pendinh
hasStatusLabelOrIsPending: (task) ->
@hasStatusLabel(task) or @getStatus(task) == @PENDING_STATUS
# Check if the status is also a GitLab label
hasStatusLabel: (task) -> @getStatus(task) in @labels[@STATUS_FIELD]
# Get the status for a task
getStatus: (task) -> @customFieldValue task, @STATUS_FIELD
# Get a custom field value
customFieldValue: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.enum_value?.name || field?.number_value || field?.text_value
# Get the id of a custom field
customFieldId: (task, fieldName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
return field?.gid
# For an enum field, find the id of the particular opion
customFieldEnumId: (task, fieldName, enumName) ->
field = task.custom_fields.find (field) -> field.name == fieldName
option = field?.enum_options?.find (option) -> option.name == enumName
return option?.gid || null
# Lookup the creator user of a story (like a note on a task)
getStoryCreator: (story) ->
{ data } = await @client.get "/users/#{story.created_by.gid}"
return data.data
# Check if the task is in the estimating phase but has no estimate
needsEstimate: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
not @customFieldValue(task, @ESTIMATE_FIELD)
# Check if we need and estimate and a message hasn't already been sent
needsEstimateAndNotSent: (task) ->
@needsEstimate(task) and not await db.get @estimateMessageKey(task)
# Check if the estimate message can be updated from slack
getEstimateMessageIfEstimateComplete: (task) ->
return if @needsEstimate task
return await db.get @estimateMessageKey(task)
# If we hvae an estimate but the status is still ON estimate
needsScheduleStatus: (task) ->
@hasStatus(task, @ESTIMATE_STATUS) and
@customFieldValue(task, @ESTIMATE_FIELD)
# Build the key used to keep track of the estimate notification
estimateMessageKey: (task) -> "PI:KEY:<KEY>END_PI#{task.gid}-PI:KEY:<KEY>END_PI"
# Make the URL to a task
taskUrl: (task) -> "https://app.asana.com/0/0/#{task.gid}"
# Update the status custom field
updateStatus: (task, status) ->
@updateEnumCustomField task, @STATUS_FIELD, status
# Update the status custom field
updatePriority: (task, priority) ->
@updateEnumCustomField task, @PRIORITY_FIELD, priority
# Update an enum custom value
updateEnumCustomField: (task, fieldName, value) ->
fieldId = @customFieldId task, fieldName
valueId = @customFieldEnumId task, fieldName, value
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": valueId
# Update the status custom field
updateEstimate: (task, hours) ->
fieldId = @customFieldId task, @ESTIMATE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": hours
# A task is ticketable if it is in a milestone-like section but doesn't have
# an issue yet and isn't named like a milestone (Asana will return sections
# like tasks)
issueable: (task) ->
@inMilestone(task) and
not @issued(task) and
task.name and # Has a name
not @namedLikeMilestone(task.name) and
not @hasStatus(task, @ESTIMATE_STATUS)
# Add a issue reference to Asana
addIssue: (task, issueUrl) ->
fieldId = @customFieldId task, @ISSUE_FIELD
@client.put "/tasks/#{task.gid}", data:
custom_fields: "#{fieldId}": issueUrl
# Has the task had a issue created for it?
issued: (task) -> !!@customFieldValue task, @ISSUE_FIELD
# Check if a task is in a milestone by seeing if any of it's memberships have
# a milestone/sprint style name
inMilestone: (task) -> !!@milestoneName task
# Get the milestone of an issue by looping through the memberships and
# getting section ones that match the naming convention. Trim trailing colon
# and whitespace from the name.
milestoneName: (task) ->
membership = task.memberships.find (membership) =>
@namedLikeMilestone membership.section?.name
return membership?.section.name.replace /\s*:\s*$/, ''
# Test if something has a milestone-like name
namedLikeMilestone: (name) -> name?.match /^(Milestone|Sprint)/i
# Complete a task
completeTask: (taskId) ->
@client.put "/tasks/#{taskId}", data: completed: true
# Build meta info on a task
getMeta: (task) ->
# Muster data
url = @taskUrl task
stories = await @getTaskStories task.gid
author = await @getStoryCreator stories[0] if stories.length
# Return payload
url: url
author:
name: PI:NAME:<NAME>END_PI
url: "https://app.asana.com/0/#{author.gid}"
icon: author.photo?.image_36x36
priority: switch @customFieldValue task, 'Priority'
when 'Critical' then '📕 Critical'
when 'High' then '📙 High'
when 'Medium' then '📒 Medium'
when 'Low' then '📘 Low'
comments: do ->
comments = stories.filter (story) -> story.type == 'comment'
return "💬 #{comments.length}"
date: '📅 '+(new Date(task.created_at)).toLocaleDateString 'en-US',
month:'short'
day:'numeric'
year: 'numeric'
# Make an array of the active value of "label" custom fields
getLabels: (task) ->
Object.keys(@labels).map (fieldName) =>
# Get the value of the field and return it if it's one of the values that
# get synced with GitLab
if value = @customFieldValue task, fieldName
if value in @labels[fieldName]
return value
# Remove labels that were empty
.filter (label) -> !!label
# Get a list of all the labels that are synced
syncedLabels: ->
Object.values(@labels).reduce (all, labels) -> all.concat labels
, []
# Take an array of labels from GitLab and return an object with keys for each
# fieldName and only one
normalizeLabels: (labels) ->
# Open a chain
_(labels)
# Group the incoming labels by Asana custom field names
.groupBy (label) =>
for fieldName, options of @labels
return fieldName if label in options
return '' # Default
# Remove null keys; these are labels that don't get synced to Asana
.pickBy (labels, fieldName) -> !!fieldName
# Reduce the labels to the highest priority or latest lifecycle label
# in the first index
.mapValues (labels, fieldName) =>
_(labels).orderBy (label) => @labels[fieldName].indexOf label
.first()
# Set emtpy strings for any fieldNames that weren't present in the list of
# labels so the value will clear if the label was removed in GitLab
.defaults _.mapValues @labels, -> null
# Return final object
.value() |
[
{
"context": "uel_test.coffee\n# mdo_prototype\n# \n# Created by Dmitry Shvetsov.\n# Copyright 2014 Dmitry Shvetsov. All rights re",
"end": 73,
"score": 0.9998883008956909,
"start": 58,
"tag": "NAME",
"value": "Dmitry Shvetsov"
},
{
"context": " \n# Created by Dmitry Shvetsov.\n# Copyright 2014 Dmitry Shvetsov. All rights reserved.\n# \n\n\n\nchai = require 'ch",
"end": 108,
"score": 0.9998860955238342,
"start": 93,
"tag": "NAME",
"value": "Dmitry Shvetsov"
}
] | test/duel_test.coffee | shvetsovdm/mdo_prototype | 0 | #
# duel_test.coffee
# mdo_prototype
#
# Created by Dmitry Shvetsov.
# Copyright 2014 Dmitry Shvetsov. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Duel class', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
newDuel = new libDuel { playerId: player }
it 'should have an id', ->
newDuel.id.should.be.a('string')
it 'should have refreshIn', ->
newDuel.refreshIn.should.be.a('number')
it 'should have the state', ->
newDuel.state.should.be.a('string')
it 'should have number of rounds', ->
newDuel.nRound.should.be.a('number')
it 'should have players', ->
newDuel.players.should.be.a('object')
it 'should have array rounds', ->
newDuel.rounds.should.be.an('array') | 218851 | #
# duel_test.coffee
# mdo_prototype
#
# Created by <NAME>.
# Copyright 2014 <NAME>. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Duel class', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
newDuel = new libDuel { playerId: player }
it 'should have an id', ->
newDuel.id.should.be.a('string')
it 'should have refreshIn', ->
newDuel.refreshIn.should.be.a('number')
it 'should have the state', ->
newDuel.state.should.be.a('string')
it 'should have number of rounds', ->
newDuel.nRound.should.be.a('number')
it 'should have players', ->
newDuel.players.should.be.a('object')
it 'should have array rounds', ->
newDuel.rounds.should.be.an('array') | true | #
# duel_test.coffee
# mdo_prototype
#
# Created by PI:NAME:<NAME>END_PI.
# Copyright 2014 PI:NAME:<NAME>END_PI. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Duel class', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
newDuel = new libDuel { playerId: player }
it 'should have an id', ->
newDuel.id.should.be.a('string')
it 'should have refreshIn', ->
newDuel.refreshIn.should.be.a('number')
it 'should have the state', ->
newDuel.state.should.be.a('string')
it 'should have number of rounds', ->
newDuel.nRound.should.be.a('number')
it 'should have players', ->
newDuel.players.should.be.a('object')
it 'should have array rounds', ->
newDuel.rounds.should.be.an('array') |
[
{
"context": "# Author: Josh Bass\n\nReact = require(\"react\");\nmathjs = require(\"math",
"end": 19,
"score": 0.9998779296875,
"start": 10,
"tag": "NAME",
"value": "Josh Bass"
}
] | src/client/components/analytics/AnalyticsView.coffee | jbass86/Aroma | 0 | # Author: Josh Bass
React = require("react");
mathjs = require("mathjs");
css = require("./res/css/analytics.css")
module.exports = React.createClass
getInitialState: ->
{};
componentDidMount: ->
render: ->
<div className="common-view inventory-view">
<div style={{"textAlign": "center", "color": "white"}}>
<span>Analytics Coming Later...</span>
</div>
</div>
| 163628 | # Author: <NAME>
React = require("react");
mathjs = require("mathjs");
css = require("./res/css/analytics.css")
module.exports = React.createClass
getInitialState: ->
{};
componentDidMount: ->
render: ->
<div className="common-view inventory-view">
<div style={{"textAlign": "center", "color": "white"}}>
<span>Analytics Coming Later...</span>
</div>
</div>
| true | # Author: PI:NAME:<NAME>END_PI
React = require("react");
mathjs = require("mathjs");
css = require("./res/css/analytics.css")
module.exports = React.createClass
getInitialState: ->
{};
componentDidMount: ->
render: ->
<div className="common-view inventory-view">
<div style={{"textAlign": "center", "color": "white"}}>
<span>Analytics Coming Later...</span>
</div>
</div>
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9935612082481384,
"start": 16,
"tag": "NAME",
"value": "Konode"
},
{
"context": "\t\t\tisEditable: isEditing\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tkey: metric.get('id')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tname: metric.get('name')\n\t\t\t\t",
"end": 44931,
"score": 0.7328571081161499,
"start": 44928,
"tag": "KEY",
"value": "get"
}
] | src/clientFilePage/progNotesTab.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Client file view for displaying, searching, and updating progress notes
Fs = require 'fs'
Path = require 'path'
Assert = require 'assert'
Imm = require 'immutable'
Moment = require 'moment'
Async = require 'async'
_ = require 'underscore'
Config = require '../config'
Term = require '../term'
Persist = require '../persist'
dataTypeOptions = Imm.fromJS [
# {name: 'Progress Notes', id: 'progNotes'}
# {name: 'Targets', id: 'targets'}
{name: 'Events', id: 'events'}
]
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
ReactDOMServer = win.ReactDOMServer
Mark = win.Mark
B = require('../utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
CancelProgNoteDialog = require('./cancelProgNoteDialog').load(win)
ColorKeyBubble = require('../colorKeyBubble').load(win)
CrashHandler = require('../crashHandler').load(win)
ExpandingTextArea = require('../expandingTextArea').load(win)
MetricWidget = require('../metricWidget').load(win)
ProgEventWidget = require('../progEventWidget').load(win)
OpenDialogLink = require('../openDialogLink').load(win)
ProgNoteDetailView = require('../progNoteDetailView').load(win)
EntryDateNavigator = require('./entryDateNavigator').load(win)
FilterBar = require('./filterBar').load(win)
{
FaIcon, openWindow, renderLineBreaks, showWhen, formatTimestamp, renderName, makeMoment
getUnitIndex, getPlanSectionIndex, getPlanTargetIndex, blockedExtensions, stripMetadata, scrollToElement
} = require('../utils').load(win)
# List of fields we exclude from keyword search
excludedSearchFields = Imm.fromJS [
'id', 'revisionId', 'templateId', 'typeId', 'relatedProgNoteId', 'programId'
'relatedProgEventId', 'authorProgramId', 'clientFileId'
'timestamp', 'backdate', 'startTimestamp', 'endTimestamp'
'type', 'entryType', 'status', 'definition'
# 'filteredProgNote' and {entryType: globalEvent} used instead
'progNoteHistory', 'globalEvents'
]
ProgNotesTab = React.createFactory React.createClass
displayName: 'ProgNotesTab'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
hasChanges: ->
@refs.ui.hasChanges()
_toProgNoteHistoryEntry: (progNoteHistory) ->
latestRevision = progNoteHistory.last()
firstRevision = progNoteHistory.first()
# We pass down a pre-filtered version of the progNote
# because the search-by-keyword feature relies on this data
filteredProgNote = filterEmptyProgNoteValues(latestRevision)
# Revisions all have same 'id', just different revisionIds
progNoteId = firstRevision.get('id')
programId = firstRevision.get('authorProgramId')
timestamp = latestRevision.get('backdate') or firstRevision.get('timestamp')
# Mix in all other related data from clientFile's other collections
progEvents = @props.progEvents.filter (progEvent) ->
return progEvent.get('relatedProgNoteId') is progNoteId
# progNote still gets any cancelled globalEvents
globalEvents = @props.globalEvents.filter (globalEvent) ->
return globalEvent.get('relatedProgNoteId') is progNoteId
attachments = @props.attachmentsByProgNoteId.get(progNoteId) or Imm.List()
return Imm.Map {
entryType: 'progNote'
id: progNoteId
programId
timestamp
progNoteHistory
filteredProgNote
progEvents
globalEvents
attachments
}
_toGlobalEventEntry: (globalEvent) ->
timestamp = globalEvent.get('startTimestamp') # Order by startTimestamp
return Imm.Map {
entryType: 'globalEvent'
id: globalEvent.get('id')
programId: globalEvent.get('programId')
timestamp
globalEvent
}
render: ->
progNoteEntries = @props.progNoteHistories.map @_toProgNoteHistoryEntry
globalEventEntries = @props.globalEvents
.filter (e) -> e.get('status') is 'default'
.map @_toGlobalEventEntry
historyEntries = progNoteEntries
.concat globalEventEntries
.sortBy (entry) -> entry.get('timestamp')
.reverse()
props = _.extend {}, @props, {
ref: 'ui'
historyEntries
}
return ProgNotesTabUi(props)
ProgNotesTabUi = React.createFactory React.createClass
displayName: 'ProgNotesTabUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
editingProgNoteId: null
attachment: null
selectedItem: null
backdate: ''
transientData: null
isLoading: null
isFiltering: null
showHistory: true
searchQuery: ''
programIdFilter: null
dataTypeFilter: null
}
hasChanges: ->
@_transientDataHasChanges()
render: ->
{transientData} = @state
hasChanges = @hasChanges()
hasEnoughData = @props.historyEntries.size > 0
isEditing = transientData?
# Only show the single progNote while editing
historyEntries = if not isEditing then @props.historyEntries else Imm.List [
@props.historyEntries.find (entry) ->
entry.get('id') is transientData.getIn(['progNote', 'id'])
]
####### Filtering / Search Logic #######
if @state.isFiltering
# TODO: Make this filtering faster
# By program?
if @state.programIdFilter
historyEntries = historyEntries.filter (e) => e.get('programId') is @state.programIdFilter
# By type of progNote?
if @state.dataTypeFilter in ['progNotes', 'targets']
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'progNote'
# by event without a query (suppress notes)
if @state.dataTypeFilter is 'events'
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'globalEvent' or not e.get('progEvents').isEmpty()
# When searching 'targets', only check 'full' progNotes
# TODO: Restore this dataType at some point
# if @state.dataTypeFilter is 'targets'
# historyEntries = historyEntries.filter (e) => e.getIn(['filteredProgNote', 'type']) is 'full'
# By search query? Pass dataTypeFilter for conditional property checks
if @state.searchQuery.trim().length > 0
historyEntries = @_filterEntries(historyEntries, @state.dataTypeFilter)
return R.div({className: 'progNotesView'},
R.div({className: 'panes'},
R.section({className: 'leftPane'},
# TODO: Make component
R.div({className: 'flexButtonToolbar'},
R.button({
className: [
'saveButton'
'collapsed' unless isEditing
].join ' '
onClick: @_saveTransientData
disabled: not hasChanges
},
FaIcon('save')
R.span({className: 'wideMenuItemText'},
"Save #{Term 'Progress Note'}"
)
)
R.button({
className: [
'discardButton'
'collapsed' unless isEditing
].join ' '
onClick: @_cancelRevisingProgNote
},
FaIcon('undo')
R.span({className: 'wideMenuItemText'},
"Discard"
)
)
R.button({
className: [
'newProgNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewProgNote
disabled: @state.isLoading or @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Progress Note'}"
)
)
R.button({
ref: 'addQuickNoteButton'
className: [
'addQuickNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewQuickNote
disabled: @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Quick Note'}"
)
)
R.button({
ref: 'openFilterBarButton'
className: [
'openFilterBarButton'
'collapsed' if isEditing or @state.isFiltering
showWhen hasEnoughData
].join ' '
onClick: @_toggleIsFiltering
},
FaIcon('search')
)
R.button({
ref: 'toggleHistoryPane'
className: [
'toggleHistoryPaneButton'
].join ' '
onClick: @_toggleHistoryPane
},
(if @state.showHistory
FaIcon('angle-right')
else
FaIcon('angle-left')
)
)
)
(unless hasEnoughData
R.div({className: 'empty'},
R.div({className: 'message'},
"This #{Term 'client'} does not currently have any #{Term 'progress notes'}."
)
)
)
(if @state.isFiltering and not isEditing
FilterBar({
ref: 'filterBar'
historyEntries
programIdFilter: @state.programIdFilter
dataTypeFilter: @state.dataTypeFilter
programsById: @props.programsById
dataTypeOptions
onClose: @_toggleIsFiltering
onUpdateSearchQuery: @_updateSearchQuery
onSelectProgramId: @_updateProgramIdFilter
onSelectDataType: @_updateDataTypeFilter
})
)
# TODO: Make component
R.div({
className: [
'empty'
showWhen @state.isFiltering and historyEntries.isEmpty()
].join ' '
},
R.div({className: 'message animated fadeIn'},
R.div({},
"No results found"
(if @state.dataTypeFilter
R.span({},
" in "
R.strong({},
dataTypeOptions.find((t) => t.get('id') is @state.dataTypeFilter).get('name')
)
)
)
)
(if @state.searchQuery.trim().length > 0
R.div({},
"matching: \""
R.strong({}, @state.searchQuery)
"\""
)
)
(if @state.programIdFilter
R.div({},
"for: "
R.strong({},
@props.programsById.getIn [@state.programIdFilter, 'name']
)
ColorKeyBubble({
colorKeyHex: @props.programsById.getIn [@state.programIdFilter, 'colorKeyHex']
})
)
)
R.div({},
R.button({
id: 'resetFilterButton'
className: 'btn btn-link'
onClick: => @refs.filterBar.clear()
},
FaIcon('refresh')
"Reset"
)
)
)
)
# Apply selectedItem styles as inline <style>
(if @state.selectedItem?
InlineSelectedItemStyles({
selectedItem: @state.selectedItem
})
)
EntriesListView({
ref: 'entriesListView'
historyEntries
entryIds: historyEntries.map (e) -> e.get('id')
transientData
eventTypes: @props.eventTypes
clientFile: @props.clientFile
programsById: @props.programsById
planTargetsById: @props.planTargetsById
dataTypeFilter: @state.dataTypeFilter
searchQuery: @state.searchQuery
programIdFilter: @state.programIdFilter
isFiltering: @state.isFiltering
isReadOnly: @props.isReadOnly
isEditing
setSelectedItem: @_setSelectedItem
selectProgNote: @_selectProgNote
startRevisingProgNote: @_startRevisingProgNote
cancelRevisingProgNote: @_cancelRevisingProgNote
updatePlanTargetNotes: @_updatePlanTargetNotes
updateBasicUnitNotes: @_updateBasicUnitNotes
updateBasicMetric: @_updateBasicMetric
updatePlanTargetMetric: @_updatePlanTargetMetric
updateProgEvent: @_updateProgEvent
updateQuickNotes: @_updateQuickNotes
updateShiftSummary: @_updateShiftSummary
})
)
R.section({
className: [
'rightPane'
'collapsed' unless @state.showHistory
].join ' '
},
ProgNoteDetailView({
ref: 'progNoteDetailView'
isFiltering: @state.isFiltering
searchQuery: @state.searchQuery
item: @state.selectedItem
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
metricsById: @props.metricsById
programsById: @props.programsById
})
)
)
)
_startRevisingProgNote: (progNote, progEvents) ->
# Include transient and original data into generic store
transientData = Imm.fromJS {
progNote
originalProgNote: progNote
progEvents
originalProgEvents: progEvents
# TODO: Allow editing for globalEvents as well
}
@setState {transientData}
_cancelRevisingProgNote: ->
if @_transientDataHasChanges()
return Bootbox.confirm "Discard all changes made to the #{Term 'progress note'}?", (ok) =>
if ok then @_discardTransientData()
@_discardTransientData()
_discardTransientData: ->
@setState {transientData: null}
_transientDataHasChanges: ->
transientData = @state.transientData
return null unless transientData?
originalProgNote = transientData.get('originalProgNote')
progNote = transientData.get('progNote')
progNoteHasChanges = not Imm.is progNote, originalProgNote
originalProgEvents = transientData.get('originalProgEvents')
progEvents = transientData.get('progEvents')
progEventsHasChanges = not Imm.is progEvents, originalProgEvents
# TODO: Compare globalEvents
return progNoteHasChanges or progEventsHasChanges
_updateBasicUnitNotes: (unitId, event) ->
newNotes = event.target.value
transientData = @state.transientData
unitIndex = getUnitIndex transientData.get('progNote'), unitId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'notes'
]
newNotes
)
}
_updatePlanTargetNotes: (unitId, sectionId, targetId, event) ->
newNotes = event.target.value
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'notes'
]
newNotes
)
}
_updateQuickNotes: (event) ->
newNotes = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'notes'], newNotes
}
_updateShiftSummary: (event) ->
newSummary = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'summary'], newSummary
}
_updateProgEvent: (index, updatedProgEvent) ->
transientData = @state.transientData.setIn ['progEvents', index], updatedProgEvent
@setState {transientData}
_isValidMetric: (value) -> value.match /^-?\d*\.?\d*$/
_updatePlanTargetMetric: (unitId, sectionId, targetId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
metricIndex = progNote.getIn(
[
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex,
'metrics'
]
).findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_updateBasicMetric: (unitId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
metricIndex = progNote.getIn ['units', unitIndex, 'metrics']
.findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_saveTransientData: ->
{progNote, progEvents, originalProgNote, originalProgEvents} = @state.transientData.toObject()
# Any progEvents modified?
revisedProgEvents = progEvents.filter (progEvent, index) ->
not Imm.is progEvent, originalProgEvents.get(index)
# Only save modified progNotes/progEvents
Async.series [
(cb) ->
return cb() if Imm.is originalProgNote, progNote
ActiveSession.persist.progNotes.createRevision progNote, cb
(cb) ->
return cb() if revisedProgEvents.isEmpty()
Async.map revisedProgEvents, ActiveSession.persist.progEvents.createRevision, cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
@_discardTransientData()
_checkUserProgram: (cb) ->
# Skip if no clientProgram(s)
if @props.clientPrograms.isEmpty()
cb()
return
userProgramId = global.ActiveSession.programId
# Skip if userProgram matches one of the clientPrograms
matchingUserProgram = @props.clientPrograms.find (program) ->
userProgramId is program.get('id')
if matchingUserProgram
cb()
return
# override by default if client only in a single program
if @props.clientPrograms.size is 1
userProgramId = @props.clientPrograms.first().get('id')
userProgram = @props.programsById.get userProgramId
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
cb()
return
clientName = renderName @props.clientFile.get('clientName')
userProgramName = if userProgramId
@props.programsById.getIn [userProgramId, 'name']
else
"(none)"
# Build programDropdown markup
programDropdown = R.select({
id: 'programDropdown'
className: 'form-control '
},
R.option({value: ''}, "Select a #{Term 'client'} #{Term 'program'}"),
(@props.clientPrograms.map (program) ->
R.option({
key: program.get('id')
value: program.get('id')
},
program.get('name')
)
)
)
focusPopover = ->
setTimeout (=>
$popover = $('.popover textarea')[0]
if $popover? then $popover.focus()
), 500
# Prompt user about temporarily overriding their program
Bootbox.dialog {
title: "Switch to #{Term 'client'} #{Term 'program'}?"
message: R.div({},
"#{clientName} is not enrolled in your assigned #{Term 'program'}: ",
'"', R.b({}, userProgramName), '".',
R.br(), R.br(),
"Override your assigned #{Term 'program'} below, or click \"Ignore\"."
R.br(), R.br(),
programDropdown
)
buttons: {
cancel: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
ignore: {
label: "Ignore"
className: "btn-warning"
callback: ->
focusPopover()
cb()
}
success: {
label: "Override #{Term 'Program'}"
className: "btn-success"
callback: =>
userProgramId = $('#programDropdown').val()
if not userProgramId? or userProgramId.length is 0
Bootbox.alert "No #{Term 'program'} was selected, please try again."
return
userProgram = @props.programsById.get userProgramId
# Override the user's program
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
focusPopover()
cb()
}
}
}
_checkPlanChanges: (cb) ->
# Check for unsaved changes to the client plan
if not @props.hasChanges()
cb()
return
# Prompt user about unsaved changes
Bootbox.dialog {
title: "Unsaved Changes to #{Term 'Plan'}"
message: """
You have unsaved changes in the #{Term 'plan'} that will not be reflected in this
#{Term 'progress note'}. How would you like to proceed?
"""
buttons: {
default: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
danger: {
label: "Ignore"
className: "btn-danger"
callback: -> cb()
}
success: {
label: "View #{Term 'Plan'}"
className: "btn-success"
callback: =>
Bootbox.hideAll()
@props.onTabChange 'plan'
return
}
}
}
_openNewProgNote: ->
Async.series [
@_checkPlanChanges
@_checkUserProgram
(cb) =>
@setState {isLoading: true}
# Cache data to global, so can access again from newProgNote window
# Set up the dataStore if doesn't exist
# Store property as clientFile ID to prevent confusion
global.dataStore ?= {}
# Only needs to pass latest revisions of each planTarget
# In this case, index [0] is the latest revision
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
global.dataStore[@props.clientFileId] = {
clientFile: @props.clientFile
planTargetsById
metricsById: @props.metricsById
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
programsById: @props.programsById
clientPrograms: @props.clientPrograms
}
openWindow {page: 'newProgNote', clientFileId: @props.clientFileId}, (newProgNoteWindow) =>
# prevent window from closing before its ready
# todo a more elegant way to do this?
newProgNoteWindow.on 'close', =>
newProgNoteWindow = null
global.ActiveSession.persist.eventBus.once 'newProgNotePage:loaded', cb
], (err) =>
@setState {isLoading: false}
if err
CrashHandler.handle err
return
_openNewQuickNote: ->
Async.series [
@_checkUserProgram
@_toggleQuickNotePopover
], (err) ->
if err
CrashHandler.handle err
return
_attach: ->
# Configures hidden file inputs with custom attributes, and clicks it
$nwbrowse = $('#nwBrowse')
$nwbrowse
.off()
#.attr('accept', ".#{extension}")
.on('change', (event) => @_encodeFile event.target.value)
.click()
_encodeFile: (file) ->
return unless file
# clear input value so onchange can still fire if user tries same file again
$('#nwBrowse').val(null)
filename = Path.basename file
fileExtension = (Path.extname file).toLowerCase()
if blockedExtensions.indexOf(fileExtension) > -1
Bootbox.alert {
title: "Warning: File Blocked"
message: "#{filename} is potentially unsafe and cannot be attached."
}
return
attachment = Fs.readFileSync(file)
filesize = Buffer.byteLength(attachment, 'base64')
if filesize < 1048576
filesize = (filesize / 1024).toFixed() + " KB"
else
filesize = (filesize / 1048576).toFixed() + " MB"
# Convert to base64 encoded string
encodedAttachment = Buffer.from(attachment).toString 'base64'
@setState {
attachment: {
encodedData: encodedAttachment
filename: filename
}
}
# TODO: Append for when multiple attachments allowed (#787)
$('#attachmentArea').html filename + " (" + filesize + ") <i class='fa fa-times' id='removeBtn'></i>"
removeFile = $('#removeBtn')
removeFile.on 'click', (event) =>
$('#attachmentArea').html ''
@setState {attachment: null}
_toggleQuickNotePopover: ->
# TODO: Refactor to stateful React component
quickNoteToggle = $(findDOMNode @refs.addQuickNoteButton)
quickNoteToggle.popover {
placement: 'bottom'
html: true
trigger: 'manual'
content: '''
<textarea class="form-control"></textarea>
<div id="attachmentArea" style="padding-top:10px; color:#3176aa;"></div>
<div class="buttonBar form-inline">
<label>Date: </label> <input type="text" class="form-control backdate date"></input>
<button class="btn btn-default" id="attachBtn"><i class="fa fa-paperclip"></i> Attach</button>
<button class="cancel btn btn-danger"><i class="fa fa-trash"></i> Discard</button>
<button class="save btn btn-primary"><i class="fa fa-check"></i> Save</button>
<input type="file" class="hidden" id="nwBrowse"></input>
</div>
'''
}
if quickNoteToggle.data('isVisible')
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
else
quickNoteToggle.popover('show')
quickNoteToggle.data('isVisible', true)
attachFile = $('#attachBtn')
attachFile.on 'click', (event) =>
@_attach event
attachFile.blur()
popover = quickNoteToggle.siblings('.popover')
popover.find('.save.btn').on 'click', (event) =>
event.preventDefault()
@_createQuickNote popover.find('textarea').val(), @state.backdate, @state.attachment, (err) =>
@setState {
backdate: '',
attachment: null
}
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('.backdate.date').datetimepicker({
format: 'MMM-DD-YYYY h:mm A'
defaultDate: Moment()
maxDate: Moment()
widgetPositioning: {
vertical: 'bottom'
}
}).on 'dp.change', (e) =>
if Moment(e.date).format('YYYY-MM-DD-HH') is Moment().format('YYYY-MM-DD-HH')
@setState {backdate: ''}
else
@setState {backdate: Moment(e.date).format(Persist.TimestampFormat)}
popover.find('.cancel.btn').on 'click', (event) =>
event.preventDefault()
@setState {
backdate: '',
attachment: null
}
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('textarea').focus()
# Store quickNoteBeginTimestamp as class var, since it wont change
@quickNoteBeginTimestamp = Moment().format(Persist.TimestampFormat)
_createQuickNote: (notes, backdate, attachment, cb) ->
unless notes
Bootbox.alert "Cannot create an empty #{Term 'quick note'}."
return
quickNote = Imm.fromJS {
type: 'basic'
status: 'default'
clientFileId: @props.clientFileId
notes
backdate
authorProgramId: global.ActiveSession.programId or ''
beginTimestamp: @quickNoteBeginTimestamp
}
# TODO: Async series
global.ActiveSession.persist.progNotes.create quickNote, (err, result) =>
if err
cb err
return
unless attachment
cb()
return
attachmentData = Imm.fromJS {
status: 'default'
filename: attachment.filename
encodedData: attachment.encodedData
clientFileId: @props.clientFileId
relatedProgNoteId: result.get('id')
}
global.ActiveSession.persist.attachments.create attachmentData, cb
_setSelectedItem: (selectedItem) ->
@setState {selectedItem}
_selectProgNote: (progNote) ->
@_setSelectedItem Imm.fromJS {
type: 'progNote'
progNoteId: progNote.get('id')
}
_filterEntries: (entries, dataTypeFilter) ->
if @state.searchQuery.trim().length is 0
return entries
# Split into query parts
queryParts = Imm.fromJS(@state.searchQuery.split(' ')).map (p) -> p.toLowerCase()
containsSearchQuery = (data) ->
if dataTypeFilter
# Only search through 'progNote' types for progNotes and targets
if dataTypeFilter in ['progNotes', 'targets'] and data.has('entryType') and data.get('entryType') isnt 'progNote'
return false
# For 'targets', favour 'filteredProgNote' with 'type: full' - since it only contains targets with data
# TODO: Restore this dataType at some point
# else if dataTypeFilter is 'targets'
# data = data.get('filteredProgNote') or data
else if dataTypeFilter is 'events'
# Ignore progNote entries without progEvents
if data.has('entryType') and data.get('entryType') isnt 'globalEvent' and data.get('progEvents').isEmpty()
return false
# Favor 'progEvents' in progNote entries
else
data = data.get('progEvents') or data
return data.some (value, property) ->
# Skip excluded field
if excludedSearchFields.includes property
return false
# Run all keywords against string contents
if typeof value is 'string'
value = value.toLowerCase()
includesAllParts = queryParts.every (part) -> value.includes(part)
# if includesAllParts then console.log "Match:", "#{property}:", value
return includesAllParts
# When not a string, it must be an Imm.List / Map
# so we'll loop through this same method on it
return containsSearchQuery(value)
# Only keep entries that contain all query parts
return entries.filter containsSearchQuery
_updateSearchQuery: (searchQuery) ->
@setState {searchQuery}
_toggleIsFiltering: ->
isFiltering = not @state.isFiltering
# Clear filter values when toggling off filterBar
if not isFiltering
@setState {
isFiltering
searchQuery: ''
dataTypeFilter: null
programIdFilter: null
}
return
@setState {isFiltering}
_toggleHistoryPane: ->
showHistory = not @state.showHistory
@setState {showHistory}
_updateProgramIdFilter: (programIdFilter) ->
@setState {programIdFilter}
_updateDataTypeFilter: (dataTypeFilter) ->
@setState {dataTypeFilter}
EntriesListView = React.createFactory React.createClass
displayName: 'EntriesListView'
mixins: [React.addons.PureRenderMixin]
getInitialState: -> {
historyCount: 10
filterCount: 10
}
componentDidMount: ->
# Watch scroll for infinite scroll behaviour, throttle to 1call/per/150ms
@_watchUnlimitedScroll = _.throttle(@_watchUnlimitedScroll, 150)
@entriesListView = $(findDOMNode @)
@entriesListView.on 'scroll', @_watchUnlimitedScroll
# Custom positioning logic to have EntryDateNavigator hug this.bottom-right
@entryDateNavigator = $(findDOMNode @refs.entryDateNavigator)
# Set initial position, and listen for window resize
@rightPane = $('.rightPane')[1] #todo: clunky... Ref not available here, maybe get from this upstream?
@_setNavigatorRightOffset()
$(win).on 'resize', @_setNavigatorRightOffset
componentDidUpdate: (oldProps, oldState) ->
# Update highlighting when anything changes while searching
# TODO: Maybe wrap component with this logic; allow state to change unimpeded
if @props.isFiltering
filterParametersChanged = (
@props.searchQuery isnt oldProps.searchQuery or
@props.dataTypeFilter isnt oldProps.dataTypeFilter or
@props.programIdFilter isnt oldProps.programIdFilter
)
# Reset filterCount and scroll to top anytime filter parameters change
if filterParametersChanged
@setState @getInitialState, @_resetScroll
if @props.searchQuery
if @state.filterCount > oldState.filterCount
# Only highlight new entries added from unlimited-scroll
newEntriesCount = @state.filterCount - oldState.filterCount
entryNodes = @props.entryIds
.slice 0, @state.filterCount
.takeLast newEntriesCount
.map (id) -> win.document.getElementById(id)
.toArray()
new Mark(entryNodes).mark(@props.searchQuery)
else
@_redrawSearchHighlighting()
# Toggle FilterBar, resets selectedItem
if @props.isFiltering isnt oldProps.isFiltering
if @props.isFiltering
# Reset filterCount when FilterBar opens
@setState {filterCount: 10}
else
# Clear search highlighting when FilterBar closes
@_redrawSearchHighlighting()
@props.setSelectedItem(null)
# Reset scroll when opens edit view for progNote
if @props.isEditing isnt oldProps.isEditing and @props.isEditing
@_resetScroll()
componentWillUnmount: ->
@entriesListView.off 'scroll', @_watchUnlimitedScroll
$(win.document).off 'resize', @_setNavigatorRightOffset
_watchUnlimitedScroll: ->
# Skip if we're scrolling via EntryDateNavigator, entry count is already set
return if @isAutoScrolling
# Detect if we've reached the lower threshold to trigger update
if @entriesListView.scrollTop() + (@entriesListView.innerHeight() *2) >= @entriesListView[0].scrollHeight
# Count is contextual to complete history, or filtered entries
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
# Disregard if nothing left to load into the count
return if @state[countType] >= @props.historyEntries.size
# Update UI with +10 to entry count
nextState = {}
nextState[countType] = @state[countType] + 10
@setState(nextState)
_setNavigatorRightOffset: ->
# Add rightPane's width to navigator's initial (css) right positioning
# TODO: Can we use new chrome 'sticky' instead? Sometimes doesn't show on HCR
right = if @rightPane? then @rightPane.offsetWidth else 0
@entryDateNavigator.css {right}
_scrollToEntryDate: (date, cb=(->)) ->
# TODO: Have moment objs already pre-built in historyEntries
entry = @props.historyEntries.find (e) ->
timestamp = makeMoment e.get('timestamp')
return date.isSame timestamp, 'day'
if not entry?
console.warn "Cancelled scroll, could not find #{date.toDate()} in historyEntries"
cb()
return
# Should we supplement filter/historyCount first?
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
index = @props.historyEntries.indexOf entry
requiresMoreEntries = @state[countType] - 1 < index
Async.series [
(cb) =>
return cb() unless requiresMoreEntries
# Provide 10 extra entries, so destinationEntry appears at top
# Set the new count (whichever type is pertinent), and *then* scroll to the entry
newState = {}
newState[countType] = (index + 1) + 10
@setState newState, cb
(cb) =>
# Scroll to latest entry matching date
$entriesListView = findDOMNode(@)
$element = win.document.getElementById "entry-#{entry.get('id')}"
@isAutoScrolling = true # Temporarily block scroll listener(s)
scrollToElement $entriesListView, $element, 1000, 'easeInOutQuad', cb
(cb) =>
@isAutoScrolling = false
# Scroll is completed, briefly highlight/animate any entries with matching date
selectedMoment = makeMoment entry.get('timestamp')
entryIdsToFlash = @props.historyEntries
.filter (e) ->
timestamp = makeMoment e.get('timestamp')
return selectedMoment.isSame makeMoment(timestamp), 'day'
.map (e) -> '#entry-' + e.get('id')
.toArray()
.join ', '
$(entryIdsToFlash).addClass 'flashDestination'
setTimeout(->
$(entryIdsToFlash).removeClass 'flashDestination'
, 2500)
cb()
], cb
_resetScroll: ->
findDOMNode(@).scrollTop = 0
_redrawSearchHighlighting: ->
# Performs a complete (expensive) mark/unmark of the entire EntriesListView
entriesHighlighting = new Mark findDOMNode @refs.entriesListView
if @props.isFiltering
entriesHighlighting.unmark().mark(@props.searchQuery)
else
entriesHighlighting.unmark()
render: ->
{historyEntries, isFiltering} = @props
# Limit number of entries by filter/historyCount
sliceCount = if isFiltering then @state.filterCount else @state.historyCount
slicedHistoryEntries = historyEntries.slice 0, sliceCount
R.div({
ref: 'entriesListView'
id: 'entriesListView'
className: showWhen not slicedHistoryEntries.isEmpty()
},
EntryDateNavigator({
ref: 'entryDateNavigator'
historyEntries: @props.historyEntries
onSelect: @_scrollToEntryDate
})
(slicedHistoryEntries.map (entry) =>
switch entry.get('entryType')
when 'progNote'
# Combine entry with @props + key
ProgNoteContainer(_.extend entry.toObject(), @props, {
key: entry.get('id')
})
when 'globalEvent'
GlobalEventView({
key: entry.get('id')
globalEvent: entry.get('globalEvent')
programsById: @props.programsById
eventTypes: @props.eventTypes
})
else
throw new Error "Unknown historyEntries entryType: \"#{entry.get('entryType')}\""
)
)
ProgNoteContainer = React.createFactory React.createClass
displayName: 'ProgNoteContainer'
mixins: [React.addons.PureRenderMixin]
render: ->
{isEditing, filteredProgNote, progEvents, globalEvents, dataTypeFilter} = @props
progNote = @props.progNoteHistory.last()
progNoteId = progNote.get('id')
firstProgNoteRev = @props.progNoteHistory.first()
userProgramId = firstProgNoteRev.get('authorProgramId')
userProgram = @props.programsById.get(userProgramId) or Imm.Map()
# TODO: Refactor to extended props
if progNote.get('status') is 'cancelled'
return CancelledProgNoteView({
progNoteHistory: @props.progNoteHistory
filteredProgNote
dataTypeFilter
attachments: @props.attachments
progEvents
globalEvents
eventTypes: @props.eventTypes
clientFile: @props.clientFile
userProgram
planTargetsById: @props.planTargetsById
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updatePlanTargetNotes: @props.updatePlanTargetNotes
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
Assert.equal progNote.get('status'), 'default'
switch progNote.get('type')
when 'basic'
QuickNoteView({
progNote
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
userProgram
clientFile: @props.clientFile
dataTypeFilter
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
progNote
filteredProgNote
dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents
globalEvents
userProgram
planTargetsById: @props.planTargetsById
eventTypes: @props.eventTypes
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
setEditingProgNoteId: @props.setEditingProgNoteId
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updateBasicMetric: @props.updateBasicMetric
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
QuickNoteView = React.createFactory React.createClass
displayName: 'QuickNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Don't render anything if only events are shown
if dataTypeFilter is 'events' and not isEditing
return null
progNote = if isEditing then @props.transientData.get('progNote') else @props.progNote
if @props.attachments?
attachmentText = " " + @props.attachments.get('filename')
R.div({
id: "entry-#{progNote.get('id')}"
className: [
'entry basic progNote'
'isEditing' if isEditing
].join ' '
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'notes'},
R.div({onClick: @_selectQuickNote},
(if isEditing
ExpandingTextArea({
value: progNote.get('notes')
onChange: @props.updateQuickNotes
})
else
renderLineBreaks progNote.get('notes')
)
)
(@props.attachments.map (attachment) =>
{id, filename} = attachment.toObject()
fileExtension = Path.extname filename
R.a({
key: id
className: 'attachment'
onClick: @_openAttachment.bind null, attachment
},
FaIcon(fileExtension)
' '
filename
)
)
)
)
_openAttachment: (attachment) ->
attachmentId = attachment.get('id')
clientFileId = @props.clientFile.get('id')
global.ActiveSession.persist.attachments.readLatestRevisions clientFileId, attachmentId, 1, (err, results) ->
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
attachment = results.first()
encodedData = attachment.get('encodedData')
filename = attachment.get('filename')
if filename?
# Absolute path required for windows
filepath = Path.join process.cwd(), Config.backend.dataDirectory, '_tmp', filename
file = Buffer.from(encodedData, 'base64')
# TODO cleanup file...
Fs.writeFile filepath, file, (err) ->
if err
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
nw.Shell.openItem filepath
_selectQuickNote: ->
@props.setSelectedItem Imm.fromJS {
type: 'quickNote'
progNoteId: @props.progNote.get('id')
}
ProgNoteView = React.createFactory React.createClass
displayName: 'ProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Use transient data when isEditing
progNote = if isEditing then @props.transientData.get('progNote') else @props.filteredProgNote
progEvents = if isEditing then @props.transientData.get('progEvents') else @props.progEvents
R.div({
id: "entry-#{progNote.get('id')}"
className: 'entry full progNote'
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
filteredProgNote: @props.filteredProgNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'progNoteList'},
(progNote.get('units').map (unit) =>
unitId = unit.get 'id'
# TODO: Make these into components
(switch unit.get('type')
when 'basic'
if unit.get('notes')
R.div({
className: [
'basic unit'
"unitId-#{unitId}"
'isEditing' if isEditing
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
onClick: @_selectBasicUnit.bind null, unit
},
R.h3({}, unit.get('name'))
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: unit.get('notes')
onChange: @props.updateBasicUnitNotes.bind null, unitId
})
else
if unit.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks unit.get('notes')
)
else
renderLineBreaks unit.get('notes')
)
)
(unless unit.get('metrics').isEmpty()
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: isEditing
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
onFocus: @_selectBasicUnit.bind null, unit
onChange: @props.updateBasicMetric.bind null, unitId, metricId
value: metric.get('value')
})
)
)
)
)
when 'plan'
R.div({
className: [
'plan unit'
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
},
(unit.get('sections').map (section) =>
sectionId = section.get('id')
R.section({key: sectionId},
R.h2({}, section.get('name'))
(if section.get('targets').isEmpty()
R.div({className: 'empty'},
"This #{Term 'section'} is empty because
the #{Term 'client'} has no #{Term 'plan targets'}."
)
)
(section.get('targets').map (target) =>
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
targetId = target.get('id')
# Use the up-to-date name & description for header display
mostRecentTargetRevision = planTargetsById.get targetId
R.div({
key: targetId
className: [
'target'
"targetId-#{targetId}"
'isEditing' if isEditing
].join ' '
onClick: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
},
R.h3({}, target.get('name'))
(if isEditing or target.get('notes') isnt ''
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: target.get('notes')
onChange: @props.updatePlanTargetNotes.bind(
null,
unitId, sectionId, targetId
)
})
else
# todo: make this nicer
if target.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks target.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks target.get('notes')
)
)
)
(unless target.get('metrics').isEmpty()
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
metricId = metric.get('id')
MetricWidget({
isEditable: isEditing
tooltipViewport: '#entriesListView'
onChange: @props.updatePlanTargetMetric.bind(
null,
unitId, sectionId, targetId, metricId
)
onFocus: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
)
)
)
)
)
)
)
)
)
(if progNote.get('summary')
R.div({
className: [
'basic unit'
showWhen dataTypeFilter isnt 'events'
].join ' '
},
R.h3({}, "Shift Summary")
(if isEditing
ExpandingTextArea({
value: progNote.get('summary')
onChange: @props.updateShiftSummary
})
else
R.div({className: 'notes'},
renderLineBreaks progNote.get('summary')
)
)
)
)
(unless progEvents.isEmpty()
R.div({
className: [
'progEvents'
showWhen not dataTypeFilter or (dataTypeFilter isnt 'targets') or isEditing
].join ' '
},
# Don't need to show the Events header when we're only looking at events
(if dataTypeFilter isnt 'events' or isEditing
R.h3({}, Term 'Events')
)
(progEvents.map (progEvent, index) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'large'
progEvent
eventTypes: @props.eventTypes
isEditing
updateProgEvent: @props.updateProgEvent.bind null, index
})
)
)
)
)
)
_selectBasicUnit: (unit) ->
@props.setSelectedItem Imm.fromJS {
type: 'basicUnit'
unitId: unit.get('id')
unitName: unit.get('name')
progNoteId: @props.progNote.get('id')
}
_selectPlanSectionTarget: (unit, section, mostRecentTargetRevision) ->
@props.setSelectedItem Imm.fromJS {
type: 'planSectionTarget'
unitId: unit.get('id')
sectionId: section.get('id')
targetId: mostRecentTargetRevision.get('id')
targetName: mostRecentTargetRevision.get('name')
targetDescription: mostRecentTargetRevision.get('description')
progNoteId: @props.progNote.get('id')
}
CancelledProgNoteView = React.createFactory React.createClass
displayName: 'CancelledProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isExpanded: false
}
render: ->
# Here, we assume that the latest revision was the one that
# changed the status. This assumption may become invalid
# when full prognote editing becomes supported.
latestRev = @props.progNoteHistory.last()
firstRev = @props.progNoteHistory.first()
statusChangeRev = latestRev
return R.div({
id: "entry-#{firstRev.get('id')}"
className: 'entry cancelStub'
},
R.button({
className: 'toggleDetails btn btn-xs btn-default'
onClick: @_toggleDetails
},
R.span({className: "#{showWhen not @state.isExpanded}"},
FaIcon 'chevron-down'
" Show details"
)
R.span({className: "#{showWhen @state.isExpanded}"},
FaIcon 'chevron-up'
" Hide details"
)
)
R.h3({},
"Discarded: "
formatTimestamp(firstRev.get('backdate') or firstRev.get('timestamp'))
" (late entry)" if firstRev.get('backdate')
),
R.div({className: "details #{showWhen @state.isExpanded}"},
R.h4({},
"Discarded by "
statusChangeRev.get('author')
" on "
formatTimestamp statusChangeRev.get('timestamp')
),
R.h4({}, "Reason for discarding:")
R.div({className: 'reason'},
renderLineBreaks latestRev.get('statusReason')
)
switch latestRev.get('type')
when 'basic'
QuickNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
userProgram: @props.userProgram
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
filteredProgNote: @props.filteredProgNote
dataTypeFilter: @props.dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
eventTypes: @props.eventTypes
userProgram: @props.userProgram
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
)
)
_toggleDetails: (event) ->
@setState (s) -> {isExpanded: not s.isExpanded}
EntryHeader = React.createFactory React.createClass
displayName: 'EntryHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
render: ->
{
userProgram
revisionHistory
isEditing
isReadOnly
progNote
filteredProgNote
progNoteHistory
progEvents
globalEvents
clientFile
startRevisingProgNote
selectProgNote
} = @props
userIsAuthor = progNote? and (progNote.get('author') is global.ActiveSession.userName)
canViewOptions = progNote? and not isEditing
canModify = userIsAuthor and not isReadOnly
hasRevisions = revisionHistory.size > 1
numberOfRevisions = revisionHistory.size - 1
hasMultipleRevisions = numberOfRevisions > 1
firstRevision = revisionHistory.first() # Use original revision's data
timestamp = (
firstRevision.get('startTimestamp') or
firstRevision.get('backdate') or
firstRevision.get('timestamp')
)
R.div({className: 'entryHeader'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp, @props.dateFormat)
(if firstRevision.get('backdate')
R.span({className: 'lateTimestamp'},
"(late entry)"
)
)
)
(if progNote? and hasRevisions
R.div({className: 'revisions'},
R.a({
className: 'selectProgNoteButton'
onClick: selectProgNote.bind null, progNote
},
"#{numberOfRevisions} revision#{if hasMultipleRevisions then 's' else ''}"
)
)
)
R.div({className: 'author'},
'by '
firstRevision.get('authorDisplayName') or firstRevision.get('author')
(if userProgram and not userProgram.isEmpty()
ColorKeyBubble({
colorKeyHex: userProgram.get('colorKeyHex')
popover: {
title: userProgram.get('name')
content: userProgram.get('description')
placement: 'left'
}
})
)
)
(if canViewOptions
R.div({className: 'options'},
B.DropdownButton({
id: "entryHeaderDropdown-#{progNote.get('id')}"
className: 'entryHeaderDropdown'
pullRight: true
noCaret: true
title: FaIcon('ellipsis-v', {className:'menuItemIcon'})
},
(if canModify
B.MenuItem({onClick: startRevisingProgNote.bind null, progNote, progEvents},
"Edit"
)
)
B.MenuItem({onClick: @_print.bind null, filteredProgNote or progNote, progEvents, clientFile},
"Print"
)
(if canModify
B.MenuItem({onClick: @_openCancelProgNoteDialog},
OpenDialogLink({
ref: 'cancelButton'
className: 'cancelNote'
dialog: CancelProgNoteDialog
progNote
progEvents
globalEvents
}, "Discard")
)
)
)
)
)
)
_openCancelProgNoteDialog: (event) ->
@refs.cancelButton.open(event)
_print: (progNote, progEvents, clientFile) ->
openWindow {
page: 'printPreview'
dataSet: JSON.stringify([
{
format: 'progNote'
data: progNote
progEvents
clientFile
}
])
}
GlobalEventView = React.createFactory React.createClass
displayName: 'GlobalEventView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{globalEvent} = @props
eventType = @props.eventTypes.find (eventType) ->
eventType.get('id') is globalEvent.get('typeId')
eventTypeName = if eventType then eventType.get('name') else null
programId = globalEvent.get('programId')
program = @props.programsById.get(programId) or Imm.Map()
timestamp = globalEvent.get('backdate') or globalEvent.get('timestamp')
startTimestamp = makeMoment globalEvent.get('startTimestamp')
endTimestamp = makeMoment globalEvent.get('endTimestamp')
# A full day is 12:00AM to 11:59PM
isFullDay = (
startTimestamp.isSame(startTimestamp.startOf 'day') and
endTimestamp.isSame(endTimestamp.endOf 'day')
)
return R.div({
id: "entry-#{globalEvent.get('id')}"
className: 'entry globalEventView'
},
EntryHeader({
revisionHistory: Imm.List [globalEvent]
userProgram: program
dateFormat: Config.dateFormat if isFullDay
})
R.h3({},
FaIcon('globe')
"Global Event: "
globalEvent.get('title') or eventTypeName or (
if globalEvent.get('description').length > 20
globalEvent.get('description').substring(0, 20) + "..."
else
globalEvent.get('description')
)
)
(if globalEvent.get('title') or eventTypeName and globalEvent.get('description')
R.p({}, globalEvent.get('description'))
)
(if globalEvent.get('endTimestamp') and not isFullDay
R.p({},
"From: "
formatTimestamp globalEvent.get('startTimestamp')
" until "
formatTimestamp globalEvent.get('endTimestamp')
)
)
R.p({},
"Reported: "
formatTimestamp timestamp
)
)
# Applies selected styles without having to re-render entire EntriesListView tree
InlineSelectedItemStyles = ({selectedItem}) ->
R.style({},
(switch selectedItem.get('type')
when 'planSectionTarget' # Target entry history
"""
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 6px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) h3 {
opacity: 1 !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) .notes {
opacity: 1 !important;
}
"""
when 'quickNote' # QuickNote entry history
"""
div.basic.progNote:not(.isEditing) .notes > div {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'basicUnit' # General 'Notes' entry history (TODO: what > 1 basic unit?)
"""
div.basic.unit.unitId-#{selectedItem.get('unitId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'progNote' # ProgNote revisions
"""
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions {
border-left: 2px solid #3176aa !important;
}
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions a {
color: #3176aa !important;
opacity: 1 !important;
}
"""
else
throw new Error "Unknown selectedItem type #{selectedItem.get('type')} for InlineSelectedItemStyles"
)
)
filterEmptyProgNoteValues = (progNote) ->
# Don't bother filtering a quickNote (doesn't have units)
unless progNote.has 'units'
return progNote
progNoteUnits = progNote.get('units')
.map (unit) ->
if unit.get('type') is 'basic'
# Strip empty metric values
unitMetrics = unit.get('metrics').filterNot (metric) -> not metric.get('value')
return unit.set('metrics', unitMetrics)
else if unit.get('type') is 'plan'
unitSections = unit.get('sections')
.map (section) ->
sectionTargets = section.get('targets')
# Strip empty metric values
.map (target) ->
targetMetrics = target.get('metrics').filterNot (metric) -> not metric.get('value')
return target
.set('metrics', targetMetrics)
.remove('description') # We don't need target description snapshot displayed/searched
# Strip empty targets
.filterNot (target) ->
not target.get('notes') and target.get('metrics').isEmpty()
return section.set('targets', sectionTargets)
.filterNot (section) ->
section.get('targets').isEmpty()
return unit.set('sections', unitSections)
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
.filterNot (unit) ->
# Finally, strip any empty 'basic' units, or 'plan' units with 0 sections
if unit.get('type') is 'basic'
return not unit.get('notes') and unit.get('metrics').isEmpty()
else if unit.get('type') is 'plan'
return unit.get('sections').isEmpty()
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
return progNote.set('units', progNoteUnits)
return ProgNotesTab
module.exports = {load}
| 207537 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Client file view for displaying, searching, and updating progress notes
Fs = require 'fs'
Path = require 'path'
Assert = require 'assert'
Imm = require 'immutable'
Moment = require 'moment'
Async = require 'async'
_ = require 'underscore'
Config = require '../config'
Term = require '../term'
Persist = require '../persist'
dataTypeOptions = Imm.fromJS [
# {name: 'Progress Notes', id: 'progNotes'}
# {name: 'Targets', id: 'targets'}
{name: 'Events', id: 'events'}
]
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
ReactDOMServer = win.ReactDOMServer
Mark = win.Mark
B = require('../utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
CancelProgNoteDialog = require('./cancelProgNoteDialog').load(win)
ColorKeyBubble = require('../colorKeyBubble').load(win)
CrashHandler = require('../crashHandler').load(win)
ExpandingTextArea = require('../expandingTextArea').load(win)
MetricWidget = require('../metricWidget').load(win)
ProgEventWidget = require('../progEventWidget').load(win)
OpenDialogLink = require('../openDialogLink').load(win)
ProgNoteDetailView = require('../progNoteDetailView').load(win)
EntryDateNavigator = require('./entryDateNavigator').load(win)
FilterBar = require('./filterBar').load(win)
{
FaIcon, openWindow, renderLineBreaks, showWhen, formatTimestamp, renderName, makeMoment
getUnitIndex, getPlanSectionIndex, getPlanTargetIndex, blockedExtensions, stripMetadata, scrollToElement
} = require('../utils').load(win)
# List of fields we exclude from keyword search
excludedSearchFields = Imm.fromJS [
'id', 'revisionId', 'templateId', 'typeId', 'relatedProgNoteId', 'programId'
'relatedProgEventId', 'authorProgramId', 'clientFileId'
'timestamp', 'backdate', 'startTimestamp', 'endTimestamp'
'type', 'entryType', 'status', 'definition'
# 'filteredProgNote' and {entryType: globalEvent} used instead
'progNoteHistory', 'globalEvents'
]
ProgNotesTab = React.createFactory React.createClass
displayName: 'ProgNotesTab'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
hasChanges: ->
@refs.ui.hasChanges()
_toProgNoteHistoryEntry: (progNoteHistory) ->
latestRevision = progNoteHistory.last()
firstRevision = progNoteHistory.first()
# We pass down a pre-filtered version of the progNote
# because the search-by-keyword feature relies on this data
filteredProgNote = filterEmptyProgNoteValues(latestRevision)
# Revisions all have same 'id', just different revisionIds
progNoteId = firstRevision.get('id')
programId = firstRevision.get('authorProgramId')
timestamp = latestRevision.get('backdate') or firstRevision.get('timestamp')
# Mix in all other related data from clientFile's other collections
progEvents = @props.progEvents.filter (progEvent) ->
return progEvent.get('relatedProgNoteId') is progNoteId
# progNote still gets any cancelled globalEvents
globalEvents = @props.globalEvents.filter (globalEvent) ->
return globalEvent.get('relatedProgNoteId') is progNoteId
attachments = @props.attachmentsByProgNoteId.get(progNoteId) or Imm.List()
return Imm.Map {
entryType: 'progNote'
id: progNoteId
programId
timestamp
progNoteHistory
filteredProgNote
progEvents
globalEvents
attachments
}
_toGlobalEventEntry: (globalEvent) ->
timestamp = globalEvent.get('startTimestamp') # Order by startTimestamp
return Imm.Map {
entryType: 'globalEvent'
id: globalEvent.get('id')
programId: globalEvent.get('programId')
timestamp
globalEvent
}
render: ->
progNoteEntries = @props.progNoteHistories.map @_toProgNoteHistoryEntry
globalEventEntries = @props.globalEvents
.filter (e) -> e.get('status') is 'default'
.map @_toGlobalEventEntry
historyEntries = progNoteEntries
.concat globalEventEntries
.sortBy (entry) -> entry.get('timestamp')
.reverse()
props = _.extend {}, @props, {
ref: 'ui'
historyEntries
}
return ProgNotesTabUi(props)
ProgNotesTabUi = React.createFactory React.createClass
displayName: 'ProgNotesTabUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
editingProgNoteId: null
attachment: null
selectedItem: null
backdate: ''
transientData: null
isLoading: null
isFiltering: null
showHistory: true
searchQuery: ''
programIdFilter: null
dataTypeFilter: null
}
hasChanges: ->
@_transientDataHasChanges()
render: ->
{transientData} = @state
hasChanges = @hasChanges()
hasEnoughData = @props.historyEntries.size > 0
isEditing = transientData?
# Only show the single progNote while editing
historyEntries = if not isEditing then @props.historyEntries else Imm.List [
@props.historyEntries.find (entry) ->
entry.get('id') is transientData.getIn(['progNote', 'id'])
]
####### Filtering / Search Logic #######
if @state.isFiltering
# TODO: Make this filtering faster
# By program?
if @state.programIdFilter
historyEntries = historyEntries.filter (e) => e.get('programId') is @state.programIdFilter
# By type of progNote?
if @state.dataTypeFilter in ['progNotes', 'targets']
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'progNote'
# by event without a query (suppress notes)
if @state.dataTypeFilter is 'events'
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'globalEvent' or not e.get('progEvents').isEmpty()
# When searching 'targets', only check 'full' progNotes
# TODO: Restore this dataType at some point
# if @state.dataTypeFilter is 'targets'
# historyEntries = historyEntries.filter (e) => e.getIn(['filteredProgNote', 'type']) is 'full'
# By search query? Pass dataTypeFilter for conditional property checks
if @state.searchQuery.trim().length > 0
historyEntries = @_filterEntries(historyEntries, @state.dataTypeFilter)
return R.div({className: 'progNotesView'},
R.div({className: 'panes'},
R.section({className: 'leftPane'},
# TODO: Make component
R.div({className: 'flexButtonToolbar'},
R.button({
className: [
'saveButton'
'collapsed' unless isEditing
].join ' '
onClick: @_saveTransientData
disabled: not hasChanges
},
FaIcon('save')
R.span({className: 'wideMenuItemText'},
"Save #{Term 'Progress Note'}"
)
)
R.button({
className: [
'discardButton'
'collapsed' unless isEditing
].join ' '
onClick: @_cancelRevisingProgNote
},
FaIcon('undo')
R.span({className: 'wideMenuItemText'},
"Discard"
)
)
R.button({
className: [
'newProgNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewProgNote
disabled: @state.isLoading or @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Progress Note'}"
)
)
R.button({
ref: 'addQuickNoteButton'
className: [
'addQuickNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewQuickNote
disabled: @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Quick Note'}"
)
)
R.button({
ref: 'openFilterBarButton'
className: [
'openFilterBarButton'
'collapsed' if isEditing or @state.isFiltering
showWhen hasEnoughData
].join ' '
onClick: @_toggleIsFiltering
},
FaIcon('search')
)
R.button({
ref: 'toggleHistoryPane'
className: [
'toggleHistoryPaneButton'
].join ' '
onClick: @_toggleHistoryPane
},
(if @state.showHistory
FaIcon('angle-right')
else
FaIcon('angle-left')
)
)
)
(unless hasEnoughData
R.div({className: 'empty'},
R.div({className: 'message'},
"This #{Term 'client'} does not currently have any #{Term 'progress notes'}."
)
)
)
(if @state.isFiltering and not isEditing
FilterBar({
ref: 'filterBar'
historyEntries
programIdFilter: @state.programIdFilter
dataTypeFilter: @state.dataTypeFilter
programsById: @props.programsById
dataTypeOptions
onClose: @_toggleIsFiltering
onUpdateSearchQuery: @_updateSearchQuery
onSelectProgramId: @_updateProgramIdFilter
onSelectDataType: @_updateDataTypeFilter
})
)
# TODO: Make component
R.div({
className: [
'empty'
showWhen @state.isFiltering and historyEntries.isEmpty()
].join ' '
},
R.div({className: 'message animated fadeIn'},
R.div({},
"No results found"
(if @state.dataTypeFilter
R.span({},
" in "
R.strong({},
dataTypeOptions.find((t) => t.get('id') is @state.dataTypeFilter).get('name')
)
)
)
)
(if @state.searchQuery.trim().length > 0
R.div({},
"matching: \""
R.strong({}, @state.searchQuery)
"\""
)
)
(if @state.programIdFilter
R.div({},
"for: "
R.strong({},
@props.programsById.getIn [@state.programIdFilter, 'name']
)
ColorKeyBubble({
colorKeyHex: @props.programsById.getIn [@state.programIdFilter, 'colorKeyHex']
})
)
)
R.div({},
R.button({
id: 'resetFilterButton'
className: 'btn btn-link'
onClick: => @refs.filterBar.clear()
},
FaIcon('refresh')
"Reset"
)
)
)
)
# Apply selectedItem styles as inline <style>
(if @state.selectedItem?
InlineSelectedItemStyles({
selectedItem: @state.selectedItem
})
)
EntriesListView({
ref: 'entriesListView'
historyEntries
entryIds: historyEntries.map (e) -> e.get('id')
transientData
eventTypes: @props.eventTypes
clientFile: @props.clientFile
programsById: @props.programsById
planTargetsById: @props.planTargetsById
dataTypeFilter: @state.dataTypeFilter
searchQuery: @state.searchQuery
programIdFilter: @state.programIdFilter
isFiltering: @state.isFiltering
isReadOnly: @props.isReadOnly
isEditing
setSelectedItem: @_setSelectedItem
selectProgNote: @_selectProgNote
startRevisingProgNote: @_startRevisingProgNote
cancelRevisingProgNote: @_cancelRevisingProgNote
updatePlanTargetNotes: @_updatePlanTargetNotes
updateBasicUnitNotes: @_updateBasicUnitNotes
updateBasicMetric: @_updateBasicMetric
updatePlanTargetMetric: @_updatePlanTargetMetric
updateProgEvent: @_updateProgEvent
updateQuickNotes: @_updateQuickNotes
updateShiftSummary: @_updateShiftSummary
})
)
R.section({
className: [
'rightPane'
'collapsed' unless @state.showHistory
].join ' '
},
ProgNoteDetailView({
ref: 'progNoteDetailView'
isFiltering: @state.isFiltering
searchQuery: @state.searchQuery
item: @state.selectedItem
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
metricsById: @props.metricsById
programsById: @props.programsById
})
)
)
)
_startRevisingProgNote: (progNote, progEvents) ->
# Include transient and original data into generic store
transientData = Imm.fromJS {
progNote
originalProgNote: progNote
progEvents
originalProgEvents: progEvents
# TODO: Allow editing for globalEvents as well
}
@setState {transientData}
_cancelRevisingProgNote: ->
if @_transientDataHasChanges()
return Bootbox.confirm "Discard all changes made to the #{Term 'progress note'}?", (ok) =>
if ok then @_discardTransientData()
@_discardTransientData()
_discardTransientData: ->
@setState {transientData: null}
_transientDataHasChanges: ->
transientData = @state.transientData
return null unless transientData?
originalProgNote = transientData.get('originalProgNote')
progNote = transientData.get('progNote')
progNoteHasChanges = not Imm.is progNote, originalProgNote
originalProgEvents = transientData.get('originalProgEvents')
progEvents = transientData.get('progEvents')
progEventsHasChanges = not Imm.is progEvents, originalProgEvents
# TODO: Compare globalEvents
return progNoteHasChanges or progEventsHasChanges
_updateBasicUnitNotes: (unitId, event) ->
newNotes = event.target.value
transientData = @state.transientData
unitIndex = getUnitIndex transientData.get('progNote'), unitId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'notes'
]
newNotes
)
}
_updatePlanTargetNotes: (unitId, sectionId, targetId, event) ->
newNotes = event.target.value
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'notes'
]
newNotes
)
}
_updateQuickNotes: (event) ->
newNotes = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'notes'], newNotes
}
_updateShiftSummary: (event) ->
newSummary = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'summary'], newSummary
}
_updateProgEvent: (index, updatedProgEvent) ->
transientData = @state.transientData.setIn ['progEvents', index], updatedProgEvent
@setState {transientData}
_isValidMetric: (value) -> value.match /^-?\d*\.?\d*$/
_updatePlanTargetMetric: (unitId, sectionId, targetId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
metricIndex = progNote.getIn(
[
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex,
'metrics'
]
).findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_updateBasicMetric: (unitId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
metricIndex = progNote.getIn ['units', unitIndex, 'metrics']
.findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_saveTransientData: ->
{progNote, progEvents, originalProgNote, originalProgEvents} = @state.transientData.toObject()
# Any progEvents modified?
revisedProgEvents = progEvents.filter (progEvent, index) ->
not Imm.is progEvent, originalProgEvents.get(index)
# Only save modified progNotes/progEvents
Async.series [
(cb) ->
return cb() if Imm.is originalProgNote, progNote
ActiveSession.persist.progNotes.createRevision progNote, cb
(cb) ->
return cb() if revisedProgEvents.isEmpty()
Async.map revisedProgEvents, ActiveSession.persist.progEvents.createRevision, cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
@_discardTransientData()
_checkUserProgram: (cb) ->
# Skip if no clientProgram(s)
if @props.clientPrograms.isEmpty()
cb()
return
userProgramId = global.ActiveSession.programId
# Skip if userProgram matches one of the clientPrograms
matchingUserProgram = @props.clientPrograms.find (program) ->
userProgramId is program.get('id')
if matchingUserProgram
cb()
return
# override by default if client only in a single program
if @props.clientPrograms.size is 1
userProgramId = @props.clientPrograms.first().get('id')
userProgram = @props.programsById.get userProgramId
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
cb()
return
clientName = renderName @props.clientFile.get('clientName')
userProgramName = if userProgramId
@props.programsById.getIn [userProgramId, 'name']
else
"(none)"
# Build programDropdown markup
programDropdown = R.select({
id: 'programDropdown'
className: 'form-control '
},
R.option({value: ''}, "Select a #{Term 'client'} #{Term 'program'}"),
(@props.clientPrograms.map (program) ->
R.option({
key: program.get('id')
value: program.get('id')
},
program.get('name')
)
)
)
focusPopover = ->
setTimeout (=>
$popover = $('.popover textarea')[0]
if $popover? then $popover.focus()
), 500
# Prompt user about temporarily overriding their program
Bootbox.dialog {
title: "Switch to #{Term 'client'} #{Term 'program'}?"
message: R.div({},
"#{clientName} is not enrolled in your assigned #{Term 'program'}: ",
'"', R.b({}, userProgramName), '".',
R.br(), R.br(),
"Override your assigned #{Term 'program'} below, or click \"Ignore\"."
R.br(), R.br(),
programDropdown
)
buttons: {
cancel: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
ignore: {
label: "Ignore"
className: "btn-warning"
callback: ->
focusPopover()
cb()
}
success: {
label: "Override #{Term 'Program'}"
className: "btn-success"
callback: =>
userProgramId = $('#programDropdown').val()
if not userProgramId? or userProgramId.length is 0
Bootbox.alert "No #{Term 'program'} was selected, please try again."
return
userProgram = @props.programsById.get userProgramId
# Override the user's program
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
focusPopover()
cb()
}
}
}
_checkPlanChanges: (cb) ->
# Check for unsaved changes to the client plan
if not @props.hasChanges()
cb()
return
# Prompt user about unsaved changes
Bootbox.dialog {
title: "Unsaved Changes to #{Term 'Plan'}"
message: """
You have unsaved changes in the #{Term 'plan'} that will not be reflected in this
#{Term 'progress note'}. How would you like to proceed?
"""
buttons: {
default: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
danger: {
label: "Ignore"
className: "btn-danger"
callback: -> cb()
}
success: {
label: "View #{Term 'Plan'}"
className: "btn-success"
callback: =>
Bootbox.hideAll()
@props.onTabChange 'plan'
return
}
}
}
_openNewProgNote: ->
Async.series [
@_checkPlanChanges
@_checkUserProgram
(cb) =>
@setState {isLoading: true}
# Cache data to global, so can access again from newProgNote window
# Set up the dataStore if doesn't exist
# Store property as clientFile ID to prevent confusion
global.dataStore ?= {}
# Only needs to pass latest revisions of each planTarget
# In this case, index [0] is the latest revision
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
global.dataStore[@props.clientFileId] = {
clientFile: @props.clientFile
planTargetsById
metricsById: @props.metricsById
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
programsById: @props.programsById
clientPrograms: @props.clientPrograms
}
openWindow {page: 'newProgNote', clientFileId: @props.clientFileId}, (newProgNoteWindow) =>
# prevent window from closing before its ready
# todo a more elegant way to do this?
newProgNoteWindow.on 'close', =>
newProgNoteWindow = null
global.ActiveSession.persist.eventBus.once 'newProgNotePage:loaded', cb
], (err) =>
@setState {isLoading: false}
if err
CrashHandler.handle err
return
_openNewQuickNote: ->
Async.series [
@_checkUserProgram
@_toggleQuickNotePopover
], (err) ->
if err
CrashHandler.handle err
return
_attach: ->
# Configures hidden file inputs with custom attributes, and clicks it
$nwbrowse = $('#nwBrowse')
$nwbrowse
.off()
#.attr('accept', ".#{extension}")
.on('change', (event) => @_encodeFile event.target.value)
.click()
_encodeFile: (file) ->
return unless file
# clear input value so onchange can still fire if user tries same file again
$('#nwBrowse').val(null)
filename = Path.basename file
fileExtension = (Path.extname file).toLowerCase()
if blockedExtensions.indexOf(fileExtension) > -1
Bootbox.alert {
title: "Warning: File Blocked"
message: "#{filename} is potentially unsafe and cannot be attached."
}
return
attachment = Fs.readFileSync(file)
filesize = Buffer.byteLength(attachment, 'base64')
if filesize < 1048576
filesize = (filesize / 1024).toFixed() + " KB"
else
filesize = (filesize / 1048576).toFixed() + " MB"
# Convert to base64 encoded string
encodedAttachment = Buffer.from(attachment).toString 'base64'
@setState {
attachment: {
encodedData: encodedAttachment
filename: filename
}
}
# TODO: Append for when multiple attachments allowed (#787)
$('#attachmentArea').html filename + " (" + filesize + ") <i class='fa fa-times' id='removeBtn'></i>"
removeFile = $('#removeBtn')
removeFile.on 'click', (event) =>
$('#attachmentArea').html ''
@setState {attachment: null}
_toggleQuickNotePopover: ->
# TODO: Refactor to stateful React component
quickNoteToggle = $(findDOMNode @refs.addQuickNoteButton)
quickNoteToggle.popover {
placement: 'bottom'
html: true
trigger: 'manual'
content: '''
<textarea class="form-control"></textarea>
<div id="attachmentArea" style="padding-top:10px; color:#3176aa;"></div>
<div class="buttonBar form-inline">
<label>Date: </label> <input type="text" class="form-control backdate date"></input>
<button class="btn btn-default" id="attachBtn"><i class="fa fa-paperclip"></i> Attach</button>
<button class="cancel btn btn-danger"><i class="fa fa-trash"></i> Discard</button>
<button class="save btn btn-primary"><i class="fa fa-check"></i> Save</button>
<input type="file" class="hidden" id="nwBrowse"></input>
</div>
'''
}
if quickNoteToggle.data('isVisible')
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
else
quickNoteToggle.popover('show')
quickNoteToggle.data('isVisible', true)
attachFile = $('#attachBtn')
attachFile.on 'click', (event) =>
@_attach event
attachFile.blur()
popover = quickNoteToggle.siblings('.popover')
popover.find('.save.btn').on 'click', (event) =>
event.preventDefault()
@_createQuickNote popover.find('textarea').val(), @state.backdate, @state.attachment, (err) =>
@setState {
backdate: '',
attachment: null
}
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('.backdate.date').datetimepicker({
format: 'MMM-DD-YYYY h:mm A'
defaultDate: Moment()
maxDate: Moment()
widgetPositioning: {
vertical: 'bottom'
}
}).on 'dp.change', (e) =>
if Moment(e.date).format('YYYY-MM-DD-HH') is Moment().format('YYYY-MM-DD-HH')
@setState {backdate: ''}
else
@setState {backdate: Moment(e.date).format(Persist.TimestampFormat)}
popover.find('.cancel.btn').on 'click', (event) =>
event.preventDefault()
@setState {
backdate: '',
attachment: null
}
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('textarea').focus()
# Store quickNoteBeginTimestamp as class var, since it wont change
@quickNoteBeginTimestamp = Moment().format(Persist.TimestampFormat)
_createQuickNote: (notes, backdate, attachment, cb) ->
unless notes
Bootbox.alert "Cannot create an empty #{Term 'quick note'}."
return
quickNote = Imm.fromJS {
type: 'basic'
status: 'default'
clientFileId: @props.clientFileId
notes
backdate
authorProgramId: global.ActiveSession.programId or ''
beginTimestamp: @quickNoteBeginTimestamp
}
# TODO: Async series
global.ActiveSession.persist.progNotes.create quickNote, (err, result) =>
if err
cb err
return
unless attachment
cb()
return
attachmentData = Imm.fromJS {
status: 'default'
filename: attachment.filename
encodedData: attachment.encodedData
clientFileId: @props.clientFileId
relatedProgNoteId: result.get('id')
}
global.ActiveSession.persist.attachments.create attachmentData, cb
_setSelectedItem: (selectedItem) ->
@setState {selectedItem}
_selectProgNote: (progNote) ->
@_setSelectedItem Imm.fromJS {
type: 'progNote'
progNoteId: progNote.get('id')
}
_filterEntries: (entries, dataTypeFilter) ->
if @state.searchQuery.trim().length is 0
return entries
# Split into query parts
queryParts = Imm.fromJS(@state.searchQuery.split(' ')).map (p) -> p.toLowerCase()
containsSearchQuery = (data) ->
if dataTypeFilter
# Only search through 'progNote' types for progNotes and targets
if dataTypeFilter in ['progNotes', 'targets'] and data.has('entryType') and data.get('entryType') isnt 'progNote'
return false
# For 'targets', favour 'filteredProgNote' with 'type: full' - since it only contains targets with data
# TODO: Restore this dataType at some point
# else if dataTypeFilter is 'targets'
# data = data.get('filteredProgNote') or data
else if dataTypeFilter is 'events'
# Ignore progNote entries without progEvents
if data.has('entryType') and data.get('entryType') isnt 'globalEvent' and data.get('progEvents').isEmpty()
return false
# Favor 'progEvents' in progNote entries
else
data = data.get('progEvents') or data
return data.some (value, property) ->
# Skip excluded field
if excludedSearchFields.includes property
return false
# Run all keywords against string contents
if typeof value is 'string'
value = value.toLowerCase()
includesAllParts = queryParts.every (part) -> value.includes(part)
# if includesAllParts then console.log "Match:", "#{property}:", value
return includesAllParts
# When not a string, it must be an Imm.List / Map
# so we'll loop through this same method on it
return containsSearchQuery(value)
# Only keep entries that contain all query parts
return entries.filter containsSearchQuery
_updateSearchQuery: (searchQuery) ->
@setState {searchQuery}
_toggleIsFiltering: ->
isFiltering = not @state.isFiltering
# Clear filter values when toggling off filterBar
if not isFiltering
@setState {
isFiltering
searchQuery: ''
dataTypeFilter: null
programIdFilter: null
}
return
@setState {isFiltering}
_toggleHistoryPane: ->
showHistory = not @state.showHistory
@setState {showHistory}
_updateProgramIdFilter: (programIdFilter) ->
@setState {programIdFilter}
_updateDataTypeFilter: (dataTypeFilter) ->
@setState {dataTypeFilter}
EntriesListView = React.createFactory React.createClass
displayName: 'EntriesListView'
mixins: [React.addons.PureRenderMixin]
getInitialState: -> {
historyCount: 10
filterCount: 10
}
componentDidMount: ->
# Watch scroll for infinite scroll behaviour, throttle to 1call/per/150ms
@_watchUnlimitedScroll = _.throttle(@_watchUnlimitedScroll, 150)
@entriesListView = $(findDOMNode @)
@entriesListView.on 'scroll', @_watchUnlimitedScroll
# Custom positioning logic to have EntryDateNavigator hug this.bottom-right
@entryDateNavigator = $(findDOMNode @refs.entryDateNavigator)
# Set initial position, and listen for window resize
@rightPane = $('.rightPane')[1] #todo: clunky... Ref not available here, maybe get from this upstream?
@_setNavigatorRightOffset()
$(win).on 'resize', @_setNavigatorRightOffset
componentDidUpdate: (oldProps, oldState) ->
# Update highlighting when anything changes while searching
# TODO: Maybe wrap component with this logic; allow state to change unimpeded
if @props.isFiltering
filterParametersChanged = (
@props.searchQuery isnt oldProps.searchQuery or
@props.dataTypeFilter isnt oldProps.dataTypeFilter or
@props.programIdFilter isnt oldProps.programIdFilter
)
# Reset filterCount and scroll to top anytime filter parameters change
if filterParametersChanged
@setState @getInitialState, @_resetScroll
if @props.searchQuery
if @state.filterCount > oldState.filterCount
# Only highlight new entries added from unlimited-scroll
newEntriesCount = @state.filterCount - oldState.filterCount
entryNodes = @props.entryIds
.slice 0, @state.filterCount
.takeLast newEntriesCount
.map (id) -> win.document.getElementById(id)
.toArray()
new Mark(entryNodes).mark(@props.searchQuery)
else
@_redrawSearchHighlighting()
# Toggle FilterBar, resets selectedItem
if @props.isFiltering isnt oldProps.isFiltering
if @props.isFiltering
# Reset filterCount when FilterBar opens
@setState {filterCount: 10}
else
# Clear search highlighting when FilterBar closes
@_redrawSearchHighlighting()
@props.setSelectedItem(null)
# Reset scroll when opens edit view for progNote
if @props.isEditing isnt oldProps.isEditing and @props.isEditing
@_resetScroll()
componentWillUnmount: ->
@entriesListView.off 'scroll', @_watchUnlimitedScroll
$(win.document).off 'resize', @_setNavigatorRightOffset
_watchUnlimitedScroll: ->
# Skip if we're scrolling via EntryDateNavigator, entry count is already set
return if @isAutoScrolling
# Detect if we've reached the lower threshold to trigger update
if @entriesListView.scrollTop() + (@entriesListView.innerHeight() *2) >= @entriesListView[0].scrollHeight
# Count is contextual to complete history, or filtered entries
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
# Disregard if nothing left to load into the count
return if @state[countType] >= @props.historyEntries.size
# Update UI with +10 to entry count
nextState = {}
nextState[countType] = @state[countType] + 10
@setState(nextState)
_setNavigatorRightOffset: ->
# Add rightPane's width to navigator's initial (css) right positioning
# TODO: Can we use new chrome 'sticky' instead? Sometimes doesn't show on HCR
right = if @rightPane? then @rightPane.offsetWidth else 0
@entryDateNavigator.css {right}
_scrollToEntryDate: (date, cb=(->)) ->
# TODO: Have moment objs already pre-built in historyEntries
entry = @props.historyEntries.find (e) ->
timestamp = makeMoment e.get('timestamp')
return date.isSame timestamp, 'day'
if not entry?
console.warn "Cancelled scroll, could not find #{date.toDate()} in historyEntries"
cb()
return
# Should we supplement filter/historyCount first?
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
index = @props.historyEntries.indexOf entry
requiresMoreEntries = @state[countType] - 1 < index
Async.series [
(cb) =>
return cb() unless requiresMoreEntries
# Provide 10 extra entries, so destinationEntry appears at top
# Set the new count (whichever type is pertinent), and *then* scroll to the entry
newState = {}
newState[countType] = (index + 1) + 10
@setState newState, cb
(cb) =>
# Scroll to latest entry matching date
$entriesListView = findDOMNode(@)
$element = win.document.getElementById "entry-#{entry.get('id')}"
@isAutoScrolling = true # Temporarily block scroll listener(s)
scrollToElement $entriesListView, $element, 1000, 'easeInOutQuad', cb
(cb) =>
@isAutoScrolling = false
# Scroll is completed, briefly highlight/animate any entries with matching date
selectedMoment = makeMoment entry.get('timestamp')
entryIdsToFlash = @props.historyEntries
.filter (e) ->
timestamp = makeMoment e.get('timestamp')
return selectedMoment.isSame makeMoment(timestamp), 'day'
.map (e) -> '#entry-' + e.get('id')
.toArray()
.join ', '
$(entryIdsToFlash).addClass 'flashDestination'
setTimeout(->
$(entryIdsToFlash).removeClass 'flashDestination'
, 2500)
cb()
], cb
_resetScroll: ->
findDOMNode(@).scrollTop = 0
_redrawSearchHighlighting: ->
# Performs a complete (expensive) mark/unmark of the entire EntriesListView
entriesHighlighting = new Mark findDOMNode @refs.entriesListView
if @props.isFiltering
entriesHighlighting.unmark().mark(@props.searchQuery)
else
entriesHighlighting.unmark()
render: ->
{historyEntries, isFiltering} = @props
# Limit number of entries by filter/historyCount
sliceCount = if isFiltering then @state.filterCount else @state.historyCount
slicedHistoryEntries = historyEntries.slice 0, sliceCount
R.div({
ref: 'entriesListView'
id: 'entriesListView'
className: showWhen not slicedHistoryEntries.isEmpty()
},
EntryDateNavigator({
ref: 'entryDateNavigator'
historyEntries: @props.historyEntries
onSelect: @_scrollToEntryDate
})
(slicedHistoryEntries.map (entry) =>
switch entry.get('entryType')
when 'progNote'
# Combine entry with @props + key
ProgNoteContainer(_.extend entry.toObject(), @props, {
key: entry.get('id')
})
when 'globalEvent'
GlobalEventView({
key: entry.get('id')
globalEvent: entry.get('globalEvent')
programsById: @props.programsById
eventTypes: @props.eventTypes
})
else
throw new Error "Unknown historyEntries entryType: \"#{entry.get('entryType')}\""
)
)
ProgNoteContainer = React.createFactory React.createClass
displayName: 'ProgNoteContainer'
mixins: [React.addons.PureRenderMixin]
render: ->
{isEditing, filteredProgNote, progEvents, globalEvents, dataTypeFilter} = @props
progNote = @props.progNoteHistory.last()
progNoteId = progNote.get('id')
firstProgNoteRev = @props.progNoteHistory.first()
userProgramId = firstProgNoteRev.get('authorProgramId')
userProgram = @props.programsById.get(userProgramId) or Imm.Map()
# TODO: Refactor to extended props
if progNote.get('status') is 'cancelled'
return CancelledProgNoteView({
progNoteHistory: @props.progNoteHistory
filteredProgNote
dataTypeFilter
attachments: @props.attachments
progEvents
globalEvents
eventTypes: @props.eventTypes
clientFile: @props.clientFile
userProgram
planTargetsById: @props.planTargetsById
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updatePlanTargetNotes: @props.updatePlanTargetNotes
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
Assert.equal progNote.get('status'), 'default'
switch progNote.get('type')
when 'basic'
QuickNoteView({
progNote
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
userProgram
clientFile: @props.clientFile
dataTypeFilter
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
progNote
filteredProgNote
dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents
globalEvents
userProgram
planTargetsById: @props.planTargetsById
eventTypes: @props.eventTypes
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
setEditingProgNoteId: @props.setEditingProgNoteId
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updateBasicMetric: @props.updateBasicMetric
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
QuickNoteView = React.createFactory React.createClass
displayName: 'QuickNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Don't render anything if only events are shown
if dataTypeFilter is 'events' and not isEditing
return null
progNote = if isEditing then @props.transientData.get('progNote') else @props.progNote
if @props.attachments?
attachmentText = " " + @props.attachments.get('filename')
R.div({
id: "entry-#{progNote.get('id')}"
className: [
'entry basic progNote'
'isEditing' if isEditing
].join ' '
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'notes'},
R.div({onClick: @_selectQuickNote},
(if isEditing
ExpandingTextArea({
value: progNote.get('notes')
onChange: @props.updateQuickNotes
})
else
renderLineBreaks progNote.get('notes')
)
)
(@props.attachments.map (attachment) =>
{id, filename} = attachment.toObject()
fileExtension = Path.extname filename
R.a({
key: id
className: 'attachment'
onClick: @_openAttachment.bind null, attachment
},
FaIcon(fileExtension)
' '
filename
)
)
)
)
_openAttachment: (attachment) ->
attachmentId = attachment.get('id')
clientFileId = @props.clientFile.get('id')
global.ActiveSession.persist.attachments.readLatestRevisions clientFileId, attachmentId, 1, (err, results) ->
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
attachment = results.first()
encodedData = attachment.get('encodedData')
filename = attachment.get('filename')
if filename?
# Absolute path required for windows
filepath = Path.join process.cwd(), Config.backend.dataDirectory, '_tmp', filename
file = Buffer.from(encodedData, 'base64')
# TODO cleanup file...
Fs.writeFile filepath, file, (err) ->
if err
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
nw.Shell.openItem filepath
_selectQuickNote: ->
@props.setSelectedItem Imm.fromJS {
type: 'quickNote'
progNoteId: @props.progNote.get('id')
}
ProgNoteView = React.createFactory React.createClass
displayName: 'ProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Use transient data when isEditing
progNote = if isEditing then @props.transientData.get('progNote') else @props.filteredProgNote
progEvents = if isEditing then @props.transientData.get('progEvents') else @props.progEvents
R.div({
id: "entry-#{progNote.get('id')}"
className: 'entry full progNote'
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
filteredProgNote: @props.filteredProgNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'progNoteList'},
(progNote.get('units').map (unit) =>
unitId = unit.get 'id'
# TODO: Make these into components
(switch unit.get('type')
when 'basic'
if unit.get('notes')
R.div({
className: [
'basic unit'
"unitId-#{unitId}"
'isEditing' if isEditing
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
onClick: @_selectBasicUnit.bind null, unit
},
R.h3({}, unit.get('name'))
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: unit.get('notes')
onChange: @props.updateBasicUnitNotes.bind null, unitId
})
else
if unit.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks unit.get('notes')
)
else
renderLineBreaks unit.get('notes')
)
)
(unless unit.get('metrics').isEmpty()
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: isEditing
key: metric.<KEY>('id')
name: metric.get('name')
definition: metric.get('definition')
onFocus: @_selectBasicUnit.bind null, unit
onChange: @props.updateBasicMetric.bind null, unitId, metricId
value: metric.get('value')
})
)
)
)
)
when 'plan'
R.div({
className: [
'plan unit'
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
},
(unit.get('sections').map (section) =>
sectionId = section.get('id')
R.section({key: sectionId},
R.h2({}, section.get('name'))
(if section.get('targets').isEmpty()
R.div({className: 'empty'},
"This #{Term 'section'} is empty because
the #{Term 'client'} has no #{Term 'plan targets'}."
)
)
(section.get('targets').map (target) =>
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
targetId = target.get('id')
# Use the up-to-date name & description for header display
mostRecentTargetRevision = planTargetsById.get targetId
R.div({
key: targetId
className: [
'target'
"targetId-#{targetId}"
'isEditing' if isEditing
].join ' '
onClick: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
},
R.h3({}, target.get('name'))
(if isEditing or target.get('notes') isnt ''
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: target.get('notes')
onChange: @props.updatePlanTargetNotes.bind(
null,
unitId, sectionId, targetId
)
})
else
# todo: make this nicer
if target.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks target.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks target.get('notes')
)
)
)
(unless target.get('metrics').isEmpty()
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
metricId = metric.get('id')
MetricWidget({
isEditable: isEditing
tooltipViewport: '#entriesListView'
onChange: @props.updatePlanTargetMetric.bind(
null,
unitId, sectionId, targetId, metricId
)
onFocus: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
)
)
)
)
)
)
)
)
)
(if progNote.get('summary')
R.div({
className: [
'basic unit'
showWhen dataTypeFilter isnt 'events'
].join ' '
},
R.h3({}, "Shift Summary")
(if isEditing
ExpandingTextArea({
value: progNote.get('summary')
onChange: @props.updateShiftSummary
})
else
R.div({className: 'notes'},
renderLineBreaks progNote.get('summary')
)
)
)
)
(unless progEvents.isEmpty()
R.div({
className: [
'progEvents'
showWhen not dataTypeFilter or (dataTypeFilter isnt 'targets') or isEditing
].join ' '
},
# Don't need to show the Events header when we're only looking at events
(if dataTypeFilter isnt 'events' or isEditing
R.h3({}, Term 'Events')
)
(progEvents.map (progEvent, index) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'large'
progEvent
eventTypes: @props.eventTypes
isEditing
updateProgEvent: @props.updateProgEvent.bind null, index
})
)
)
)
)
)
_selectBasicUnit: (unit) ->
@props.setSelectedItem Imm.fromJS {
type: 'basicUnit'
unitId: unit.get('id')
unitName: unit.get('name')
progNoteId: @props.progNote.get('id')
}
_selectPlanSectionTarget: (unit, section, mostRecentTargetRevision) ->
@props.setSelectedItem Imm.fromJS {
type: 'planSectionTarget'
unitId: unit.get('id')
sectionId: section.get('id')
targetId: mostRecentTargetRevision.get('id')
targetName: mostRecentTargetRevision.get('name')
targetDescription: mostRecentTargetRevision.get('description')
progNoteId: @props.progNote.get('id')
}
CancelledProgNoteView = React.createFactory React.createClass
displayName: 'CancelledProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isExpanded: false
}
render: ->
# Here, we assume that the latest revision was the one that
# changed the status. This assumption may become invalid
# when full prognote editing becomes supported.
latestRev = @props.progNoteHistory.last()
firstRev = @props.progNoteHistory.first()
statusChangeRev = latestRev
return R.div({
id: "entry-#{firstRev.get('id')}"
className: 'entry cancelStub'
},
R.button({
className: 'toggleDetails btn btn-xs btn-default'
onClick: @_toggleDetails
},
R.span({className: "#{showWhen not @state.isExpanded}"},
FaIcon 'chevron-down'
" Show details"
)
R.span({className: "#{showWhen @state.isExpanded}"},
FaIcon 'chevron-up'
" Hide details"
)
)
R.h3({},
"Discarded: "
formatTimestamp(firstRev.get('backdate') or firstRev.get('timestamp'))
" (late entry)" if firstRev.get('backdate')
),
R.div({className: "details #{showWhen @state.isExpanded}"},
R.h4({},
"Discarded by "
statusChangeRev.get('author')
" on "
formatTimestamp statusChangeRev.get('timestamp')
),
R.h4({}, "Reason for discarding:")
R.div({className: 'reason'},
renderLineBreaks latestRev.get('statusReason')
)
switch latestRev.get('type')
when 'basic'
QuickNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
userProgram: @props.userProgram
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
filteredProgNote: @props.filteredProgNote
dataTypeFilter: @props.dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
eventTypes: @props.eventTypes
userProgram: @props.userProgram
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
)
)
_toggleDetails: (event) ->
@setState (s) -> {isExpanded: not s.isExpanded}
EntryHeader = React.createFactory React.createClass
displayName: 'EntryHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
render: ->
{
userProgram
revisionHistory
isEditing
isReadOnly
progNote
filteredProgNote
progNoteHistory
progEvents
globalEvents
clientFile
startRevisingProgNote
selectProgNote
} = @props
userIsAuthor = progNote? and (progNote.get('author') is global.ActiveSession.userName)
canViewOptions = progNote? and not isEditing
canModify = userIsAuthor and not isReadOnly
hasRevisions = revisionHistory.size > 1
numberOfRevisions = revisionHistory.size - 1
hasMultipleRevisions = numberOfRevisions > 1
firstRevision = revisionHistory.first() # Use original revision's data
timestamp = (
firstRevision.get('startTimestamp') or
firstRevision.get('backdate') or
firstRevision.get('timestamp')
)
R.div({className: 'entryHeader'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp, @props.dateFormat)
(if firstRevision.get('backdate')
R.span({className: 'lateTimestamp'},
"(late entry)"
)
)
)
(if progNote? and hasRevisions
R.div({className: 'revisions'},
R.a({
className: 'selectProgNoteButton'
onClick: selectProgNote.bind null, progNote
},
"#{numberOfRevisions} revision#{if hasMultipleRevisions then 's' else ''}"
)
)
)
R.div({className: 'author'},
'by '
firstRevision.get('authorDisplayName') or firstRevision.get('author')
(if userProgram and not userProgram.isEmpty()
ColorKeyBubble({
colorKeyHex: userProgram.get('colorKeyHex')
popover: {
title: userProgram.get('name')
content: userProgram.get('description')
placement: 'left'
}
})
)
)
(if canViewOptions
R.div({className: 'options'},
B.DropdownButton({
id: "entryHeaderDropdown-#{progNote.get('id')}"
className: 'entryHeaderDropdown'
pullRight: true
noCaret: true
title: FaIcon('ellipsis-v', {className:'menuItemIcon'})
},
(if canModify
B.MenuItem({onClick: startRevisingProgNote.bind null, progNote, progEvents},
"Edit"
)
)
B.MenuItem({onClick: @_print.bind null, filteredProgNote or progNote, progEvents, clientFile},
"Print"
)
(if canModify
B.MenuItem({onClick: @_openCancelProgNoteDialog},
OpenDialogLink({
ref: 'cancelButton'
className: 'cancelNote'
dialog: CancelProgNoteDialog
progNote
progEvents
globalEvents
}, "Discard")
)
)
)
)
)
)
_openCancelProgNoteDialog: (event) ->
@refs.cancelButton.open(event)
_print: (progNote, progEvents, clientFile) ->
openWindow {
page: 'printPreview'
dataSet: JSON.stringify([
{
format: 'progNote'
data: progNote
progEvents
clientFile
}
])
}
GlobalEventView = React.createFactory React.createClass
displayName: 'GlobalEventView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{globalEvent} = @props
eventType = @props.eventTypes.find (eventType) ->
eventType.get('id') is globalEvent.get('typeId')
eventTypeName = if eventType then eventType.get('name') else null
programId = globalEvent.get('programId')
program = @props.programsById.get(programId) or Imm.Map()
timestamp = globalEvent.get('backdate') or globalEvent.get('timestamp')
startTimestamp = makeMoment globalEvent.get('startTimestamp')
endTimestamp = makeMoment globalEvent.get('endTimestamp')
# A full day is 12:00AM to 11:59PM
isFullDay = (
startTimestamp.isSame(startTimestamp.startOf 'day') and
endTimestamp.isSame(endTimestamp.endOf 'day')
)
return R.div({
id: "entry-#{globalEvent.get('id')}"
className: 'entry globalEventView'
},
EntryHeader({
revisionHistory: Imm.List [globalEvent]
userProgram: program
dateFormat: Config.dateFormat if isFullDay
})
R.h3({},
FaIcon('globe')
"Global Event: "
globalEvent.get('title') or eventTypeName or (
if globalEvent.get('description').length > 20
globalEvent.get('description').substring(0, 20) + "..."
else
globalEvent.get('description')
)
)
(if globalEvent.get('title') or eventTypeName and globalEvent.get('description')
R.p({}, globalEvent.get('description'))
)
(if globalEvent.get('endTimestamp') and not isFullDay
R.p({},
"From: "
formatTimestamp globalEvent.get('startTimestamp')
" until "
formatTimestamp globalEvent.get('endTimestamp')
)
)
R.p({},
"Reported: "
formatTimestamp timestamp
)
)
# Applies selected styles without having to re-render entire EntriesListView tree
InlineSelectedItemStyles = ({selectedItem}) ->
R.style({},
(switch selectedItem.get('type')
when 'planSectionTarget' # Target entry history
"""
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 6px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) h3 {
opacity: 1 !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) .notes {
opacity: 1 !important;
}
"""
when 'quickNote' # QuickNote entry history
"""
div.basic.progNote:not(.isEditing) .notes > div {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'basicUnit' # General 'Notes' entry history (TODO: what > 1 basic unit?)
"""
div.basic.unit.unitId-#{selectedItem.get('unitId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'progNote' # ProgNote revisions
"""
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions {
border-left: 2px solid #3176aa !important;
}
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions a {
color: #3176aa !important;
opacity: 1 !important;
}
"""
else
throw new Error "Unknown selectedItem type #{selectedItem.get('type')} for InlineSelectedItemStyles"
)
)
filterEmptyProgNoteValues = (progNote) ->
# Don't bother filtering a quickNote (doesn't have units)
unless progNote.has 'units'
return progNote
progNoteUnits = progNote.get('units')
.map (unit) ->
if unit.get('type') is 'basic'
# Strip empty metric values
unitMetrics = unit.get('metrics').filterNot (metric) -> not metric.get('value')
return unit.set('metrics', unitMetrics)
else if unit.get('type') is 'plan'
unitSections = unit.get('sections')
.map (section) ->
sectionTargets = section.get('targets')
# Strip empty metric values
.map (target) ->
targetMetrics = target.get('metrics').filterNot (metric) -> not metric.get('value')
return target
.set('metrics', targetMetrics)
.remove('description') # We don't need target description snapshot displayed/searched
# Strip empty targets
.filterNot (target) ->
not target.get('notes') and target.get('metrics').isEmpty()
return section.set('targets', sectionTargets)
.filterNot (section) ->
section.get('targets').isEmpty()
return unit.set('sections', unitSections)
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
.filterNot (unit) ->
# Finally, strip any empty 'basic' units, or 'plan' units with 0 sections
if unit.get('type') is 'basic'
return not unit.get('notes') and unit.get('metrics').isEmpty()
else if unit.get('type') is 'plan'
return unit.get('sections').isEmpty()
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
return progNote.set('units', progNoteUnits)
return ProgNotesTab
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Client file view for displaying, searching, and updating progress notes
Fs = require 'fs'
Path = require 'path'
Assert = require 'assert'
Imm = require 'immutable'
Moment = require 'moment'
Async = require 'async'
_ = require 'underscore'
Config = require '../config'
Term = require '../term'
Persist = require '../persist'
dataTypeOptions = Imm.fromJS [
# {name: 'Progress Notes', id: 'progNotes'}
# {name: 'Targets', id: 'targets'}
{name: 'Events', id: 'events'}
]
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
ReactDOMServer = win.ReactDOMServer
Mark = win.Mark
B = require('../utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
CancelProgNoteDialog = require('./cancelProgNoteDialog').load(win)
ColorKeyBubble = require('../colorKeyBubble').load(win)
CrashHandler = require('../crashHandler').load(win)
ExpandingTextArea = require('../expandingTextArea').load(win)
MetricWidget = require('../metricWidget').load(win)
ProgEventWidget = require('../progEventWidget').load(win)
OpenDialogLink = require('../openDialogLink').load(win)
ProgNoteDetailView = require('../progNoteDetailView').load(win)
EntryDateNavigator = require('./entryDateNavigator').load(win)
FilterBar = require('./filterBar').load(win)
{
FaIcon, openWindow, renderLineBreaks, showWhen, formatTimestamp, renderName, makeMoment
getUnitIndex, getPlanSectionIndex, getPlanTargetIndex, blockedExtensions, stripMetadata, scrollToElement
} = require('../utils').load(win)
# List of fields we exclude from keyword search
excludedSearchFields = Imm.fromJS [
'id', 'revisionId', 'templateId', 'typeId', 'relatedProgNoteId', 'programId'
'relatedProgEventId', 'authorProgramId', 'clientFileId'
'timestamp', 'backdate', 'startTimestamp', 'endTimestamp'
'type', 'entryType', 'status', 'definition'
# 'filteredProgNote' and {entryType: globalEvent} used instead
'progNoteHistory', 'globalEvents'
]
ProgNotesTab = React.createFactory React.createClass
displayName: 'ProgNotesTab'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
hasChanges: ->
@refs.ui.hasChanges()
_toProgNoteHistoryEntry: (progNoteHistory) ->
latestRevision = progNoteHistory.last()
firstRevision = progNoteHistory.first()
# We pass down a pre-filtered version of the progNote
# because the search-by-keyword feature relies on this data
filteredProgNote = filterEmptyProgNoteValues(latestRevision)
# Revisions all have same 'id', just different revisionIds
progNoteId = firstRevision.get('id')
programId = firstRevision.get('authorProgramId')
timestamp = latestRevision.get('backdate') or firstRevision.get('timestamp')
# Mix in all other related data from clientFile's other collections
progEvents = @props.progEvents.filter (progEvent) ->
return progEvent.get('relatedProgNoteId') is progNoteId
# progNote still gets any cancelled globalEvents
globalEvents = @props.globalEvents.filter (globalEvent) ->
return globalEvent.get('relatedProgNoteId') is progNoteId
attachments = @props.attachmentsByProgNoteId.get(progNoteId) or Imm.List()
return Imm.Map {
entryType: 'progNote'
id: progNoteId
programId
timestamp
progNoteHistory
filteredProgNote
progEvents
globalEvents
attachments
}
_toGlobalEventEntry: (globalEvent) ->
timestamp = globalEvent.get('startTimestamp') # Order by startTimestamp
return Imm.Map {
entryType: 'globalEvent'
id: globalEvent.get('id')
programId: globalEvent.get('programId')
timestamp
globalEvent
}
render: ->
progNoteEntries = @props.progNoteHistories.map @_toProgNoteHistoryEntry
globalEventEntries = @props.globalEvents
.filter (e) -> e.get('status') is 'default'
.map @_toGlobalEventEntry
historyEntries = progNoteEntries
.concat globalEventEntries
.sortBy (entry) -> entry.get('timestamp')
.reverse()
props = _.extend {}, @props, {
ref: 'ui'
historyEntries
}
return ProgNotesTabUi(props)
ProgNotesTabUi = React.createFactory React.createClass
displayName: 'ProgNotesTabUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
editingProgNoteId: null
attachment: null
selectedItem: null
backdate: ''
transientData: null
isLoading: null
isFiltering: null
showHistory: true
searchQuery: ''
programIdFilter: null
dataTypeFilter: null
}
hasChanges: ->
@_transientDataHasChanges()
render: ->
{transientData} = @state
hasChanges = @hasChanges()
hasEnoughData = @props.historyEntries.size > 0
isEditing = transientData?
# Only show the single progNote while editing
historyEntries = if not isEditing then @props.historyEntries else Imm.List [
@props.historyEntries.find (entry) ->
entry.get('id') is transientData.getIn(['progNote', 'id'])
]
####### Filtering / Search Logic #######
if @state.isFiltering
# TODO: Make this filtering faster
# By program?
if @state.programIdFilter
historyEntries = historyEntries.filter (e) => e.get('programId') is @state.programIdFilter
# By type of progNote?
if @state.dataTypeFilter in ['progNotes', 'targets']
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'progNote'
# by event without a query (suppress notes)
if @state.dataTypeFilter is 'events'
historyEntries = historyEntries.filter (e) => e.get('entryType') is 'globalEvent' or not e.get('progEvents').isEmpty()
# When searching 'targets', only check 'full' progNotes
# TODO: Restore this dataType at some point
# if @state.dataTypeFilter is 'targets'
# historyEntries = historyEntries.filter (e) => e.getIn(['filteredProgNote', 'type']) is 'full'
# By search query? Pass dataTypeFilter for conditional property checks
if @state.searchQuery.trim().length > 0
historyEntries = @_filterEntries(historyEntries, @state.dataTypeFilter)
return R.div({className: 'progNotesView'},
R.div({className: 'panes'},
R.section({className: 'leftPane'},
# TODO: Make component
R.div({className: 'flexButtonToolbar'},
R.button({
className: [
'saveButton'
'collapsed' unless isEditing
].join ' '
onClick: @_saveTransientData
disabled: not hasChanges
},
FaIcon('save')
R.span({className: 'wideMenuItemText'},
"Save #{Term 'Progress Note'}"
)
)
R.button({
className: [
'discardButton'
'collapsed' unless isEditing
].join ' '
onClick: @_cancelRevisingProgNote
},
FaIcon('undo')
R.span({className: 'wideMenuItemText'},
"Discard"
)
)
R.button({
className: [
'newProgNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewProgNote
disabled: @state.isLoading or @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Progress Note'}"
)
)
R.button({
ref: 'addQuickNoteButton'
className: [
'addQuickNoteButton'
'collapsed' if isEditing
].join ' '
onClick: @_openNewQuickNote
disabled: @props.isReadOnly
},
FaIcon('plus')
R.span({className: 'wideMenuItemText'},
"#{Term 'Quick Note'}"
)
)
R.button({
ref: 'openFilterBarButton'
className: [
'openFilterBarButton'
'collapsed' if isEditing or @state.isFiltering
showWhen hasEnoughData
].join ' '
onClick: @_toggleIsFiltering
},
FaIcon('search')
)
R.button({
ref: 'toggleHistoryPane'
className: [
'toggleHistoryPaneButton'
].join ' '
onClick: @_toggleHistoryPane
},
(if @state.showHistory
FaIcon('angle-right')
else
FaIcon('angle-left')
)
)
)
(unless hasEnoughData
R.div({className: 'empty'},
R.div({className: 'message'},
"This #{Term 'client'} does not currently have any #{Term 'progress notes'}."
)
)
)
(if @state.isFiltering and not isEditing
FilterBar({
ref: 'filterBar'
historyEntries
programIdFilter: @state.programIdFilter
dataTypeFilter: @state.dataTypeFilter
programsById: @props.programsById
dataTypeOptions
onClose: @_toggleIsFiltering
onUpdateSearchQuery: @_updateSearchQuery
onSelectProgramId: @_updateProgramIdFilter
onSelectDataType: @_updateDataTypeFilter
})
)
# TODO: Make component
R.div({
className: [
'empty'
showWhen @state.isFiltering and historyEntries.isEmpty()
].join ' '
},
R.div({className: 'message animated fadeIn'},
R.div({},
"No results found"
(if @state.dataTypeFilter
R.span({},
" in "
R.strong({},
dataTypeOptions.find((t) => t.get('id') is @state.dataTypeFilter).get('name')
)
)
)
)
(if @state.searchQuery.trim().length > 0
R.div({},
"matching: \""
R.strong({}, @state.searchQuery)
"\""
)
)
(if @state.programIdFilter
R.div({},
"for: "
R.strong({},
@props.programsById.getIn [@state.programIdFilter, 'name']
)
ColorKeyBubble({
colorKeyHex: @props.programsById.getIn [@state.programIdFilter, 'colorKeyHex']
})
)
)
R.div({},
R.button({
id: 'resetFilterButton'
className: 'btn btn-link'
onClick: => @refs.filterBar.clear()
},
FaIcon('refresh')
"Reset"
)
)
)
)
# Apply selectedItem styles as inline <style>
(if @state.selectedItem?
InlineSelectedItemStyles({
selectedItem: @state.selectedItem
})
)
EntriesListView({
ref: 'entriesListView'
historyEntries
entryIds: historyEntries.map (e) -> e.get('id')
transientData
eventTypes: @props.eventTypes
clientFile: @props.clientFile
programsById: @props.programsById
planTargetsById: @props.planTargetsById
dataTypeFilter: @state.dataTypeFilter
searchQuery: @state.searchQuery
programIdFilter: @state.programIdFilter
isFiltering: @state.isFiltering
isReadOnly: @props.isReadOnly
isEditing
setSelectedItem: @_setSelectedItem
selectProgNote: @_selectProgNote
startRevisingProgNote: @_startRevisingProgNote
cancelRevisingProgNote: @_cancelRevisingProgNote
updatePlanTargetNotes: @_updatePlanTargetNotes
updateBasicUnitNotes: @_updateBasicUnitNotes
updateBasicMetric: @_updateBasicMetric
updatePlanTargetMetric: @_updatePlanTargetMetric
updateProgEvent: @_updateProgEvent
updateQuickNotes: @_updateQuickNotes
updateShiftSummary: @_updateShiftSummary
})
)
R.section({
className: [
'rightPane'
'collapsed' unless @state.showHistory
].join ' '
},
ProgNoteDetailView({
ref: 'progNoteDetailView'
isFiltering: @state.isFiltering
searchQuery: @state.searchQuery
item: @state.selectedItem
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
metricsById: @props.metricsById
programsById: @props.programsById
})
)
)
)
_startRevisingProgNote: (progNote, progEvents) ->
# Include transient and original data into generic store
transientData = Imm.fromJS {
progNote
originalProgNote: progNote
progEvents
originalProgEvents: progEvents
# TODO: Allow editing for globalEvents as well
}
@setState {transientData}
_cancelRevisingProgNote: ->
if @_transientDataHasChanges()
return Bootbox.confirm "Discard all changes made to the #{Term 'progress note'}?", (ok) =>
if ok then @_discardTransientData()
@_discardTransientData()
_discardTransientData: ->
@setState {transientData: null}
_transientDataHasChanges: ->
transientData = @state.transientData
return null unless transientData?
originalProgNote = transientData.get('originalProgNote')
progNote = transientData.get('progNote')
progNoteHasChanges = not Imm.is progNote, originalProgNote
originalProgEvents = transientData.get('originalProgEvents')
progEvents = transientData.get('progEvents')
progEventsHasChanges = not Imm.is progEvents, originalProgEvents
# TODO: Compare globalEvents
return progNoteHasChanges or progEventsHasChanges
_updateBasicUnitNotes: (unitId, event) ->
newNotes = event.target.value
transientData = @state.transientData
unitIndex = getUnitIndex transientData.get('progNote'), unitId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'notes'
]
newNotes
)
}
_updatePlanTargetNotes: (unitId, sectionId, targetId, event) ->
newNotes = event.target.value
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'notes'
]
newNotes
)
}
_updateQuickNotes: (event) ->
newNotes = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'notes'], newNotes
}
_updateShiftSummary: (event) ->
newSummary = event.target.value
@setState {
transientData: @state.transientData.setIn ['progNote', 'summary'], newSummary
}
_updateProgEvent: (index, updatedProgEvent) ->
transientData = @state.transientData.setIn ['progEvents', index], updatedProgEvent
@setState {transientData}
_isValidMetric: (value) -> value.match /^-?\d*\.?\d*$/
_updatePlanTargetMetric: (unitId, sectionId, targetId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
sectionIndex = getPlanSectionIndex progNote, unitIndex, sectionId
targetIndex = getPlanTargetIndex progNote, unitIndex, sectionIndex, targetId
metricIndex = progNote.getIn(
[
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex,
'metrics'
]
).findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'sections', sectionIndex
'targets', targetIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_updateBasicMetric: (unitId, metricId, newMetricValue) ->
return unless @_isValidMetric(newMetricValue)
transientData = @state.transientData
progNote = transientData.get('progNote')
unitIndex = getUnitIndex progNote, unitId
metricIndex = progNote.getIn ['units', unitIndex, 'metrics']
.findIndex (metric) =>
return metric.get('id') is metricId
@setState {
transientData: transientData.setIn(
[
'progNote'
'units', unitIndex
'metrics', metricIndex
'value'
]
newMetricValue
)
}
_saveTransientData: ->
{progNote, progEvents, originalProgNote, originalProgEvents} = @state.transientData.toObject()
# Any progEvents modified?
revisedProgEvents = progEvents.filter (progEvent, index) ->
not Imm.is progEvent, originalProgEvents.get(index)
# Only save modified progNotes/progEvents
Async.series [
(cb) ->
return cb() if Imm.is originalProgNote, progNote
ActiveSession.persist.progNotes.createRevision progNote, cb
(cb) ->
return cb() if revisedProgEvents.isEmpty()
Async.map revisedProgEvents, ActiveSession.persist.progEvents.createRevision, cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
@_discardTransientData()
_checkUserProgram: (cb) ->
# Skip if no clientProgram(s)
if @props.clientPrograms.isEmpty()
cb()
return
userProgramId = global.ActiveSession.programId
# Skip if userProgram matches one of the clientPrograms
matchingUserProgram = @props.clientPrograms.find (program) ->
userProgramId is program.get('id')
if matchingUserProgram
cb()
return
# override by default if client only in a single program
if @props.clientPrograms.size is 1
userProgramId = @props.clientPrograms.first().get('id')
userProgram = @props.programsById.get userProgramId
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
cb()
return
clientName = renderName @props.clientFile.get('clientName')
userProgramName = if userProgramId
@props.programsById.getIn [userProgramId, 'name']
else
"(none)"
# Build programDropdown markup
programDropdown = R.select({
id: 'programDropdown'
className: 'form-control '
},
R.option({value: ''}, "Select a #{Term 'client'} #{Term 'program'}"),
(@props.clientPrograms.map (program) ->
R.option({
key: program.get('id')
value: program.get('id')
},
program.get('name')
)
)
)
focusPopover = ->
setTimeout (=>
$popover = $('.popover textarea')[0]
if $popover? then $popover.focus()
), 500
# Prompt user about temporarily overriding their program
Bootbox.dialog {
title: "Switch to #{Term 'client'} #{Term 'program'}?"
message: R.div({},
"#{clientName} is not enrolled in your assigned #{Term 'program'}: ",
'"', R.b({}, userProgramName), '".',
R.br(), R.br(),
"Override your assigned #{Term 'program'} below, or click \"Ignore\"."
R.br(), R.br(),
programDropdown
)
buttons: {
cancel: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
ignore: {
label: "Ignore"
className: "btn-warning"
callback: ->
focusPopover()
cb()
}
success: {
label: "Override #{Term 'Program'}"
className: "btn-success"
callback: =>
userProgramId = $('#programDropdown').val()
if not userProgramId? or userProgramId.length is 0
Bootbox.alert "No #{Term 'program'} was selected, please try again."
return
userProgram = @props.programsById.get userProgramId
# Override the user's program
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
focusPopover()
cb()
}
}
}
_checkPlanChanges: (cb) ->
# Check for unsaved changes to the client plan
if not @props.hasChanges()
cb()
return
# Prompt user about unsaved changes
Bootbox.dialog {
title: "Unsaved Changes to #{Term 'Plan'}"
message: """
You have unsaved changes in the #{Term 'plan'} that will not be reflected in this
#{Term 'progress note'}. How would you like to proceed?
"""
buttons: {
default: {
label: "Cancel"
className: "btn-default"
callback: =>
Bootbox.hideAll()
}
danger: {
label: "Ignore"
className: "btn-danger"
callback: -> cb()
}
success: {
label: "View #{Term 'Plan'}"
className: "btn-success"
callback: =>
Bootbox.hideAll()
@props.onTabChange 'plan'
return
}
}
}
_openNewProgNote: ->
Async.series [
@_checkPlanChanges
@_checkUserProgram
(cb) =>
@setState {isLoading: true}
# Cache data to global, so can access again from newProgNote window
# Set up the dataStore if doesn't exist
# Store property as clientFile ID to prevent confusion
global.dataStore ?= {}
# Only needs to pass latest revisions of each planTarget
# In this case, index [0] is the latest revision
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
global.dataStore[@props.clientFileId] = {
clientFile: @props.clientFile
planTargetsById
metricsById: @props.metricsById
progNoteHistories: @props.progNoteHistories
progEvents: @props.progEvents
eventTypes: @props.eventTypes
programsById: @props.programsById
clientPrograms: @props.clientPrograms
}
openWindow {page: 'newProgNote', clientFileId: @props.clientFileId}, (newProgNoteWindow) =>
# prevent window from closing before its ready
# todo a more elegant way to do this?
newProgNoteWindow.on 'close', =>
newProgNoteWindow = null
global.ActiveSession.persist.eventBus.once 'newProgNotePage:loaded', cb
], (err) =>
@setState {isLoading: false}
if err
CrashHandler.handle err
return
_openNewQuickNote: ->
Async.series [
@_checkUserProgram
@_toggleQuickNotePopover
], (err) ->
if err
CrashHandler.handle err
return
_attach: ->
# Configures hidden file inputs with custom attributes, and clicks it
$nwbrowse = $('#nwBrowse')
$nwbrowse
.off()
#.attr('accept', ".#{extension}")
.on('change', (event) => @_encodeFile event.target.value)
.click()
_encodeFile: (file) ->
return unless file
# clear input value so onchange can still fire if user tries same file again
$('#nwBrowse').val(null)
filename = Path.basename file
fileExtension = (Path.extname file).toLowerCase()
if blockedExtensions.indexOf(fileExtension) > -1
Bootbox.alert {
title: "Warning: File Blocked"
message: "#{filename} is potentially unsafe and cannot be attached."
}
return
attachment = Fs.readFileSync(file)
filesize = Buffer.byteLength(attachment, 'base64')
if filesize < 1048576
filesize = (filesize / 1024).toFixed() + " KB"
else
filesize = (filesize / 1048576).toFixed() + " MB"
# Convert to base64 encoded string
encodedAttachment = Buffer.from(attachment).toString 'base64'
@setState {
attachment: {
encodedData: encodedAttachment
filename: filename
}
}
# TODO: Append for when multiple attachments allowed (#787)
$('#attachmentArea').html filename + " (" + filesize + ") <i class='fa fa-times' id='removeBtn'></i>"
removeFile = $('#removeBtn')
removeFile.on 'click', (event) =>
$('#attachmentArea').html ''
@setState {attachment: null}
_toggleQuickNotePopover: ->
# TODO: Refactor to stateful React component
quickNoteToggle = $(findDOMNode @refs.addQuickNoteButton)
quickNoteToggle.popover {
placement: 'bottom'
html: true
trigger: 'manual'
content: '''
<textarea class="form-control"></textarea>
<div id="attachmentArea" style="padding-top:10px; color:#3176aa;"></div>
<div class="buttonBar form-inline">
<label>Date: </label> <input type="text" class="form-control backdate date"></input>
<button class="btn btn-default" id="attachBtn"><i class="fa fa-paperclip"></i> Attach</button>
<button class="cancel btn btn-danger"><i class="fa fa-trash"></i> Discard</button>
<button class="save btn btn-primary"><i class="fa fa-check"></i> Save</button>
<input type="file" class="hidden" id="nwBrowse"></input>
</div>
'''
}
if quickNoteToggle.data('isVisible')
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
else
quickNoteToggle.popover('show')
quickNoteToggle.data('isVisible', true)
attachFile = $('#attachBtn')
attachFile.on 'click', (event) =>
@_attach event
attachFile.blur()
popover = quickNoteToggle.siblings('.popover')
popover.find('.save.btn').on 'click', (event) =>
event.preventDefault()
@_createQuickNote popover.find('textarea').val(), @state.backdate, @state.attachment, (err) =>
@setState {
backdate: '',
attachment: null
}
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('.backdate.date').datetimepicker({
format: 'MMM-DD-YYYY h:mm A'
defaultDate: Moment()
maxDate: Moment()
widgetPositioning: {
vertical: 'bottom'
}
}).on 'dp.change', (e) =>
if Moment(e.date).format('YYYY-MM-DD-HH') is Moment().format('YYYY-MM-DD-HH')
@setState {backdate: ''}
else
@setState {backdate: Moment(e.date).format(Persist.TimestampFormat)}
popover.find('.cancel.btn').on 'click', (event) =>
event.preventDefault()
@setState {
backdate: '',
attachment: null
}
quickNoteToggle.popover('hide')
quickNoteToggle.data('isVisible', false)
popover.find('textarea').focus()
# Store quickNoteBeginTimestamp as class var, since it wont change
@quickNoteBeginTimestamp = Moment().format(Persist.TimestampFormat)
_createQuickNote: (notes, backdate, attachment, cb) ->
unless notes
Bootbox.alert "Cannot create an empty #{Term 'quick note'}."
return
quickNote = Imm.fromJS {
type: 'basic'
status: 'default'
clientFileId: @props.clientFileId
notes
backdate
authorProgramId: global.ActiveSession.programId or ''
beginTimestamp: @quickNoteBeginTimestamp
}
# TODO: Async series
global.ActiveSession.persist.progNotes.create quickNote, (err, result) =>
if err
cb err
return
unless attachment
cb()
return
attachmentData = Imm.fromJS {
status: 'default'
filename: attachment.filename
encodedData: attachment.encodedData
clientFileId: @props.clientFileId
relatedProgNoteId: result.get('id')
}
global.ActiveSession.persist.attachments.create attachmentData, cb
_setSelectedItem: (selectedItem) ->
@setState {selectedItem}
_selectProgNote: (progNote) ->
@_setSelectedItem Imm.fromJS {
type: 'progNote'
progNoteId: progNote.get('id')
}
_filterEntries: (entries, dataTypeFilter) ->
if @state.searchQuery.trim().length is 0
return entries
# Split into query parts
queryParts = Imm.fromJS(@state.searchQuery.split(' ')).map (p) -> p.toLowerCase()
containsSearchQuery = (data) ->
if dataTypeFilter
# Only search through 'progNote' types for progNotes and targets
if dataTypeFilter in ['progNotes', 'targets'] and data.has('entryType') and data.get('entryType') isnt 'progNote'
return false
# For 'targets', favour 'filteredProgNote' with 'type: full' - since it only contains targets with data
# TODO: Restore this dataType at some point
# else if dataTypeFilter is 'targets'
# data = data.get('filteredProgNote') or data
else if dataTypeFilter is 'events'
# Ignore progNote entries without progEvents
if data.has('entryType') and data.get('entryType') isnt 'globalEvent' and data.get('progEvents').isEmpty()
return false
# Favor 'progEvents' in progNote entries
else
data = data.get('progEvents') or data
return data.some (value, property) ->
# Skip excluded field
if excludedSearchFields.includes property
return false
# Run all keywords against string contents
if typeof value is 'string'
value = value.toLowerCase()
includesAllParts = queryParts.every (part) -> value.includes(part)
# if includesAllParts then console.log "Match:", "#{property}:", value
return includesAllParts
# When not a string, it must be an Imm.List / Map
# so we'll loop through this same method on it
return containsSearchQuery(value)
# Only keep entries that contain all query parts
return entries.filter containsSearchQuery
_updateSearchQuery: (searchQuery) ->
@setState {searchQuery}
_toggleIsFiltering: ->
isFiltering = not @state.isFiltering
# Clear filter values when toggling off filterBar
if not isFiltering
@setState {
isFiltering
searchQuery: ''
dataTypeFilter: null
programIdFilter: null
}
return
@setState {isFiltering}
_toggleHistoryPane: ->
showHistory = not @state.showHistory
@setState {showHistory}
_updateProgramIdFilter: (programIdFilter) ->
@setState {programIdFilter}
_updateDataTypeFilter: (dataTypeFilter) ->
@setState {dataTypeFilter}
EntriesListView = React.createFactory React.createClass
displayName: 'EntriesListView'
mixins: [React.addons.PureRenderMixin]
getInitialState: -> {
historyCount: 10
filterCount: 10
}
componentDidMount: ->
# Watch scroll for infinite scroll behaviour, throttle to 1call/per/150ms
@_watchUnlimitedScroll = _.throttle(@_watchUnlimitedScroll, 150)
@entriesListView = $(findDOMNode @)
@entriesListView.on 'scroll', @_watchUnlimitedScroll
# Custom positioning logic to have EntryDateNavigator hug this.bottom-right
@entryDateNavigator = $(findDOMNode @refs.entryDateNavigator)
# Set initial position, and listen for window resize
@rightPane = $('.rightPane')[1] #todo: clunky... Ref not available here, maybe get from this upstream?
@_setNavigatorRightOffset()
$(win).on 'resize', @_setNavigatorRightOffset
componentDidUpdate: (oldProps, oldState) ->
# Update highlighting when anything changes while searching
# TODO: Maybe wrap component with this logic; allow state to change unimpeded
if @props.isFiltering
filterParametersChanged = (
@props.searchQuery isnt oldProps.searchQuery or
@props.dataTypeFilter isnt oldProps.dataTypeFilter or
@props.programIdFilter isnt oldProps.programIdFilter
)
# Reset filterCount and scroll to top anytime filter parameters change
if filterParametersChanged
@setState @getInitialState, @_resetScroll
if @props.searchQuery
if @state.filterCount > oldState.filterCount
# Only highlight new entries added from unlimited-scroll
newEntriesCount = @state.filterCount - oldState.filterCount
entryNodes = @props.entryIds
.slice 0, @state.filterCount
.takeLast newEntriesCount
.map (id) -> win.document.getElementById(id)
.toArray()
new Mark(entryNodes).mark(@props.searchQuery)
else
@_redrawSearchHighlighting()
# Toggle FilterBar, resets selectedItem
if @props.isFiltering isnt oldProps.isFiltering
if @props.isFiltering
# Reset filterCount when FilterBar opens
@setState {filterCount: 10}
else
# Clear search highlighting when FilterBar closes
@_redrawSearchHighlighting()
@props.setSelectedItem(null)
# Reset scroll when opens edit view for progNote
if @props.isEditing isnt oldProps.isEditing and @props.isEditing
@_resetScroll()
componentWillUnmount: ->
@entriesListView.off 'scroll', @_watchUnlimitedScroll
$(win.document).off 'resize', @_setNavigatorRightOffset
_watchUnlimitedScroll: ->
# Skip if we're scrolling via EntryDateNavigator, entry count is already set
return if @isAutoScrolling
# Detect if we've reached the lower threshold to trigger update
if @entriesListView.scrollTop() + (@entriesListView.innerHeight() *2) >= @entriesListView[0].scrollHeight
# Count is contextual to complete history, or filtered entries
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
# Disregard if nothing left to load into the count
return if @state[countType] >= @props.historyEntries.size
# Update UI with +10 to entry count
nextState = {}
nextState[countType] = @state[countType] + 10
@setState(nextState)
_setNavigatorRightOffset: ->
# Add rightPane's width to navigator's initial (css) right positioning
# TODO: Can we use new chrome 'sticky' instead? Sometimes doesn't show on HCR
right = if @rightPane? then @rightPane.offsetWidth else 0
@entryDateNavigator.css {right}
_scrollToEntryDate: (date, cb=(->)) ->
# TODO: Have moment objs already pre-built in historyEntries
entry = @props.historyEntries.find (e) ->
timestamp = makeMoment e.get('timestamp')
return date.isSame timestamp, 'day'
if not entry?
console.warn "Cancelled scroll, could not find #{date.toDate()} in historyEntries"
cb()
return
# Should we supplement filter/historyCount first?
countType = if @props.isFiltering then 'filterCount' else 'historyCount'
index = @props.historyEntries.indexOf entry
requiresMoreEntries = @state[countType] - 1 < index
Async.series [
(cb) =>
return cb() unless requiresMoreEntries
# Provide 10 extra entries, so destinationEntry appears at top
# Set the new count (whichever type is pertinent), and *then* scroll to the entry
newState = {}
newState[countType] = (index + 1) + 10
@setState newState, cb
(cb) =>
# Scroll to latest entry matching date
$entriesListView = findDOMNode(@)
$element = win.document.getElementById "entry-#{entry.get('id')}"
@isAutoScrolling = true # Temporarily block scroll listener(s)
scrollToElement $entriesListView, $element, 1000, 'easeInOutQuad', cb
(cb) =>
@isAutoScrolling = false
# Scroll is completed, briefly highlight/animate any entries with matching date
selectedMoment = makeMoment entry.get('timestamp')
entryIdsToFlash = @props.historyEntries
.filter (e) ->
timestamp = makeMoment e.get('timestamp')
return selectedMoment.isSame makeMoment(timestamp), 'day'
.map (e) -> '#entry-' + e.get('id')
.toArray()
.join ', '
$(entryIdsToFlash).addClass 'flashDestination'
setTimeout(->
$(entryIdsToFlash).removeClass 'flashDestination'
, 2500)
cb()
], cb
_resetScroll: ->
findDOMNode(@).scrollTop = 0
_redrawSearchHighlighting: ->
# Performs a complete (expensive) mark/unmark of the entire EntriesListView
entriesHighlighting = new Mark findDOMNode @refs.entriesListView
if @props.isFiltering
entriesHighlighting.unmark().mark(@props.searchQuery)
else
entriesHighlighting.unmark()
render: ->
{historyEntries, isFiltering} = @props
# Limit number of entries by filter/historyCount
sliceCount = if isFiltering then @state.filterCount else @state.historyCount
slicedHistoryEntries = historyEntries.slice 0, sliceCount
R.div({
ref: 'entriesListView'
id: 'entriesListView'
className: showWhen not slicedHistoryEntries.isEmpty()
},
EntryDateNavigator({
ref: 'entryDateNavigator'
historyEntries: @props.historyEntries
onSelect: @_scrollToEntryDate
})
(slicedHistoryEntries.map (entry) =>
switch entry.get('entryType')
when 'progNote'
# Combine entry with @props + key
ProgNoteContainer(_.extend entry.toObject(), @props, {
key: entry.get('id')
})
when 'globalEvent'
GlobalEventView({
key: entry.get('id')
globalEvent: entry.get('globalEvent')
programsById: @props.programsById
eventTypes: @props.eventTypes
})
else
throw new Error "Unknown historyEntries entryType: \"#{entry.get('entryType')}\""
)
)
ProgNoteContainer = React.createFactory React.createClass
displayName: 'ProgNoteContainer'
mixins: [React.addons.PureRenderMixin]
render: ->
{isEditing, filteredProgNote, progEvents, globalEvents, dataTypeFilter} = @props
progNote = @props.progNoteHistory.last()
progNoteId = progNote.get('id')
firstProgNoteRev = @props.progNoteHistory.first()
userProgramId = firstProgNoteRev.get('authorProgramId')
userProgram = @props.programsById.get(userProgramId) or Imm.Map()
# TODO: Refactor to extended props
if progNote.get('status') is 'cancelled'
return CancelledProgNoteView({
progNoteHistory: @props.progNoteHistory
filteredProgNote
dataTypeFilter
attachments: @props.attachments
progEvents
globalEvents
eventTypes: @props.eventTypes
clientFile: @props.clientFile
userProgram
planTargetsById: @props.planTargetsById
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updatePlanTargetNotes: @props.updatePlanTargetNotes
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
Assert.equal progNote.get('status'), 'default'
switch progNote.get('type')
when 'basic'
QuickNoteView({
progNote
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
userProgram
clientFile: @props.clientFile
dataTypeFilter
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
progNote
filteredProgNote
dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents
globalEvents
userProgram
planTargetsById: @props.planTargetsById
eventTypes: @props.eventTypes
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
setEditingProgNoteId: @props.setEditingProgNoteId
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
isReadOnly: @props.isReadOnly
isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateBasicUnitNotes: @props.updateBasicUnitNotes
updateBasicMetric: @props.updateBasicMetric
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
QuickNoteView = React.createFactory React.createClass
displayName: 'QuickNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Don't render anything if only events are shown
if dataTypeFilter is 'events' and not isEditing
return null
progNote = if isEditing then @props.transientData.get('progNote') else @props.progNote
if @props.attachments?
attachmentText = " " + @props.attachments.get('filename')
R.div({
id: "entry-#{progNote.get('id')}"
className: [
'entry basic progNote'
'isEditing' if isEditing
].join ' '
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'notes'},
R.div({onClick: @_selectQuickNote},
(if isEditing
ExpandingTextArea({
value: progNote.get('notes')
onChange: @props.updateQuickNotes
})
else
renderLineBreaks progNote.get('notes')
)
)
(@props.attachments.map (attachment) =>
{id, filename} = attachment.toObject()
fileExtension = Path.extname filename
R.a({
key: id
className: 'attachment'
onClick: @_openAttachment.bind null, attachment
},
FaIcon(fileExtension)
' '
filename
)
)
)
)
_openAttachment: (attachment) ->
attachmentId = attachment.get('id')
clientFileId = @props.clientFile.get('id')
global.ActiveSession.persist.attachments.readLatestRevisions clientFileId, attachmentId, 1, (err, results) ->
if err
if err instanceof Persist.IOError
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
attachment = results.first()
encodedData = attachment.get('encodedData')
filename = attachment.get('filename')
if filename?
# Absolute path required for windows
filepath = Path.join process.cwd(), Config.backend.dataDirectory, '_tmp', filename
file = Buffer.from(encodedData, 'base64')
# TODO cleanup file...
Fs.writeFile filepath, file, (err) ->
if err
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
nw.Shell.openItem filepath
_selectQuickNote: ->
@props.setSelectedItem Imm.fromJS {
type: 'quickNote'
progNoteId: @props.progNote.get('id')
}
ProgNoteView = React.createFactory React.createClass
displayName: 'ProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{isEditing, dataTypeFilter} = @props
# Use transient data when isEditing
progNote = if isEditing then @props.transientData.get('progNote') else @props.filteredProgNote
progEvents = if isEditing then @props.transientData.get('progEvents') else @props.progEvents
R.div({
id: "entry-#{progNote.get('id')}"
className: 'entry full progNote'
},
EntryHeader({
revisionHistory: @props.progNoteHistory
userProgram: @props.userProgram
isReadOnly: @props.isReadOnly
progNote: @props.progNote
filteredProgNote: @props.filteredProgNote
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
clientFile: @props.clientFile
isEditing
startRevisingProgNote: @props.startRevisingProgNote
selectProgNote: @props.selectProgNote
})
R.div({className: 'progNoteList'},
(progNote.get('units').map (unit) =>
unitId = unit.get 'id'
# TODO: Make these into components
(switch unit.get('type')
when 'basic'
if unit.get('notes')
R.div({
className: [
'basic unit'
"unitId-#{unitId}"
'isEditing' if isEditing
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
onClick: @_selectBasicUnit.bind null, unit
},
R.h3({}, unit.get('name'))
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: unit.get('notes')
onChange: @props.updateBasicUnitNotes.bind null, unitId
})
else
if unit.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks unit.get('notes')
)
else
renderLineBreaks unit.get('notes')
)
)
(unless unit.get('metrics').isEmpty()
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: isEditing
key: metric.PI:KEY:<KEY>END_PI('id')
name: metric.get('name')
definition: metric.get('definition')
onFocus: @_selectBasicUnit.bind null, unit
onChange: @props.updateBasicMetric.bind null, unitId, metricId
value: metric.get('value')
})
)
)
)
)
when 'plan'
R.div({
className: [
'plan unit'
showWhen dataTypeFilter isnt 'events' or isEditing
].join ' '
key: unitId
},
(unit.get('sections').map (section) =>
sectionId = section.get('id')
R.section({key: sectionId},
R.h2({}, section.get('name'))
(if section.get('targets').isEmpty()
R.div({className: 'empty'},
"This #{Term 'section'} is empty because
the #{Term 'client'} has no #{Term 'plan targets'}."
)
)
(section.get('targets').map (target) =>
planTargetsById = @props.planTargetsById.map (target) -> target.get('revisions').first()
targetId = target.get('id')
# Use the up-to-date name & description for header display
mostRecentTargetRevision = planTargetsById.get targetId
R.div({
key: targetId
className: [
'target'
"targetId-#{targetId}"
'isEditing' if isEditing
].join ' '
onClick: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
},
R.h3({}, target.get('name'))
(if isEditing or target.get('notes') isnt ''
R.div({className: 'notes'},
(if isEditing
ExpandingTextArea({
value: target.get('notes')
onChange: @props.updatePlanTargetNotes.bind(
null,
unitId, sectionId, targetId
)
})
else
# todo: make this nicer
if target.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks target.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks target.get('notes')
)
)
)
(unless target.get('metrics').isEmpty()
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
metricId = metric.get('id')
MetricWidget({
isEditable: isEditing
tooltipViewport: '#entriesListView'
onChange: @props.updatePlanTargetMetric.bind(
null,
unitId, sectionId, targetId, metricId
)
onFocus: @_selectPlanSectionTarget.bind(null, unit, section, mostRecentTargetRevision)
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
)
)
)
)
)
)
)
)
)
(if progNote.get('summary')
R.div({
className: [
'basic unit'
showWhen dataTypeFilter isnt 'events'
].join ' '
},
R.h3({}, "Shift Summary")
(if isEditing
ExpandingTextArea({
value: progNote.get('summary')
onChange: @props.updateShiftSummary
})
else
R.div({className: 'notes'},
renderLineBreaks progNote.get('summary')
)
)
)
)
(unless progEvents.isEmpty()
R.div({
className: [
'progEvents'
showWhen not dataTypeFilter or (dataTypeFilter isnt 'targets') or isEditing
].join ' '
},
# Don't need to show the Events header when we're only looking at events
(if dataTypeFilter isnt 'events' or isEditing
R.h3({}, Term 'Events')
)
(progEvents.map (progEvent, index) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'large'
progEvent
eventTypes: @props.eventTypes
isEditing
updateProgEvent: @props.updateProgEvent.bind null, index
})
)
)
)
)
)
_selectBasicUnit: (unit) ->
@props.setSelectedItem Imm.fromJS {
type: 'basicUnit'
unitId: unit.get('id')
unitName: unit.get('name')
progNoteId: @props.progNote.get('id')
}
_selectPlanSectionTarget: (unit, section, mostRecentTargetRevision) ->
@props.setSelectedItem Imm.fromJS {
type: 'planSectionTarget'
unitId: unit.get('id')
sectionId: section.get('id')
targetId: mostRecentTargetRevision.get('id')
targetName: mostRecentTargetRevision.get('name')
targetDescription: mostRecentTargetRevision.get('description')
progNoteId: @props.progNote.get('id')
}
CancelledProgNoteView = React.createFactory React.createClass
displayName: 'CancelledProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
isExpanded: false
}
render: ->
# Here, we assume that the latest revision was the one that
# changed the status. This assumption may become invalid
# when full prognote editing becomes supported.
latestRev = @props.progNoteHistory.last()
firstRev = @props.progNoteHistory.first()
statusChangeRev = latestRev
return R.div({
id: "entry-#{firstRev.get('id')}"
className: 'entry cancelStub'
},
R.button({
className: 'toggleDetails btn btn-xs btn-default'
onClick: @_toggleDetails
},
R.span({className: "#{showWhen not @state.isExpanded}"},
FaIcon 'chevron-down'
" Show details"
)
R.span({className: "#{showWhen @state.isExpanded}"},
FaIcon 'chevron-up'
" Hide details"
)
)
R.h3({},
"Discarded: "
formatTimestamp(firstRev.get('backdate') or firstRev.get('timestamp'))
" (late entry)" if firstRev.get('backdate')
),
R.div({className: "details #{showWhen @state.isExpanded}"},
R.h4({},
"Discarded by "
statusChangeRev.get('author')
" on "
formatTimestamp statusChangeRev.get('timestamp')
),
R.h4({}, "Reason for discarding:")
R.div({className: 'reason'},
renderLineBreaks latestRev.get('statusReason')
)
switch latestRev.get('type')
when 'basic'
QuickNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
progNoteHistory: @props.progNoteHistory
attachments: @props.attachments
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
userProgram: @props.userProgram
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updateQuickNotes: @props.updateQuickNotes
saveProgNoteRevision: @props.saveProgNoteRevision
})
when 'full'
ProgNoteView({
planTargetsById: @props.planTargetsById
progNote: @props.progNoteHistory.last()
filteredProgNote: @props.filteredProgNote
dataTypeFilter: @props.dataTypeFilter
progNoteHistory: @props.progNoteHistory
progEvents: @props.progEvents
globalEvents: @props.globalEvents
eventTypes: @props.eventTypes
userProgram: @props.userProgram
clientFile: @props.clientFile
setSelectedItem: @props.setSelectedItem
selectProgNote: @props.selectProgNote
isReadOnly: true
isEditing: @props.isEditing
transientData: @props.transientData
startRevisingProgNote: @props.startRevisingProgNote
cancelRevisingProgNote: @props.cancelRevisingProgNote
updatePlanTargetNotes: @props.updatePlanTargetNotes
updateShiftSummary: @props.updateShiftSummary
updatePlanTargetMetric: @props.updatePlanTargetMetric
updateProgEvent: @props.updateProgEvent
saveProgNoteRevision: @props.saveProgNoteRevision
})
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
)
)
_toggleDetails: (event) ->
@setState (s) -> {isExpanded: not s.isExpanded}
EntryHeader = React.createFactory React.createClass
displayName: 'EntryHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
getDefaultProps: -> {
progEvents: Imm.List()
globalEvents: Imm.List()
}
render: ->
{
userProgram
revisionHistory
isEditing
isReadOnly
progNote
filteredProgNote
progNoteHistory
progEvents
globalEvents
clientFile
startRevisingProgNote
selectProgNote
} = @props
userIsAuthor = progNote? and (progNote.get('author') is global.ActiveSession.userName)
canViewOptions = progNote? and not isEditing
canModify = userIsAuthor and not isReadOnly
hasRevisions = revisionHistory.size > 1
numberOfRevisions = revisionHistory.size - 1
hasMultipleRevisions = numberOfRevisions > 1
firstRevision = revisionHistory.first() # Use original revision's data
timestamp = (
firstRevision.get('startTimestamp') or
firstRevision.get('backdate') or
firstRevision.get('timestamp')
)
R.div({className: 'entryHeader'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp, @props.dateFormat)
(if firstRevision.get('backdate')
R.span({className: 'lateTimestamp'},
"(late entry)"
)
)
)
(if progNote? and hasRevisions
R.div({className: 'revisions'},
R.a({
className: 'selectProgNoteButton'
onClick: selectProgNote.bind null, progNote
},
"#{numberOfRevisions} revision#{if hasMultipleRevisions then 's' else ''}"
)
)
)
R.div({className: 'author'},
'by '
firstRevision.get('authorDisplayName') or firstRevision.get('author')
(if userProgram and not userProgram.isEmpty()
ColorKeyBubble({
colorKeyHex: userProgram.get('colorKeyHex')
popover: {
title: userProgram.get('name')
content: userProgram.get('description')
placement: 'left'
}
})
)
)
(if canViewOptions
R.div({className: 'options'},
B.DropdownButton({
id: "entryHeaderDropdown-#{progNote.get('id')}"
className: 'entryHeaderDropdown'
pullRight: true
noCaret: true
title: FaIcon('ellipsis-v', {className:'menuItemIcon'})
},
(if canModify
B.MenuItem({onClick: startRevisingProgNote.bind null, progNote, progEvents},
"Edit"
)
)
B.MenuItem({onClick: @_print.bind null, filteredProgNote or progNote, progEvents, clientFile},
"Print"
)
(if canModify
B.MenuItem({onClick: @_openCancelProgNoteDialog},
OpenDialogLink({
ref: 'cancelButton'
className: 'cancelNote'
dialog: CancelProgNoteDialog
progNote
progEvents
globalEvents
}, "Discard")
)
)
)
)
)
)
_openCancelProgNoteDialog: (event) ->
@refs.cancelButton.open(event)
_print: (progNote, progEvents, clientFile) ->
openWindow {
page: 'printPreview'
dataSet: JSON.stringify([
{
format: 'progNote'
data: progNote
progEvents
clientFile
}
])
}
GlobalEventView = React.createFactory React.createClass
displayName: 'GlobalEventView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
render: ->
{globalEvent} = @props
eventType = @props.eventTypes.find (eventType) ->
eventType.get('id') is globalEvent.get('typeId')
eventTypeName = if eventType then eventType.get('name') else null
programId = globalEvent.get('programId')
program = @props.programsById.get(programId) or Imm.Map()
timestamp = globalEvent.get('backdate') or globalEvent.get('timestamp')
startTimestamp = makeMoment globalEvent.get('startTimestamp')
endTimestamp = makeMoment globalEvent.get('endTimestamp')
# A full day is 12:00AM to 11:59PM
isFullDay = (
startTimestamp.isSame(startTimestamp.startOf 'day') and
endTimestamp.isSame(endTimestamp.endOf 'day')
)
return R.div({
id: "entry-#{globalEvent.get('id')}"
className: 'entry globalEventView'
},
EntryHeader({
revisionHistory: Imm.List [globalEvent]
userProgram: program
dateFormat: Config.dateFormat if isFullDay
})
R.h3({},
FaIcon('globe')
"Global Event: "
globalEvent.get('title') or eventTypeName or (
if globalEvent.get('description').length > 20
globalEvent.get('description').substring(0, 20) + "..."
else
globalEvent.get('description')
)
)
(if globalEvent.get('title') or eventTypeName and globalEvent.get('description')
R.p({}, globalEvent.get('description'))
)
(if globalEvent.get('endTimestamp') and not isFullDay
R.p({},
"From: "
formatTimestamp globalEvent.get('startTimestamp')
" until "
formatTimestamp globalEvent.get('endTimestamp')
)
)
R.p({},
"Reported: "
formatTimestamp timestamp
)
)
# Applies selected styles without having to re-render entire EntriesListView tree
InlineSelectedItemStyles = ({selectedItem}) ->
R.style({},
(switch selectedItem.get('type')
when 'planSectionTarget' # Target entry history
"""
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 6px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) h3 {
opacity: 1 !important;
}
div.target.targetId-#{selectedItem.get('targetId')}:not(.isEditing) .notes {
opacity: 1 !important;
}
"""
when 'quickNote' # QuickNote entry history
"""
div.basic.progNote:not(.isEditing) .notes > div {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'basicUnit' # General 'Notes' entry history (TODO: what > 1 basic unit?)
"""
div.basic.unit.unitId-#{selectedItem.get('unitId')}:not(.isEditing) {
padding-left: 20px !important;
padding-right: 0px !important;
border-left: 2px solid #3176aa !important;
color: #3176aa !important;
opacity: 1 !important;
}
"""
when 'progNote' # ProgNote revisions
"""
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions {
border-left: 2px solid #3176aa !important;
}
div.progNote#entry-#{selectedItem.get('progNoteId')}:not(.isEditing) .revisions a {
color: #3176aa !important;
opacity: 1 !important;
}
"""
else
throw new Error "Unknown selectedItem type #{selectedItem.get('type')} for InlineSelectedItemStyles"
)
)
filterEmptyProgNoteValues = (progNote) ->
# Don't bother filtering a quickNote (doesn't have units)
unless progNote.has 'units'
return progNote
progNoteUnits = progNote.get('units')
.map (unit) ->
if unit.get('type') is 'basic'
# Strip empty metric values
unitMetrics = unit.get('metrics').filterNot (metric) -> not metric.get('value')
return unit.set('metrics', unitMetrics)
else if unit.get('type') is 'plan'
unitSections = unit.get('sections')
.map (section) ->
sectionTargets = section.get('targets')
# Strip empty metric values
.map (target) ->
targetMetrics = target.get('metrics').filterNot (metric) -> not metric.get('value')
return target
.set('metrics', targetMetrics)
.remove('description') # We don't need target description snapshot displayed/searched
# Strip empty targets
.filterNot (target) ->
not target.get('notes') and target.get('metrics').isEmpty()
return section.set('targets', sectionTargets)
.filterNot (section) ->
section.get('targets').isEmpty()
return unit.set('sections', unitSections)
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
.filterNot (unit) ->
# Finally, strip any empty 'basic' units, or 'plan' units with 0 sections
if unit.get('type') is 'basic'
return not unit.get('notes') and unit.get('metrics').isEmpty()
else if unit.get('type') is 'plan'
return unit.get('sections').isEmpty()
else
throw new Error "Unknown progNote unit type: #{unit.get('type')}"
return progNote.set('units', progNoteUnits)
return ProgNotesTab
module.exports = {load}
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9978378415107727,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/internet/test-net-connect-timeout.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# This example attempts to time out before the connection is established
# https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8
# https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw
#
# TODO: how to do this without relying on the responses of specific sites?
common = require("../common")
net = require("net")
assert = require("assert")
start = new Date()
gotTimeout0 = false
gotTimeout1 = false
gotConnect0 = false
gotConnect1 = false
T = 100
# With DNS
socket0 = net.createConnection(9999, "google.com")
socket0.setTimeout T
socket0.on "timeout", ->
console.error "timeout"
gotTimeout0 = true
now = new Date()
assert.ok now - start < T + 500
socket0.destroy()
return
socket0.on "connect", ->
console.error "connect"
gotConnect0 = true
socket0.destroy()
return
# Without DNS
socket1 = net.createConnection(9999, "24.24.24.24")
socket1.setTimeout T
socket1.on "timeout", ->
console.error "timeout"
gotTimeout1 = true
now = new Date()
assert.ok now - start < T + 500
socket1.destroy()
return
socket1.on "connect", ->
console.error "connect"
gotConnect1 = true
socket1.destroy()
return
process.on "exit", ->
assert.ok gotTimeout0
assert.ok not gotConnect0
assert.ok gotTimeout1
assert.ok not gotConnect1
return
| 14209 | # 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.
# This example attempts to time out before the connection is established
# https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8
# https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw
#
# TODO: how to do this without relying on the responses of specific sites?
common = require("../common")
net = require("net")
assert = require("assert")
start = new Date()
gotTimeout0 = false
gotTimeout1 = false
gotConnect0 = false
gotConnect1 = false
T = 100
# With DNS
socket0 = net.createConnection(9999, "google.com")
socket0.setTimeout T
socket0.on "timeout", ->
console.error "timeout"
gotTimeout0 = true
now = new Date()
assert.ok now - start < T + 500
socket0.destroy()
return
socket0.on "connect", ->
console.error "connect"
gotConnect0 = true
socket0.destroy()
return
# Without DNS
socket1 = net.createConnection(9999, "24.24.24.24")
socket1.setTimeout T
socket1.on "timeout", ->
console.error "timeout"
gotTimeout1 = true
now = new Date()
assert.ok now - start < T + 500
socket1.destroy()
return
socket1.on "connect", ->
console.error "connect"
gotConnect1 = true
socket1.destroy()
return
process.on "exit", ->
assert.ok gotTimeout0
assert.ok not gotConnect0
assert.ok gotTimeout1
assert.ok not gotConnect1
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.
# This example attempts to time out before the connection is established
# https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8
# https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw
#
# TODO: how to do this without relying on the responses of specific sites?
common = require("../common")
net = require("net")
assert = require("assert")
start = new Date()
gotTimeout0 = false
gotTimeout1 = false
gotConnect0 = false
gotConnect1 = false
T = 100
# With DNS
socket0 = net.createConnection(9999, "google.com")
socket0.setTimeout T
socket0.on "timeout", ->
console.error "timeout"
gotTimeout0 = true
now = new Date()
assert.ok now - start < T + 500
socket0.destroy()
return
socket0.on "connect", ->
console.error "connect"
gotConnect0 = true
socket0.destroy()
return
# Without DNS
socket1 = net.createConnection(9999, "24.24.24.24")
socket1.setTimeout T
socket1.on "timeout", ->
console.error "timeout"
gotTimeout1 = true
now = new Date()
assert.ok now - start < T + 500
socket1.destroy()
return
socket1.on "connect", ->
console.error "connect"
gotConnect1 = true
socket1.destroy()
return
process.on "exit", ->
assert.ok gotTimeout0
assert.ok not gotConnect0
assert.ok gotTimeout1
assert.ok not gotConnect1
return
|
[
{
"context": "ieves all products owned by a given user.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass CurrentUserProd",
"end": 679,
"score": 0.9998679757118225,
"start": 667,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/router/routes/ajax/user/CurrentUserProductsRoute.coffee | qrefdev/qref | 0 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
async = require('async')
ProductManager = require('../../../../db/manager/ProductManager')
###
Service route that allows the retrieval of all products owned by a current user.
@example Service Methods
Request Format: application/json
Response Format: application/json
GET /services/ajax/user/products?token=:token
:token - (Required) A valid authentication token.
Retrieves all products owned by a given user.
@author Nathan Klick
@copyright QRef 2012
###
class CurrentUserProductsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/products' }, { method: 'GET', path: '/products' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
UserAuth.userFromToken(token, (err, usr) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
if not usr?
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
query = db.UserProduct.find()
query = query.where('user').equals(usr._id).populate('product')
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.UserProduct.where('user')
.equals(usr._id)
.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
arrProducts = []
for uProd in arrObjs
arrProducts.push(uProd.product.toObject())
mgr = new ProductManager()
mgr.expandAll(arrProducts, (err, eArrProducts) ->
if err?
resp.failure(err, 500)
res.json(resp, 200)
return
resp.addRecords(eArrProducts)
resp.setTotal(count)
res.json(resp, 200)
)
# async.forEach(arrObjs,
# (item, callback) ->
# currProd = item.product.toObject()
#
# db.AircraftChecklist.findById(currProd.aircraftChecklist)
# .exec((err, chk) ->
# if err?
# callback(err)
#
# if not chk?
# callback('Not Found')
#
# chk = chk.toObject()
# currProd.aircraftChecklist = chk
#
# async.parallel([
# (cb) ->
# db.AircraftManufacturer.findById(chk.manufacturer)
# .exec((err, mfr) ->
# if err?
# cb(err)
# if not mfr?
# cb('Not Found')
#
# chk.manufacturer = mfr.toObject()
# cb(null)
# )
# ,
# (cb) ->
# db.AircraftModel.findById(chk.model)
# .exec((err, mdl) ->
# if err?
# cb(err)
# if not mdl?
# cb('Not Found')
#
# chk.model = mdl.toObject()
# cb(null)
# )
# ],
# (err, results) ->
#
# arrProducts.push(currProd)
# callback(null)
# )
#
# )
# ,
# (err) ->
# if err?
# resp.failure(err, 500)
# res.json(resp, 200)
# return
#
# resp.addRecords(arrProducts)
# resp.setTotal(count)
# res.json(resp, 200)
# )
)
)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Forbidden', 403)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token?)
true
else
false
module.exports = new CurrentUserProductsRoute() | 194477 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
async = require('async')
ProductManager = require('../../../../db/manager/ProductManager')
###
Service route that allows the retrieval of all products owned by a current user.
@example Service Methods
Request Format: application/json
Response Format: application/json
GET /services/ajax/user/products?token=:token
:token - (Required) A valid authentication token.
Retrieves all products owned by a given user.
@author <NAME>
@copyright QRef 2012
###
class CurrentUserProductsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/products' }, { method: 'GET', path: '/products' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
UserAuth.userFromToken(token, (err, usr) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
if not usr?
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
query = db.UserProduct.find()
query = query.where('user').equals(usr._id).populate('product')
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.UserProduct.where('user')
.equals(usr._id)
.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
arrProducts = []
for uProd in arrObjs
arrProducts.push(uProd.product.toObject())
mgr = new ProductManager()
mgr.expandAll(arrProducts, (err, eArrProducts) ->
if err?
resp.failure(err, 500)
res.json(resp, 200)
return
resp.addRecords(eArrProducts)
resp.setTotal(count)
res.json(resp, 200)
)
# async.forEach(arrObjs,
# (item, callback) ->
# currProd = item.product.toObject()
#
# db.AircraftChecklist.findById(currProd.aircraftChecklist)
# .exec((err, chk) ->
# if err?
# callback(err)
#
# if not chk?
# callback('Not Found')
#
# chk = chk.toObject()
# currProd.aircraftChecklist = chk
#
# async.parallel([
# (cb) ->
# db.AircraftManufacturer.findById(chk.manufacturer)
# .exec((err, mfr) ->
# if err?
# cb(err)
# if not mfr?
# cb('Not Found')
#
# chk.manufacturer = mfr.toObject()
# cb(null)
# )
# ,
# (cb) ->
# db.AircraftModel.findById(chk.model)
# .exec((err, mdl) ->
# if err?
# cb(err)
# if not mdl?
# cb('Not Found')
#
# chk.model = mdl.toObject()
# cb(null)
# )
# ],
# (err, results) ->
#
# arrProducts.push(currProd)
# callback(null)
# )
#
# )
# ,
# (err) ->
# if err?
# resp.failure(err, 500)
# res.json(resp, 200)
# return
#
# resp.addRecords(arrProducts)
# resp.setTotal(count)
# res.json(resp, 200)
# )
)
)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Forbidden', 403)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token?)
true
else
false
module.exports = new CurrentUserProductsRoute() | true | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
async = require('async')
ProductManager = require('../../../../db/manager/ProductManager')
###
Service route that allows the retrieval of all products owned by a current user.
@example Service Methods
Request Format: application/json
Response Format: application/json
GET /services/ajax/user/products?token=:token
:token - (Required) A valid authentication token.
Retrieves all products owned by a given user.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
###
class CurrentUserProductsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/products' }, { method: 'GET', path: '/products' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
UserAuth.userFromToken(token, (err, usr) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
if not usr?
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
query = db.UserProduct.find()
query = query.where('user').equals(usr._id).populate('product')
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.UserProduct.where('user')
.equals(usr._id)
.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
arrProducts = []
for uProd in arrObjs
arrProducts.push(uProd.product.toObject())
mgr = new ProductManager()
mgr.expandAll(arrProducts, (err, eArrProducts) ->
if err?
resp.failure(err, 500)
res.json(resp, 200)
return
resp.addRecords(eArrProducts)
resp.setTotal(count)
res.json(resp, 200)
)
# async.forEach(arrObjs,
# (item, callback) ->
# currProd = item.product.toObject()
#
# db.AircraftChecklist.findById(currProd.aircraftChecklist)
# .exec((err, chk) ->
# if err?
# callback(err)
#
# if not chk?
# callback('Not Found')
#
# chk = chk.toObject()
# currProd.aircraftChecklist = chk
#
# async.parallel([
# (cb) ->
# db.AircraftManufacturer.findById(chk.manufacturer)
# .exec((err, mfr) ->
# if err?
# cb(err)
# if not mfr?
# cb('Not Found')
#
# chk.manufacturer = mfr.toObject()
# cb(null)
# )
# ,
# (cb) ->
# db.AircraftModel.findById(chk.model)
# .exec((err, mdl) ->
# if err?
# cb(err)
# if not mdl?
# cb('Not Found')
#
# chk.model = mdl.toObject()
# cb(null)
# )
# ],
# (err, results) ->
#
# arrProducts.push(currProd)
# callback(null)
# )
#
# )
# ,
# (err) ->
# if err?
# resp.failure(err, 500)
# res.json(resp, 200)
# return
#
# resp.addRecords(arrProducts)
# resp.setTotal(count)
# res.json(resp, 200)
# )
)
)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Forbidden', 403)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token?)
true
else
false
module.exports = new CurrentUserProductsRoute() |
[
{
"context": "n/common/constants')\n\nmodule.exports = {\n name: 'ひよこ'\n character: 'character.hiyoko'\n base:\n str:",
"end": 202,
"score": 0.9995914697647095,
"start": 199,
"tag": "NAME",
"value": "ひよこ"
}
] | src/data/001/actor/001.coffee | fukuyama/tmlib-rpg | 0 | path = require 'path'
base = path.dirname module.filename
require path.relative(base,'./src/main/common/utils')
require path.relative(base,'./src/main/common/constants')
module.exports = {
name: 'ひよこ'
character: 'character.hiyoko'
base:
str: 10 # ちから
vit: 10 # たいりょく
dex: 10 # きようさ
agi: 10 # すばやさ
int: 10 # かしこさ
sen: 10 # かんせい
luc: 10 # うんのよさ
cha: 10 # みりょく
basehp: 10 # HP
basemp: 10 # MP
}
| 125188 | path = require 'path'
base = path.dirname module.filename
require path.relative(base,'./src/main/common/utils')
require path.relative(base,'./src/main/common/constants')
module.exports = {
name: '<NAME>'
character: 'character.hiyoko'
base:
str: 10 # ちから
vit: 10 # たいりょく
dex: 10 # きようさ
agi: 10 # すばやさ
int: 10 # かしこさ
sen: 10 # かんせい
luc: 10 # うんのよさ
cha: 10 # みりょく
basehp: 10 # HP
basemp: 10 # MP
}
| true | path = require 'path'
base = path.dirname module.filename
require path.relative(base,'./src/main/common/utils')
require path.relative(base,'./src/main/common/constants')
module.exports = {
name: 'PI:NAME:<NAME>END_PI'
character: 'character.hiyoko'
base:
str: 10 # ちから
vit: 10 # たいりょく
dex: 10 # きようさ
agi: 10 # すばやさ
int: 10 # かしこさ
sen: 10 # かんせい
luc: 10 # うんのよさ
cha: 10 # みりょく
basehp: 10 # HP
basemp: 10 # MP
}
|
[
{
"context": "****\n The MIT License (MIT)\n\n Copyright (c) 2013 Shaun Springer\n\n Permission is hereby granted, free of charge, ",
"end": 151,
"score": 0.9998868107795715,
"start": 137,
"tag": "NAME",
"value": "Shaun Springer"
},
{
"context": "f Collections, Models, and Controllers\n#\n# @author Shaun Springer\n# @copyright Shaun Springer\n# @version 0.1.2\n#\n#\n",
"end": 1407,
"score": 0.9998930096626282,
"start": 1393,
"tag": "NAME",
"value": "Shaun Springer"
},
{
"context": "ontrollers\n#\n# @author Shaun Springer\n# @copyright Shaun Springer\n# @version 0.1.2\n#\n#\nclass Wraith\n # Version num",
"end": 1435,
"score": 0.9996145367622375,
"start": 1421,
"tag": "NAME",
"value": "Shaun Springer"
}
] | src/wraith.coffee | ShaunSpringer/Wraith | 2 | ###
**************************************************************************************
The MIT License (MIT)
Copyright (c) 2013 Shaun Springer
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.
**************************************************************************************
###
#
# Global Wraith Object
# Contains a list of Collections, Models, and Controllers
#
# @author Shaun Springer
# @copyright Shaun Springer
# @version 0.1.2
#
#
class Wraith
# Version number
@version: '0.1.2'
# Essentially allow logging or not
@DEBUG: false
# List of acceptable UIEVENTS
@UIEVENTS: ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'scroll', 'keypress', 'keyup', 'keydown', 'change', 'blur', 'focus', 'submit']
# List of controllers keyed by id
@controllers: {}
# List of models keyed by id
@models: {}
# The global validators object
@Validators: {}
#
# Logs to the console if DEBUG is set to true
#
@log: (args ...) -> if Wraith.DEBUG then console.log args ...
#
# Checks to see if a given object
# is a funciton.
# @param [Object] obj The object to test
#
@isFunction: (obj) -> Object.prototype.toString.call(obj) == '[object Function]'
#
# Generates a UID at the desired length
# @param [Number] length Desired length of the UID
# @param [String] prefix A prefix to append to the UID
#
@uniqueId: (length = 16, prefix = "") ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
id = prefix + id
# Export Wraith
root = exports ? @
root.Wraith = Wraith
| 142601 | ###
**************************************************************************************
The MIT License (MIT)
Copyright (c) 2013 <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.
**************************************************************************************
###
#
# Global Wraith Object
# Contains a list of Collections, Models, and Controllers
#
# @author <NAME>
# @copyright <NAME>
# @version 0.1.2
#
#
class Wraith
# Version number
@version: '0.1.2'
# Essentially allow logging or not
@DEBUG: false
# List of acceptable UIEVENTS
@UIEVENTS: ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'scroll', 'keypress', 'keyup', 'keydown', 'change', 'blur', 'focus', 'submit']
# List of controllers keyed by id
@controllers: {}
# List of models keyed by id
@models: {}
# The global validators object
@Validators: {}
#
# Logs to the console if DEBUG is set to true
#
@log: (args ...) -> if Wraith.DEBUG then console.log args ...
#
# Checks to see if a given object
# is a funciton.
# @param [Object] obj The object to test
#
@isFunction: (obj) -> Object.prototype.toString.call(obj) == '[object Function]'
#
# Generates a UID at the desired length
# @param [Number] length Desired length of the UID
# @param [String] prefix A prefix to append to the UID
#
@uniqueId: (length = 16, prefix = "") ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
id = prefix + id
# Export Wraith
root = exports ? @
root.Wraith = Wraith
| true | ###
**************************************************************************************
The MIT License (MIT)
Copyright (c) 2013 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.
**************************************************************************************
###
#
# Global Wraith Object
# Contains a list of Collections, Models, and Controllers
#
# @author PI:NAME:<NAME>END_PI
# @copyright PI:NAME:<NAME>END_PI
# @version 0.1.2
#
#
class Wraith
# Version number
@version: '0.1.2'
# Essentially allow logging or not
@DEBUG: false
# List of acceptable UIEVENTS
@UIEVENTS: ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'scroll', 'keypress', 'keyup', 'keydown', 'change', 'blur', 'focus', 'submit']
# List of controllers keyed by id
@controllers: {}
# List of models keyed by id
@models: {}
# The global validators object
@Validators: {}
#
# Logs to the console if DEBUG is set to true
#
@log: (args ...) -> if Wraith.DEBUG then console.log args ...
#
# Checks to see if a given object
# is a funciton.
# @param [Object] obj The object to test
#
@isFunction: (obj) -> Object.prototype.toString.call(obj) == '[object Function]'
#
# Generates a UID at the desired length
# @param [Number] length Desired length of the UID
# @param [String] prefix A prefix to append to the UID
#
@uniqueId: (length = 16, prefix = "") ->
id = ""
id += Math.random().toString(36).substr(2) while id.length < length
id.substr 0, length
id = prefix + id
# Export Wraith
root = exports ? @
root.Wraith = Wraith
|
[
{
"context": "ocalhost'\n secure: true\n auth:\n user: 'protothril@localhost'\n pass: 'secret'\n appEmail: 'protothril@loc",
"end": 212,
"score": 0.8069208860397339,
"start": 192,
"tag": "EMAIL",
"value": "protothril@localhost"
},
{
"context": ":\n user: 'protothril@localhost'\n pass: 'secret'\n appEmail: 'protothril@localhost'\n frontend: '",
"end": 233,
"score": 0.9994378685951233,
"start": 227,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "hril@localhost'\n pass: 'secret'\n appEmail: 'protothril@localhost'\n frontend: 'localhost:9000/?'\n",
"end": 268,
"score": 0.9583412408828735,
"start": 248,
"tag": "EMAIL",
"value": "protothril@localhost"
}
] | server/coffee/conf.default.coffee | softwarerero/protothril | 0 | module.exports =
appName: 'protothril'
debugPort: 3017
elasticsearch:
host: 'localhost:9200'
index: 'users'
smtp:
host: 'localhost'
secure: true
auth:
user: 'protothril@localhost'
pass: 'secret'
appEmail: 'protothril@localhost'
frontend: 'localhost:9000/?'
| 105822 | module.exports =
appName: 'protothril'
debugPort: 3017
elasticsearch:
host: 'localhost:9200'
index: 'users'
smtp:
host: 'localhost'
secure: true
auth:
user: '<EMAIL>'
pass: '<PASSWORD>'
appEmail: '<EMAIL>'
frontend: 'localhost:9000/?'
| true | module.exports =
appName: 'protothril'
debugPort: 3017
elasticsearch:
host: 'localhost:9200'
index: 'users'
smtp:
host: 'localhost'
secure: true
auth:
user: 'PI:EMAIL:<EMAIL>END_PI'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
appEmail: 'PI:EMAIL:<EMAIL>END_PI'
frontend: 'localhost:9000/?'
|
[
{
"context": "ccount_title: \"Obnovení účtu\"\n send_password: \"Zaslat nové heslo\"\n\n signup:\n create_account_title: \"Vytvořit ú",
"end": 1194,
"score": 0.9289093017578125,
"start": 1177,
"tag": "PASSWORD",
"value": "Zaslat nové heslo"
},
{
"context": "k\"\n wizard_tab: \"Kouzelník\"\n password_tab: \"Heslo\"\n emails_tab: \"Emaily\"\n# admin: \"Admin\"\n ",
"end": 4608,
"score": 0.9955432415008545,
"start": 4603,
"tag": "PASSWORD",
"value": "Heslo"
},
{
"context": " \"Barva Kouzelníkova oblečení\"\n new_password: \"Nové heslo\"\n new_password_verify: \"Potvrdit\"\n email_su",
"end": 4969,
"score": 0.9992459416389465,
"start": 4959,
"tag": "PASSWORD",
"value": "Nové heslo"
},
{
"context": "_password: \"Nové heslo\"\n new_password_verify: \"Potvrdit\"\n email_subscriptions: \"Doručovat emailem\"\n ",
"end": 5005,
"score": 0.9992782473564148,
"start": 4997,
"tag": "PASSWORD",
"value": "Potvrdit"
},
{
"context": " saved: \"Změny uloženy\"\n password_mismatch: \"Hesla nesouhlasí.\"\n\n account_profile:\n edit_settings: \"Editova",
"end": 5665,
"score": 0.9716956615447998,
"start": 5649,
"tag": "PASSWORD",
"value": "Hesla nesouhlasí"
},
{
"context": " or: \"nebo\"\n email: \"Email\"\n# password: \"Password\"\n message: \"Zpráva\"\n# code: \"Code\"\n# lad",
"end": 13396,
"score": 0.9994435906410217,
"start": 13388,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "rogramováním.\"\n why_paragraph_1: \"Při vytváření Skritteru neznal George základy programování a byl neustále",
"end": 14096,
"score": 0.9089819192886353,
"start": 14087,
"tag": "NAME",
"value": "Skritteru"
},
{
"context": " why_paragraph_1: \"Při vytváření Skritteru neznal George základy programování a byl neustále frustrován sv",
"end": 14110,
"score": 0.7159677743911743,
"start": 14104,
"tag": "NAME",
"value": "George"
},
{
"context": "stejný problém, který jsme již vyřešili při tvorbě Skitteru: lidé se pokouší učit na pomalých, intenzivních ",
"end": 14620,
"score": 0.9965506196022034,
"start": 14613,
"tag": "NAME",
"value": "Skitter"
},
{
"context": "rový architekt, kouzelník v kuchyni i pán financí. Scott je v týmu pan rozumný.\"\n nick_description: \"Pr",
"end": 15837,
"score": 0.9316325187683105,
"start": 15832,
"tag": "NAME",
"value": "Scott"
},
{
"context": "elník, excentrický motivační mág i experimentátor. Nick by mohl dělat de-facto cokoliv, ale zvolil si vyt",
"end": 15959,
"score": 0.9291670918464661,
"start": 15955,
"tag": "NAME",
"value": "Nick"
},
{
"context": " administrátor a král podsvětí technického zázemí. Michael udržuje naše servery online.\"\n# glen_descripti",
"end": 16283,
"score": 0.9284316897392273,
"start": 16276,
"tag": "NAME",
"value": "Michael"
},
{
"context": "edující plán monetizace:\"\n recruitment_title: \"Nábor\"\n recruitment_description_prefix: \"Zde na Code",
"end": 18390,
"score": 0.9275569319725037,
"start": 18385,
"tag": "NAME",
"value": "Nábor"
},
{
"context": " nám přidáte!\"\n introduction_desc_signature: \"- Nick, George, Scott, Michael a Jeremy\"\n alert_account_messa",
"end": 23171,
"score": 0.9477787613868713,
"start": 23159,
"tag": "NAME",
"value": "Nick, George"
},
{
"context": "\n introduction_desc_signature: \"- Nick, George, Scott, Michael a Jeremy\"\n alert_account_message_intr",
"end": 23178,
"score": 0.9962148666381836,
"start": 23173,
"tag": "NAME",
"value": "Scott"
},
{
"context": "troduction_desc_signature: \"- Nick, George, Scott, Michael a Jeremy\"\n alert_account_message_intro: \"Vítejte",
"end": 23189,
"score": 0.7865042090415955,
"start": 23180,
"tag": "NAME",
"value": "Michael a"
},
{
"context": "_desc_signature: \"- Nick, George, Scott, Michael a Jeremy\"\n alert_account_message_intro: \"Vítejte!\"\n ",
"end": 23196,
"score": 0.9605004787445068,
"start": 23190,
"tag": "NAME",
"value": "Jeremy"
},
{
"context": "rer_join_pref: \"Buďto se spojte (nebo si najděte!) Dobrodruha a pracujte s ním, nebo zaškrtněte políčko níže a ",
"end": 28348,
"score": 0.9945219159126282,
"start": 28338,
"tag": "NAME",
"value": "Dobrodruha"
},
{
"context": "er: \"Dozvědět se více o tom, jak se stát statečným Dobrodruhem\"\n adventurer_subscribe_desc: \"Dostávat emai",
"end": 28741,
"score": 0.9963826537132263,
"start": 28733,
"tag": "NAME",
"value": "Dobrodru"
},
{
"context": "ription: \"(Tvůrce úrovní)\"\n adventurer_title: \"Dobrodruh\"\n adventurer_title_description: \"(Tester úrovn",
"end": 35226,
"score": 0.9910785555839539,
"start": 35217,
"tag": "NAME",
"value": "Dobrodruh"
},
{
"context": "escription: \"(Tester úrovní)\"\n scribe_title: \"Pisálek\"\n scribe_title_description: \"(Editor článků)\"\n",
"end": 35306,
"score": 0.653369665145874,
"start": 35300,
"tag": "NAME",
"value": "isálek"
},
{
"context": "summary_matches: \"Matches - \"\n# summary_wins: \" Wins, \"\n# summary_losses: \" Losses\"\n# rank_no_cod",
"end": 36158,
"score": 0.9991009831428528,
"start": 36154,
"tag": "NAME",
"value": "Wins"
}
] | app/locale/cs.coffee | individuo7/codecombat | 1 | module.exports = nativeDescription: "čeština", englishDescription: "Czech", translation:
common:
loading: "Načítání..."
saving: "Ukládání..."
sending: "Odesílání..."
cancel: "Zrušit"
save: "Uložit"
delay_1_sec: "1 vteřina"
delay_3_sec: "3 vteřiny"
delay_5_sec: "5 vteřin"
manual: "Ručně"
fork: "Klonovat"
play: "Přehrát"
modal:
close: "Zavřít"
okay: "Budiž"
not_found:
page_not_found: "Stránka nenalezena"
nav:
play: "Úrovně"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Domů"
contribute: "Přispívat"
legal: "Licence"
about: "O programu"
contact: "Kontakt"
twitter_follow: "Sledovat na twitteru"
employers: "Pro zaměstnavatele"
versions:
save_version_title: "Uložit novou Verzi"
new_major_version: "Nová hlavní Verze"
cla_prefix: "Před uložením musíte souhlasit s"
cla_url: "licencí"
cla_suffix: "."
cla_agree: "SOUHLASÍM"
login:
sign_up: "Vytvořit účet"
log_in: "Přihlásit"
log_out: "Odhlásit"
recover: "obnovit účet"
recover:
recover_account_title: "Obnovení účtu"
send_password: "Zaslat nové heslo"
signup:
create_account_title: "Vytvořit účet k uložení úrovně"
description: "Registrace je zdarma. Vyplňte pouze několik údajů:"
email_announcements: "Dostávat novinky emailem"
coppa: "starší 13 let nebo nejste z USA "
coppa_why: "(Proč?)"
creating: "Vytvářím účet..."
sign_up: "Přihlášení"
log_in: "zadejte vaše heslo"
home:
slogan: "Naučte se programování JavaScriptu při hraní více-hráčové programovací hry."
no_ie: "Omlouváme se, ale CodeCombat boužel nefunguje v Internet Exploreru 9 nebo starším."
no_mobile: "CodeCombat není navržen pro mobilní zařízení a nemusí fungovat správně!"
play: "Hrát"
# old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!"
# old_browser_suffix: "You can try anyway, but it probably won't work."
# campaign: "Campaign"
# for_beginners: "For Beginners"
# multiplayer: "Multiplayer"
# for_developers: "For Developers"
play:
choose_your_level: "Zvolte si úroveň"
adventurer_prefix: "Můžete přejít do dalších úrovní, nebo debatovat o úrovních na "
adventurer_forum: "fóru Dobrodruhů"
adventurer_suffix: "."
campaign_beginner: "Začátečnická úroveň"
campaign_beginner_description: "...ve které se naučíte kouzla programování."
campaign_dev: "Náhodné težší úrovně"
campaign_dev_description: "...ve kterých se dozvíte více o prostředí při plnění těžších úkolů."
campaign_multiplayer: "Multiplayer Aréna"
campaign_multiplayer_description: "...ve které programujete proti jiným hráčům."
campaign_player_created: "Uživatelsky vytvořené úrovně"
campaign_player_created_description: "...ve kterých bojujete proti kreativitě ostatních <a href=\"/contribute#artisan\">Zdatných Kouzelníků</a>."
level_difficulty: "Obtížnost: "
# play_as: "Play As"
# spectate: "Spectate"
contact:
contact_us: "Konktujte CodeCombat"
welcome: "Rádi od vás uslyšíme. Použijte tento formulář pro odeslání emailu. "
contribute_prefix: "Chcete-li nám přispět, prohlédněte si naši stránku "
contribute_page: "přispivatelů"
contribute_suffix: "!"
forum_prefix: "Pro ostatní veřejné věci, prosím zkuste "
forum_page: "naše fórum"
forum_suffix: "."
send: "Odeslat připomínku"
diplomat_suggestion:
title: "Pomozte přeložit CodeCombat!"
sub_heading: "Potřebujeme vaše dovednosti."
pitch_body: "Přestože vyvíjíme CodeCombat v angličtině, máme spoustu hráčů z celého světa a mnozí z nich by si rádi zahráli česky, neboť anglicky neumí. Pokud anglicky umíte, přihlaste se prosím jako Diplomat a pomozte nám v překladu webu i jednotlivých úrovní."
missing_translations: "Dokud nebude vše přeloženo, bude se vám na zatím nepřeložených místech zobrazovat text anglicky."
learn_more: "Dozvědět se více o Diplomatech"
subscribe_as_diplomat: "Přihlásit se jako Diplomat"
wizard_settings:
title: "Nastavení Kouzelníka"
customize_avatar: "Upravte vás Avatar"
# clothes: "Clothes"
# trim: "Trim"
# cloud: "Cloud"
# spell: "Spell"
# boots: "Boots"
# hue: "Hue"
# saturation: "Saturation"
# lightness: "Lightness"
account_settings:
title: "Nastavení účtu"
not_logged_in: "Přihlaste se, nebo vytvořte si účet pro uložení nastavení."
autosave: "Automatické ukládání změn"
me_tab: "O mne"
picture_tab: "Obrázek"
wizard_tab: "Kouzelník"
password_tab: "Heslo"
emails_tab: "Emaily"
# admin: "Admin"
gravatar_select: "Zvolte kterou Gravatar fotografii použít"
gravatar_add_photos: "Přidat náhledy a fotografie do Gravatar účtu pro zvolení obrázku"
gravatar_add_more_photos: "Přidat do vašeho Gravatar účtu další fotografie."
wizard_color: "Barva Kouzelníkova oblečení"
new_password: "Nové heslo"
new_password_verify: "Potvrdit"
email_subscriptions: "Doručovat emailem"
email_announcements: "Oznámení"
# email_notifications: "Notifications"
email_notifications_description: "Zasílat na váš účet opakovaná oznámení."
email_announcements_description: "Zasílat emaily o posledních novinkách a o postupu ve vývoji CodeCombat."
contributor_emails: "Emaily pro přispívatele"
contribute_prefix: "Hledáme další přispívatele! Čtěte prosím "
contribute_page: "stránku přispívatelům"
contribute_suffix: " pro více informací."
email_toggle: "Zvolit vše"
error_saving: "Chyba při ukládání"
saved: "Změny uloženy"
password_mismatch: "Hesla nesouhlasí."
account_profile:
edit_settings: "Editovat Nastavení"
profile_for_prefix: "Profil pro "
# profile_for_suffix: ""
profile: "Profil"
user_not_found: "Uživatel nenalezen. Zkontrolujte adresu URL?"
gravatar_not_found_mine: "Nenalezli jsme profil asociovaný s:"
gravatar_not_found_email_suffix: "."
gravatar_signup_prefix: "Přihlásit se "
gravatar_signup_suffix: " k nastavení!"
gravatar_not_found_other: "Bohužel, neexistuje profil asociovaný s touto emailovou adresou."
gravatar_contact: "Kontakt"
gravatar_websites: "Weby"
gravatar_accounts: "Jak zobrazeno na"
gravatar_profile_link: "Účet Gravatar"
play_level:
level_load_error: "Úroveň se nepodařilo otevřít: "
done: "Hotovo"
grid: "Mřížka"
customize_wizard: "Upravit Kouzelníka"
home: "Domů"
guide: "Průvodce"
multiplayer: "Multiplayer"
restart: "Restartovat"
goals: "Cíl"
action_timeline: "Časová osa"
click_to_select: "Vyberte kliknutím."
reload_title: "Znovunačíst veškerý kód?"
reload_really: "Opravdu chcete resetovat tuto úroveň do počátečního stavu?"
reload_confirm: "Znovu načíst vše"
# victory_title_prefix: ""
victory_title_suffix: " Hotovo"
victory_sign_up: "Přihlásit se pro uložení postupu"
victory_sign_up_poke: "Chcete uložit váš kód? Vytvořte si účet zdarma!"
victory_rate_the_level: "Ohodnoťte tuto úroveň: "
# victory_rank_my_game: "Rank My Game"
# victory_ranking_game: "Submitting..."
# victory_return_to_ladder: "Return to Ladder"
victory_play_next_level: "Hrát další úroveň"
victory_go_home: "Přejít domů"
victory_review: "Připomínky!"
victory_hour_of_code_done: "Skončili jste?"
victory_hour_of_code_done_yes: "Ano, pro dnešek jsem skončil!"
multiplayer_title: "Nastavení Multiplayeru"
multiplayer_link_description: "Sdílejte tento odkaz s lidmi, kteří se k vám mohou přidat ve hře."
multiplayer_hint_label: "Tip:"
multiplayer_hint: " Klikněte na odkaz pro jeho výběr, poté stiskněte ⌘-C nebo Ctrl-C pro kopírování odkazu."
multiplayer_coming_soon: "Další vlastnosti multiplayeru jsou na cestě!"
guide_title: "Průvodce"
tome_minion_spells: "Vaše oblíbená kouzla"
tome_read_only_spells: "Kouzla jen pro čtení"
tome_other_units: "Ostatní jednotky"
tome_cast_button_castable: "Spustit"
tome_cast_button_casting: "Spouštění"
tome_cast_button_cast: "Spustit Kouzlo"
tome_autocast_delay: "Prodleva Autospouštení"
tome_select_spell: "Zvolte Kouzlo"
tome_select_a_thang: "Zvolte někoho pro "
tome_available_spells: "Dostupná kouzla"
hud_continue: "Pokračovat (stiskněte shift-mezera)"
spell_saved: "Kouzlo uloženo"
# skip_tutorial: "Skip (esc)"
# editor_config: "Editor Config"
# editor_config_title: "Editor Configuration"
# editor_config_keybindings_label: "Key Bindings"
# editor_config_keybindings_default: "Default (Ace)"
# editor_config_keybindings_description: "Adds additional shortcuts known from the common editors."
# editor_config_invisibles_label: "Show Invisibles"
# editor_config_invisibles_description: "Displays invisibles such as spaces or tabs."
# editor_config_indentguides_label: "Show Indent Guides"
# editor_config_indentguides_description: "Displays vertical lines to see indentation better."
# editor_config_behaviors_label: "Smart Behaviors"
# editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes."
# loading_ready: "Ready!"
# tip_insert_positions: "Shift+Click a point on the map to insert it into the spell editor."
# tip_toggle_play: "Toggle play/paused with Ctrl+P."
# tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward."
# tip_guide_exists: "Click the guide at the top of the page for useful info."
# tip_open_source: "CodeCombat is 100% open source!"
# tip_beta_launch: "CodeCombat launched its beta in October, 2013."
# tip_js_beginning: "JavaScript is just the beginning."
# tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button."
# tip_baby_coders: "In the future, even babies will be Archmages."
# tip_morale_improves: "Loading will continue until morale improves."
# tip_all_species: "We believe in equal opportunities to learn programming for all species."
# tip_reticulating: "Reticulating spines."
# tip_harry: "Yer a Wizard, "
admin:
av_title: "Administrátorský pohled"
av_entities_sub_title: "Entity"
av_entities_users_url: "Uživatelé"
av_entities_active_instances_url: "Aktivní instance"
av_other_sub_title: "Ostatní"
av_other_debug_base_url: "Base (pro debugování base.jade)"
u_title: "Seznam uživatelů"
lg_title: "Poslední hry"
# clas: "CLAs"
editor:
main_title: "Editory CodeCombatu"
main_description: "Vytvořte vlastní úrovně, kampaně, jednotky a vzdělávací obsah. My vám poskytujeme všechny potřebné nástroje!"
article_title: "Editor článků"
article_description: "Napište články, které objasní hráčům koncepty programování využitelné v úrovních a kampaních."
thang_title: "Editor Thangů - objektů"
thang_description: "Vytvořte jednotky, definujte jejich logiku, vlastnosti, grafiku a zvuk. Momentálně jsou podporovány pouze importy vektorové grafiky exportované z Flashe."
level_title: "Editor úrovní"
level_description: "Zahrnuje pomůcky pro skriptování, nahrávání audia a tvorbu vlastní logiky pro vytvoření vlastních úrovní. Obsahuje vše, čeho využíváme k tvorbě úrovní my!"
security_notice: "Velké množství důležitých funkcí těchto editorů je standardně vypnuto. Jak postupem času vylepšujeme bezpečnost celého systému, jsou tyto funkce uvolňovány k veřejnému použití. Potřebujete-li některé funkce dříve, "
contact_us: "kontaktujte nás!"
hipchat_prefix: "Můžete nás také najít v naší"
hipchat_url: "HipChat diskusní místnosti."
# revert: "Revert"
# revert_models: "Revert Models"
level_some_options: "Volby?"
level_tab_thangs: "Thangy"
level_tab_scripts: "Skripty"
level_tab_settings: "Nastavení"
level_tab_components: "Komponenty"
level_tab_systems: "Systémy"
level_tab_thangs_title: "Současné Thangy"
level_tab_thangs_conditions: "Výchozí prostředí"
level_tab_thangs_add: "Přidat Thangy"
level_settings_title: "Nastavení"
level_component_tab_title: "Současné komponenty"
level_component_btn_new: "Vytvořit novou komponentu"
level_systems_tab_title: "Současné systémy"
level_systems_btn_new: "Vytvořit nový systém"
level_systems_btn_add: "Přidat systém"
level_components_title: "Zpět na všechny Thangy"
level_components_type: "Druh"
level_component_edit_title: "Editovat komponentu"
# level_component_config_schema: "Config Schema"
# level_component_settings: "Settings"
level_system_edit_title: "Editovat systém"
create_system_title: "Vytvořit nový systém"
new_component_title: "Vytvořit novou komponentu"
new_component_field_system: "Systém"
# new_article_title: "Create a New Article"
# new_thang_title: "Create a New Thang Type"
# new_level_title: "Create a New Level"
# article_search_title: "Search Articles Here"
# thang_search_title: "Search Thang Types Here"
# level_search_title: "Search Levels Here"
article:
edit_btn_preview: "Náhled"
edit_article_title: "Editovat článek"
general:
and: "a"
name: "Jméno"
body: "Tělo"
version: "Verze"
commit_msg: "Popisek ukládání"
# history: "History"
version_history_for: "Verze historie pro: "
# result: "Result"
results: "Výsledky"
description: "Popis"
or: "nebo"
email: "Email"
# password: "Password"
message: "Zpráva"
# code: "Code"
# ladder: "Ladder"
# when: "When"
# opponent: "Opponent"
# rank: "Rank"
# score: "Score"
# win: "Win"
# loss: "Loss"
# tie: "Tie"
# easy: "Easy"
# medium: "Medium"
# hard: "Hard"
about:
who_is_codecombat: "Kdo je CodeCombat?"
why_codecombat: "Proč CodeCombat?"
who_description_prefix: "společně přišli s projektem CodeCombat v roce 2013. V roce 2008 jsme vytvořili také "
who_description_suffix: ", jedničku mezi webovými a IOS aplikacemi pro učení psaní japonských a čínských znaků."
who_description_ending: "Nyní nastal čas pomoci lidem s programováním."
why_paragraph_1: "Při vytváření Skritteru neznal George základy programování a byl neustále frustrován svou neschopností implementovat vlastní nápady. Zkoušel se naučit programovat, ale lekce programování byly na něj příliš pomalé. Jeho spolubydlící se rozhodl o rekvalifikaci a tak zkusil Codeacademy, ale brzy toho nechal s tím, že je to příliš velká nuda. Týden co týden se někdo z Georgových přátel pokoušel využít Codeacademyk učení programování, ale po chvíli odpadl. Uvědomili jsme si, že se jedná o stejný problém, který jsme již vyřešili při tvorbě Skitteru: lidé se pokouší učit na pomalých, intenzivních teoretických lekcích, ale místo toho potřebují rychlé, ale obsáhlé praktické cvičení. A na tento problém známe řešení."
why_paragraph_2: "Potřebujete se naučit programovat? Pak nepotřebujete lekce, potřebuje příležitost psát spoustu kódu a při tom se u toho dobře bavit."
why_paragraph_3_prefix: "To je to o čem musí programování být. Ne rádoby zábava typu"
why_paragraph_3_italic: "hmm, další odznáček"
why_paragraph_3_center: "ale nadšení typu"
why_paragraph_3_italic_caps: "POČKEJ MAMI, MUSÍM DOKONČIT ÚROVEŇ!"
why_paragraph_3_suffix: "Proto je CodeCombat opravdová multiplayer hra, ne lekce kurzu s herními odznáčky. Neskončí, dokud sami nepřestanete, což je tentokrát dobrá věc."
why_paragraph_4: "A jestli se máte stát závislými na nějaké hře, pak ať je to hra tato, a staňte se díky tomu kouzelníky a odborníky v této technické době."
why_ending: "A mimochodem - je to zdarma. "
why_ending_url: "Začněte kouzlit!"
george_description: "CEO, obchodník, návrhář webů i her a šampión všech začátečníků programování."
scott_description: "Výtečný programátor, softwarový architekt, kouzelník v kuchyni i pán financí. Scott je v týmu pan rozumný."
nick_description: "Programátorský kouzelník, excentrický motivační mág i experimentátor. Nick by mohl dělat de-facto cokoliv, ale zvolil si vytvořit CodeCombat."
jeremy_description: "Mistr zákaznické podpory, tester použitelnosti a organizátor komunity. Je velmi pravděpodobné, že jste si spolu již psali."
michael_description: "Programátor, systémový administrátor a král podsvětí technického zázemí. Michael udržuje naše servery online."
# glen_description: "Programmer and passionate game developer, with the motivation to make this world a better place, by developing things that matter. The word impossible can't be found in his dictionary. Learning new skills is his joy!"
legal:
page_title: "Licence"
opensource_intro: "CodeCombat je zdarma a plně open source."
opensource_description_prefix: "Podívejte se na "
github_url: "naši stránku na GitHubu"
opensource_description_center: "a pokud se vám chce, můžete i pomoct! CodeCombat je vystavěn na několika oblíbených svobodných projektech. Podívejte se na"
archmage_wiki_url: "naši wiki Arcikouzelníků "
opensource_description_suffix: "pro seznam projektů, díky kterým může tato hra existovat."
practices_title: "Doporučené postupy"
practices_description: "Toto je příslib našeho přístupu v jednoduchém jazyce."
privacy_title: "Soukromí"
privacy_description: "Neprodáme vaše osobní informace. Náš plán na zhodnocení je založen na poskytování pracovních příležitostí, přesto si můžete být jisti, že vaše osobní informace nebudou distribuovány bez vašeho plného souhlasu."
security_title: "Zabezpečení"
security_description: "Usilujeme o to, abychom udrželi vaše osobní informace v bezpečí. Jako otevřený projekt jsme přístupni komukoliv k provedení kontroly kódu pro zlepšení našich bezpečnostních systémů."
email_title: "Email"
email_description_prefix: "Nebudeme vás zaplavovat nevyžádanou korespondencí. Pomocí "
email_settings_url: " nastavení emailu"
email_description_suffix: "nebo skrze odkazy v odeslaných emailech si můžete nastavit nebo se kdykoliv odhlásit z naší korespondence."
cost_title: "Cena"
cost_description: "Momentálně je CodeCombat 100% zdarma! Naší snahou je udržet přístup zdarma, abychom dali možnost hrát co největšímu množství lidí. V případě nutnosti budeme muset přejít na placený vstup nebo platbu za přístup k určitému obsahu, ale raději bychom se tomu vyhnuli. S trochou štěstí doufáme v následující plán monetizace:"
recruitment_title: "Nábor"
recruitment_description_prefix: "Zde na CodeCombatu se stanete mocným kouzelníkem a to nejen ve hře, ale i v reálném životě."
url_hire_programmers: "O dobré programátory je stále velký zájem "
recruitment_description_suffix: "takže až se vypracujete a pokud budete souhlasit, budeme demonstrovat vaše nejlepší programátorské úspěchy tisícovkám zaměstnavatelů, kteří by vás rádi zaměstnali. Ti nám zaplatí něco málo, ale vám pak zaplatí "
recruitment_description_italic: "daleko více,"
recruitment_description_ending: "tato hra zůstane zdarma a všichni budou spokojeni. Takový je plán."
copyrights_title: "Copyrights a Licence"
contributor_title: "Licenční ujednání přispívatelů (CLA)"
contributor_description_prefix: "Všichni přispívatelé jak na webu tak do projektu na GitHubu spadají pod naše "
cla_url: "CLA"
contributor_description_suffix: "se kterým je nutno souhlasit před tím, nežli přispějete."
code_title: "Kód - MIT"
code_description_prefix: "Veškerý kód vlastněný CodeCombatem nebo hostovaným na codecombat.com, kód v repozitáři na GitHub repository nebo v databázi codecombat.com, je licencován pod "
mit_license_url: "MIT licencí"
code_description_suffix: "Zahrnut je veškerý kód v systémech a komponentech, které jsou zpřístupněné CodeCombatem pro vytváření úrovní."
art_title: "Art/Hudba - Creative Commons "
art_description_prefix: "Veškerý obecný obsah je dostupný pod "
cc_license_url: "Mezinárodní Licencí Creative Commons Attribution 4.0"
art_description_suffix: "Obecným obsahem se rozumí vše dostupné na CodeCombatu, určené k vytváření úrovní. To zahrnuje:"
art_music: "Hudbu"
art_sound: "Zvuky"
art_artwork: "Umělecká díla"
art_sprites: "Doplňkový kód"
art_other: "A veškeré další kreativní práce použité při vytváření úrovní."
art_access: "Momentálně neexistuje jednoduchý systém pro stažení těchto součástí, částí úrovní a podobně. Lze je stáhnout z URL adres na tomto webu, můžete nás kontaktovat se žádostí o informace nebo nám i pomoci ve sdílení a vytváření systému pro jednoduché sdílení těchto doplňkových součástí."
art_paragraph_1: "Při uvádění zdroje, uvádějte prosím jméno a odkaz na codecombat.com v místech, která jsou vhodná a kde je to možné. Například:"
use_list_1: "Při použití ve filmu uveďte codecombat.com v titulcích."
use_list_2: "Při použití na webu, zahrňte odkaz například pod obrázkem/odkazem, nebo na stránce uvádějící zdroj, kde také zmíníte další Creative Commons díla a další použité open source projekty. Ostatní, na CodeCombat odkazující se práce (například článek na blogu zmiňující CodeCombat) není nutno separátně označovat a uvádět zdroj."
art_paragraph_2: "Využíváte-li obsah vytvořený některým uživatelem na codecombat.com, uvádějte odkaz na zdroj přímo na tohoto autora a následujte doporučení uvádění zdroje daného obsahu, je-li uvedeno."
rights_title: "Práva vyhrazena"
rights_desc: "Všechna práva jsou vyhrazena jednotlivým samostatným úrovním. To zahrnuje"
rights_scripts: "Skripty"
rights_unit: "Unit konfigurace"
rights_description: "Popisy"
rights_writings: "Zápisy"
rights_media: "Média (zvuky, hudba) a další tvořivý obsah vytvořený specificky pro tuto úroveň, který nebyl zpřístupněn při vytváření úrovně."
rights_clarification: "Pro ujasnění - vše, co je dostupné v editoru úrovní při vytváření úrovně spadá pod CC, ale obsah vytvořený v editoru úrovní nebo nahraný při vytváření spadá pod úroveň."
nutshell_title: "Ve zkratce"
nutshell_description: "Vše co je poskytnuto v editoru úrovní je zdarma a mžete toho využít při vytváření úrovní. Ale vyhrazujeme si právo omezit distribuci úrovní samotných (těch, které byly vytvořeny na codecombat.com), takže v budoucnu bude možno tyto zpoplatnit, bude-li to v nejhorším případě nutné"
canonical: "Anglická verze tohoto dokumentu je původní, rozhodující verzí. Nastane-li rozdíl v překladu, Anglická verze bude mít vždy přednost."
contribute:
page_title: "Přispívání"
character_classes_title: "Obsazení rolí"
introduction_desc_intro: "Vkládáme do CodeCombatu velké naděje."
introduction_desc_pref: "Chceme být to místo, ve kterém se všichni programátoři sejdou pro společnou hru a učení, uvedou další do úžasného světa programování a kde se předvede elita. Víme, že toto sami nezvládneme, jsou to lidé, kteří dělají projekty typu GitHub, Stack Overflow a Linux úspěšnými. Za tímto účelem, "
introduction_desc_github_url: "CodeCombat je kompletně open source"
introduction_desc_suf: "a snažíme se jak jen to jde, abychom vám umožnili se do tohoto projektu zapojit."
introduction_desc_ending: "Doufáme, že se k nám přidáte!"
introduction_desc_signature: "- Nick, George, Scott, Michael a Jeremy"
alert_account_message_intro: "Vítejte!"
alert_account_message_pref: "K přihlášení odebírání emailů si nejprve musíte "
alert_account_message_suf: "vytvořit účet"
alert_account_message_create_url: "."
# archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever."
archmage_introduction: "Jedna z nejlepších věcí na vytváření her je to, že se jedná o spojení různých procesů. Grafika, zvuk, síťování v reálném čase, mezilidské vztahy a samozřejmě také spousta běžných aspektů programování, od nízkoúrovňového managementu databáze přes administraci serverů až po tvorbu uživatelská rozhraní. Je zde spousta práce a pokud jste zkušený programátor a všeuměl připravený k ponoření se do hloubek CodeCombatu, tato skupina je pro vás. Budeme moc rádi za vaši pomoc při tvorbě té nejlepší programovací hry."
class_attributes: "Vlastnosti"
archmage_attribute_1_pref: "Znáte "
archmage_attribute_1_suf: "nebo se jej chcete naučit. Je v něm většina našeho kódu. Je-li vaším oblíbeným jazykem Ruby nebo Python, budete se cítit jako doma. Je to JavaScript, ale s lepší syntaxí."
archmage_attribute_2: "Zkušenosti s programováním a osobní iniciativa. Pomůžeme vám se zorientovat, ale nemůžeme vás učit."
how_to_join: "Jak se přidat"
join_desc_1: "Pomoct může kdokoliv! Pro začátek se podívejte na naši stránku na "
join_desc_2: " , zaškrtněte políčko níže - označíte se tím jako statečný Arcimág a začnete dostávat informace o novinkách emailem. Chcete popovídat o tom jak začít? "
join_desc_3: ", nebo se s námi spojte v naší "
join_desc_4: "!"
join_url_email: "Pošlete nám email"
join_url_hipchat: "veřejné HipChat chatovací místnosti"
more_about_archmage: "Dozvědět se více o tom, jak se stát mocným Arcimágem"
archmage_subscribe_desc: "Dostávat emailem oznámení a informacemi nových programovacích příležitostech"
# artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to"
# artisan_summary_suf: "then this class is for you."
artisan_introduction_pref: "Musíme vytvářet další úrovně! Lidé nás prosí o další obsah, ale sami zvládáme vytvořit jen málo. Naším prvním pracovním zastavením je první úroveň. Editor úrovní je tak-tak použitelný i pro jeho vlastní tvůrce. Máte-li vizi pro vytvoření vnořených úrovní alá "
artisan_introduction_suf: "pak neváhejte, toto je vaše destinace."
artisan_attribute_1: "Předchozí zkušenosti s vytvářením podobného obsahu by byly vítány, například z editorů úrovní Blizzardu, ale nejsou vyžadovány!"
artisan_attribute_2: "Připraveni ke spoustě testování a pokusů. K vytvoření dobré úrovně je potřeba je představit ostatním, nechat je hrát a pak je z velké části měnit a opravovat."
artisan_attribute_3: "Pro teď, stejné jako Dobrodruh - tester úrovní. Náš editor úrovní je ve velmi raném stádiu a frustrující při používání. Varovali jsme vás!"
artisan_join_desc: "Použijte editor úrovní v těchto postupných krocích:"
artisan_join_step1: "Přečtěte si dokumentaci."
artisan_join_step2: "Vytvořte novou úroveň a prozkoumejte existující úrovně."
artisan_join_step3: "Požádejte nás o pomoc ve veřejné HipChat místnosti."
artisan_join_step4: "Zveřejněte vaši úroveň na fóru pro připomínkování."
more_about_artisan: "Dozvědět se více o tom, jak se stát kreativním Řemeslníkem"
artisan_subscribe_desc: "Dostávat emailem oznámení a informace o aktualizacích editoru úrovní."
# adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you."
adventurer_introduction: "Ujasněme si dopředu jednu věc o vaší roli: budete jako tank. Projdete ohněm. Potřebujeme někoho, kdo odzkouší zbrusu nové úrovně a pomůže identifikovat kde je možno je zlepšit. Ten boj bude ohromný - tvorba her je dlouhý proces, který nikdo nezvládne na první pokus. Máte-li na to a vydržíte-li to, pak toto je vaše skupina."
adventurer_attribute_1: "Touha po učení se. Vy se chcete naučit programovat a my vás to chceme naučit. Jenom, v tomto případě to budete vy, kdo bude vyučovat."
adventurer_attribute_2: "Charismatický. Buďte mírný a pečlivě artikulujte co a jak je potřeba zlepšit."
adventurer_join_pref: "Buďto se spojte (nebo si najděte!) Dobrodruha a pracujte s ním, nebo zaškrtněte políčko níže a dostávejte emaily o dostupnosti nových úrovní k testování. Budeme také posílat informace o nových úrovních k recenzím na sociálních webech, "
adventurer_forum_url: " našem fóru"
adventurer_join_suf: "takže pokud chcete být v obraze, připojte se k nám!"
more_about_adventurer: "Dozvědět se více o tom, jak se stát statečným Dobrodruhem"
adventurer_subscribe_desc: "Dostávat emailem oznámení a informace nových úrovních k testování."
# scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the "
# scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you."
scribe_introduction_pref: "CodeCombat nebude pouze kupa úrovní. Bude také zahrnovat informační zdroje a wiki programovacích konceptů na které se úrovně mohou navázat. Takto, namísto toho aby každý Řemeslník musel sám do detailu popsatco který operátor dělá, mohou jednoduše nalinkovat svoji úroveň na článek existující k edukaci hráčů. Něco ve stylu "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jestliže vás baví popisovat a předávat koncept programování v Markdown editoru, pak tato role může být právě pro vás."
scribe_attribute_1: "Zkušenost s psaním je jediné co budete potřebovat. Nejen gramatika, ale také schopnost popsat složité koncepty a myšlenky ostatním."
contact_us_url: "Spojte se s námi"
scribe_join_description: "dejte nám o vás vědět, o vašich zkušenostech s programováním a o čm byste rádi psali. Od toho začneme!"
more_about_scribe: "Dozvědět se více o tom, jak se stát pilným Pisálkem"
scribe_subscribe_desc: "Dostávat emailem oznámení a informace o článcích."
# diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you."
diplomat_introduction_pref: "Jedna z věcí, kterou jsme zjistili během "
diplomat_launch_url: "zahájení v Říjnu"
diplomat_introduction_suf: "bylo, že o CodeCombat je velký zájem i v jiných zemích, obzvláště v Brazílii! Chystáme regiment překladatelů ke zpřístupnění CodeCombatu světu. Pokud chcete nakouknout pod pokličku, dozvědět se o připravovaných novinkách a zpřístupnit úrovně vašim národním kolegům, toto je role pro vás."
diplomat_attribute_1: "Plynulost v angličtině a v jazyce do kterého budete překládat. Při předávání komplexních myšlenek je důležité si být jistí v kramflecích v obou jazycích!"
# diplomat_join_pref_github: "Find your language locale file "
# diplomat_github_url: "on GitHub"
# diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!"
more_about_diplomat: "Dozvědět se více o tom, jak se stát Diplomatem"
diplomat_subscribe_desc: "Dostávat emailem oznámení a informace o internacionalizaci a o úrovních k překladu."
# ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you."
ambassador_introduction: "Zde se tvoří komunita a vy jste její spojení. Využíváme chat, emaily a sociální sítě se spoustou lidí k informování a diskuzím a seznámení s naší hrou. Chcete-li pomoci lidem se přidat a pobavit se a získat dobrý náhled na CodeCombat a kam směřujeme, pak toto je vaše role."
ambassador_attribute_1: "Komunikační schopnosti. Schopnost identifikovat problémy hráčů a pomoci jim je řešit. Naslouchat co hráči říkají, co mají rádi a co rádi nemají a komunikovat to zpět ostatním!"
ambassador_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Od toho začneme!"
ambassador_join_note_strong: "Poznámka"
ambassador_join_note_desc: "Jedna z našich priorit je vytvoření vícehráčové hry, kde hráč, který má problém s řešením úrovní může oslovit a požádat o pomoc zkušenější kouzelníky. To je přesně ten případ a místo pro pomoc Velvyslance . Dáme vám vědět více!"
more_about_ambassador: "Dozvědět se více o tom, jak se stát nápomocným Velvyslancem"
ambassador_subscribe_desc: "Dostávat emailem oznámení a informace o vývoji v podpoře a vícehráčové hře."
# counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you."
counselor_introduction_1: "Máte životní zkušenosti? Máte odlišný náhled na věci a jste schopni nám tímto pomoci v dalším vývoji CodeCombatu? Jedna z důležitých rolí i když asi nejméně časově náročná, nicméně každá individualita je schopná udělat velký rozdíl. Hledáme zkušené odborníky, zvláště pak v oblastech vzdělávání, vývoji her managementu open source, source project management, náboru lidských zdrojů, podnikání nebo designu."
counselor_introduction_2: "Nebo cokoliv, co je relevantní ve vývoji CodeCombatu. Máte-li znalosti a jste-li ochotni se o ně podělit pro další růst tohoto projektu , pak toto je role pro vás."
counselor_attribute_1: "Zkušenosti ve výše zmíněných oblastech, nebo něco, čím byste mohli být nápomocni."
counselor_attribute_2: "Troška volného času!"
counselor_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Přidáme si vás do seznamu a budeme vás kontaktovat v případě, že to bude potřeba (ne moc často)."
more_about_counselor: "Dozvědět se více o tom, jak se stát Poradcem"
changes_auto_save: "Změny jsou automaticky uloženy při kliknutí na zaškrtávací políčka."
diligent_scribes: "Naši pilní Písaři:"
powerful_archmages: "Naši mocní Arcimágové:"
creative_artisans: "Naši kreativní Řemeslníci:"
brave_adventurers: "Naši stateční Dobrodruzi:"
translating_diplomats: "Naši překladatelští Diplomati:"
helpful_ambassadors: "Naši nápomocní Velvyslanci:"
classes:
archmage_title: "Arcikouzelník"
archmage_title_description: "(Programátor)"
artisan_title: "Řemeslník"
artisan_title_description: "(Tvůrce úrovní)"
adventurer_title: "Dobrodruh"
adventurer_title_description: "(Tester úrovní)"
scribe_title: "Pisálek"
scribe_title_description: "(Editor článků)"
diplomat_title: "Diplomat"
diplomat_title_description: "(Překladatel)"
ambassador_title: "Velvyslanec"
ambassador_title_description: "(Podpora)"
counselor_title: "Poradce"
counselor_title_description: "(Odborník)"
# ladder:
# please_login: "Please log in first before playing a ladder game."
# my_matches: "My Matches"
# simulate: "Simulate"
# simulation_explanation: "By simulating games you can get your game ranked faster!"
# simulate_games: "Simulate Games!"
# simulate_all: "RESET AND SIMULATE GAMES"
# games_simulated_by: "Games simulated by you:"
# games_simulated_for: "Games simulated for you:"
# leaderboard: "Leaderboard"
# battle_as: "Battle as "
# summary_your: "Your "
# summary_matches: "Matches - "
# summary_wins: " Wins, "
# summary_losses: " Losses"
# rank_no_code: "No New Code to Rank"
# rank_my_game: "Rank My Game!"
# rank_submitting: "Submitting..."
# rank_submitted: "Submitted for Ranking"
# rank_failed: "Failed to Rank"
# rank_being_ranked: "Game Being Ranked"
# code_being_simulated: "Your new code is being simulated by other players for ranking. This will refresh as new matches come in."
# no_ranked_matches_pre: "No ranked matches for the "
# no_ranked_matches_post: " team! Play against some competitors and then come back here to get your game ranked."
# choose_opponent: "Choose an Opponent"
# tutorial_play: "Play Tutorial"
# tutorial_recommended: "Recommended if you've never played before"
# tutorial_skip: "Skip Tutorial"
# tutorial_not_sure: "Not sure what's going on?"
# tutorial_play_first: "Play the Tutorial first."
# simple_ai: "Simple AI"
# warmup: "Warmup"
# vs: "VS"
# multiplayer_launch:
# introducing_dungeon_arena: "Introducing Dungeon Arena"
# new_way: "March 17, 2014: The new way to compete with code."
# to_battle: "To Battle, Developers!"
# modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here."
# arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here."
# ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even"
# fork_our_arenas: "fork our arenas"
# create_worlds: "and create your own worlds."
# javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a"
# tutorial: "tutorial"
# new_to_programming: ". New to programming? Hit our beginner campaign to skill up."
# so_ready: "I Am So Ready for This"
| 139950 | module.exports = nativeDescription: "čeština", englishDescription: "Czech", translation:
common:
loading: "Načítání..."
saving: "Ukládání..."
sending: "Odesílání..."
cancel: "Zrušit"
save: "Uložit"
delay_1_sec: "1 vteřina"
delay_3_sec: "3 vteřiny"
delay_5_sec: "5 vteřin"
manual: "Ručně"
fork: "Klonovat"
play: "Přehrát"
modal:
close: "Zavřít"
okay: "Budiž"
not_found:
page_not_found: "Stránka nenalezena"
nav:
play: "Úrovně"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Domů"
contribute: "Přispívat"
legal: "Licence"
about: "O programu"
contact: "Kontakt"
twitter_follow: "Sledovat na twitteru"
employers: "Pro zaměstnavatele"
versions:
save_version_title: "Uložit novou Verzi"
new_major_version: "Nová hlavní Verze"
cla_prefix: "Před uložením musíte souhlasit s"
cla_url: "licencí"
cla_suffix: "."
cla_agree: "SOUHLASÍM"
login:
sign_up: "Vytvořit účet"
log_in: "Přihlásit"
log_out: "Odhlásit"
recover: "obnovit účet"
recover:
recover_account_title: "Obnovení účtu"
send_password: "<PASSWORD>"
signup:
create_account_title: "Vytvořit účet k uložení úrovně"
description: "Registrace je zdarma. Vyplňte pouze několik údajů:"
email_announcements: "Dostávat novinky emailem"
coppa: "starší 13 let nebo nejste z USA "
coppa_why: "(Proč?)"
creating: "Vytvářím účet..."
sign_up: "Přihlášení"
log_in: "zadejte vaše heslo"
home:
slogan: "Naučte se programování JavaScriptu při hraní více-hráčové programovací hry."
no_ie: "Omlouváme se, ale CodeCombat boužel nefunguje v Internet Exploreru 9 nebo starším."
no_mobile: "CodeCombat není navržen pro mobilní zařízení a nemusí fungovat správně!"
play: "Hrát"
# old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!"
# old_browser_suffix: "You can try anyway, but it probably won't work."
# campaign: "Campaign"
# for_beginners: "For Beginners"
# multiplayer: "Multiplayer"
# for_developers: "For Developers"
play:
choose_your_level: "Zvolte si úroveň"
adventurer_prefix: "Můžete přejít do dalších úrovní, nebo debatovat o úrovních na "
adventurer_forum: "fóru Dobrodruhů"
adventurer_suffix: "."
campaign_beginner: "Začátečnická úroveň"
campaign_beginner_description: "...ve které se naučíte kouzla programování."
campaign_dev: "Náhodné težší úrovně"
campaign_dev_description: "...ve kterých se dozvíte více o prostředí při plnění těžších úkolů."
campaign_multiplayer: "Multiplayer Aréna"
campaign_multiplayer_description: "...ve které programujete proti jiným hráčům."
campaign_player_created: "Uživatelsky vytvořené úrovně"
campaign_player_created_description: "...ve kterých bojujete proti kreativitě ostatních <a href=\"/contribute#artisan\">Zdatných Kouzelníků</a>."
level_difficulty: "Obtížnost: "
# play_as: "Play As"
# spectate: "Spectate"
contact:
contact_us: "Konktujte CodeCombat"
welcome: "Rádi od vás uslyšíme. Použijte tento formulář pro odeslání emailu. "
contribute_prefix: "Chcete-li nám přispět, prohlédněte si naši stránku "
contribute_page: "přispivatelů"
contribute_suffix: "!"
forum_prefix: "Pro ostatní veřejné věci, prosím zkuste "
forum_page: "naše fórum"
forum_suffix: "."
send: "Odeslat připomínku"
diplomat_suggestion:
title: "Pomozte přeložit CodeCombat!"
sub_heading: "Potřebujeme vaše dovednosti."
pitch_body: "Přestože vyvíjíme CodeCombat v angličtině, máme spoustu hráčů z celého světa a mnozí z nich by si rádi zahráli česky, neboť anglicky neumí. Pokud anglicky umíte, přihlaste se prosím jako Diplomat a pomozte nám v překladu webu i jednotlivých úrovní."
missing_translations: "Dokud nebude vše přeloženo, bude se vám na zatím nepřeložených místech zobrazovat text anglicky."
learn_more: "Dozvědět se více o Diplomatech"
subscribe_as_diplomat: "Přihlásit se jako Diplomat"
wizard_settings:
title: "Nastavení Kouzelníka"
customize_avatar: "Upravte vás Avatar"
# clothes: "Clothes"
# trim: "Trim"
# cloud: "Cloud"
# spell: "Spell"
# boots: "Boots"
# hue: "Hue"
# saturation: "Saturation"
# lightness: "Lightness"
account_settings:
title: "Nastavení účtu"
not_logged_in: "Přihlaste se, nebo vytvořte si účet pro uložení nastavení."
autosave: "Automatické ukládání změn"
me_tab: "O mne"
picture_tab: "Obrázek"
wizard_tab: "Kouzelník"
password_tab: "<PASSWORD>"
emails_tab: "Emaily"
# admin: "Admin"
gravatar_select: "Zvolte kterou Gravatar fotografii použít"
gravatar_add_photos: "Přidat náhledy a fotografie do Gravatar účtu pro zvolení obrázku"
gravatar_add_more_photos: "Přidat do vašeho Gravatar účtu další fotografie."
wizard_color: "Barva Kouzelníkova oblečení"
new_password: "<PASSWORD>"
new_password_verify: "<PASSWORD>"
email_subscriptions: "Doručovat emailem"
email_announcements: "Oznámení"
# email_notifications: "Notifications"
email_notifications_description: "Zasílat na váš účet opakovaná oznámení."
email_announcements_description: "Zasílat emaily o posledních novinkách a o postupu ve vývoji CodeCombat."
contributor_emails: "Emaily pro přispívatele"
contribute_prefix: "Hledáme další přispívatele! Čtěte prosím "
contribute_page: "stránku přispívatelům"
contribute_suffix: " pro více informací."
email_toggle: "Zvolit vše"
error_saving: "Chyba při ukládání"
saved: "Změny uloženy"
password_mismatch: "<PASSWORD>."
account_profile:
edit_settings: "Editovat Nastavení"
profile_for_prefix: "Profil pro "
# profile_for_suffix: ""
profile: "Profil"
user_not_found: "Uživatel nenalezen. Zkontrolujte adresu URL?"
gravatar_not_found_mine: "Nenalezli jsme profil asociovaný s:"
gravatar_not_found_email_suffix: "."
gravatar_signup_prefix: "Přihlásit se "
gravatar_signup_suffix: " k nastavení!"
gravatar_not_found_other: "Bohužel, neexistuje profil asociovaný s touto emailovou adresou."
gravatar_contact: "Kontakt"
gravatar_websites: "Weby"
gravatar_accounts: "Jak zobrazeno na"
gravatar_profile_link: "Účet Gravatar"
play_level:
level_load_error: "Úroveň se nepodařilo otevřít: "
done: "Hotovo"
grid: "Mřížka"
customize_wizard: "Upravit Kouzelníka"
home: "Domů"
guide: "Průvodce"
multiplayer: "Multiplayer"
restart: "Restartovat"
goals: "Cíl"
action_timeline: "Časová osa"
click_to_select: "Vyberte kliknutím."
reload_title: "Znovunačíst veškerý kód?"
reload_really: "Opravdu chcete resetovat tuto úroveň do počátečního stavu?"
reload_confirm: "Znovu načíst vše"
# victory_title_prefix: ""
victory_title_suffix: " Hotovo"
victory_sign_up: "Přihlásit se pro uložení postupu"
victory_sign_up_poke: "Chcete uložit váš kód? Vytvořte si účet zdarma!"
victory_rate_the_level: "Ohodnoťte tuto úroveň: "
# victory_rank_my_game: "Rank My Game"
# victory_ranking_game: "Submitting..."
# victory_return_to_ladder: "Return to Ladder"
victory_play_next_level: "Hrát další úroveň"
victory_go_home: "Přejít domů"
victory_review: "Připomínky!"
victory_hour_of_code_done: "Skončili jste?"
victory_hour_of_code_done_yes: "Ano, pro dnešek jsem skončil!"
multiplayer_title: "Nastavení Multiplayeru"
multiplayer_link_description: "Sdílejte tento odkaz s lidmi, kteří se k vám mohou přidat ve hře."
multiplayer_hint_label: "Tip:"
multiplayer_hint: " Klikněte na odkaz pro jeho výběr, poté stiskněte ⌘-C nebo Ctrl-C pro kopírování odkazu."
multiplayer_coming_soon: "Další vlastnosti multiplayeru jsou na cestě!"
guide_title: "Průvodce"
tome_minion_spells: "Vaše oblíbená kouzla"
tome_read_only_spells: "Kouzla jen pro čtení"
tome_other_units: "Ostatní jednotky"
tome_cast_button_castable: "Spustit"
tome_cast_button_casting: "Spouštění"
tome_cast_button_cast: "Spustit Kouzlo"
tome_autocast_delay: "Prodleva Autospouštení"
tome_select_spell: "Zvolte Kouzlo"
tome_select_a_thang: "Zvolte někoho pro "
tome_available_spells: "Dostupná kouzla"
hud_continue: "Pokračovat (stiskněte shift-mezera)"
spell_saved: "Kouzlo uloženo"
# skip_tutorial: "Skip (esc)"
# editor_config: "Editor Config"
# editor_config_title: "Editor Configuration"
# editor_config_keybindings_label: "Key Bindings"
# editor_config_keybindings_default: "Default (Ace)"
# editor_config_keybindings_description: "Adds additional shortcuts known from the common editors."
# editor_config_invisibles_label: "Show Invisibles"
# editor_config_invisibles_description: "Displays invisibles such as spaces or tabs."
# editor_config_indentguides_label: "Show Indent Guides"
# editor_config_indentguides_description: "Displays vertical lines to see indentation better."
# editor_config_behaviors_label: "Smart Behaviors"
# editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes."
# loading_ready: "Ready!"
# tip_insert_positions: "Shift+Click a point on the map to insert it into the spell editor."
# tip_toggle_play: "Toggle play/paused with Ctrl+P."
# tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward."
# tip_guide_exists: "Click the guide at the top of the page for useful info."
# tip_open_source: "CodeCombat is 100% open source!"
# tip_beta_launch: "CodeCombat launched its beta in October, 2013."
# tip_js_beginning: "JavaScript is just the beginning."
# tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button."
# tip_baby_coders: "In the future, even babies will be Archmages."
# tip_morale_improves: "Loading will continue until morale improves."
# tip_all_species: "We believe in equal opportunities to learn programming for all species."
# tip_reticulating: "Reticulating spines."
# tip_harry: "Yer a Wizard, "
admin:
av_title: "Administrátorský pohled"
av_entities_sub_title: "Entity"
av_entities_users_url: "Uživatelé"
av_entities_active_instances_url: "Aktivní instance"
av_other_sub_title: "Ostatní"
av_other_debug_base_url: "Base (pro debugování base.jade)"
u_title: "Seznam uživatelů"
lg_title: "Poslední hry"
# clas: "CLAs"
editor:
main_title: "Editory CodeCombatu"
main_description: "Vytvořte vlastní úrovně, kampaně, jednotky a vzdělávací obsah. My vám poskytujeme všechny potřebné nástroje!"
article_title: "Editor článků"
article_description: "Napište články, které objasní hráčům koncepty programování využitelné v úrovních a kampaních."
thang_title: "Editor Thangů - objektů"
thang_description: "Vytvořte jednotky, definujte jejich logiku, vlastnosti, grafiku a zvuk. Momentálně jsou podporovány pouze importy vektorové grafiky exportované z Flashe."
level_title: "Editor úrovní"
level_description: "Zahrnuje pomůcky pro skriptování, nahrávání audia a tvorbu vlastní logiky pro vytvoření vlastních úrovní. Obsahuje vše, čeho využíváme k tvorbě úrovní my!"
security_notice: "Velké množství důležitých funkcí těchto editorů je standardně vypnuto. Jak postupem času vylepšujeme bezpečnost celého systému, jsou tyto funkce uvolňovány k veřejnému použití. Potřebujete-li některé funkce dříve, "
contact_us: "kontaktujte nás!"
hipchat_prefix: "Můžete nás také najít v naší"
hipchat_url: "HipChat diskusní místnosti."
# revert: "Revert"
# revert_models: "Revert Models"
level_some_options: "Volby?"
level_tab_thangs: "Thangy"
level_tab_scripts: "Skripty"
level_tab_settings: "Nastavení"
level_tab_components: "Komponenty"
level_tab_systems: "Systémy"
level_tab_thangs_title: "Současné Thangy"
level_tab_thangs_conditions: "Výchozí prostředí"
level_tab_thangs_add: "Přidat Thangy"
level_settings_title: "Nastavení"
level_component_tab_title: "Současné komponenty"
level_component_btn_new: "Vytvořit novou komponentu"
level_systems_tab_title: "Současné systémy"
level_systems_btn_new: "Vytvořit nový systém"
level_systems_btn_add: "Přidat systém"
level_components_title: "Zpět na všechny Thangy"
level_components_type: "Druh"
level_component_edit_title: "Editovat komponentu"
# level_component_config_schema: "Config Schema"
# level_component_settings: "Settings"
level_system_edit_title: "Editovat systém"
create_system_title: "Vytvořit nový systém"
new_component_title: "Vytvořit novou komponentu"
new_component_field_system: "Systém"
# new_article_title: "Create a New Article"
# new_thang_title: "Create a New Thang Type"
# new_level_title: "Create a New Level"
# article_search_title: "Search Articles Here"
# thang_search_title: "Search Thang Types Here"
# level_search_title: "Search Levels Here"
article:
edit_btn_preview: "Náhled"
edit_article_title: "Editovat článek"
general:
and: "a"
name: "Jméno"
body: "Tělo"
version: "Verze"
commit_msg: "Popisek ukládání"
# history: "History"
version_history_for: "Verze historie pro: "
# result: "Result"
results: "Výsledky"
description: "Popis"
or: "nebo"
email: "Email"
# password: "<PASSWORD>"
message: "Zpráva"
# code: "Code"
# ladder: "Ladder"
# when: "When"
# opponent: "Opponent"
# rank: "Rank"
# score: "Score"
# win: "Win"
# loss: "Loss"
# tie: "Tie"
# easy: "Easy"
# medium: "Medium"
# hard: "Hard"
about:
who_is_codecombat: "Kdo je CodeCombat?"
why_codecombat: "Proč CodeCombat?"
who_description_prefix: "společně přišli s projektem CodeCombat v roce 2013. V roce 2008 jsme vytvořili také "
who_description_suffix: ", jedničku mezi webovými a IOS aplikacemi pro učení psaní japonských a čínských znaků."
who_description_ending: "Nyní nastal čas pomoci lidem s programováním."
why_paragraph_1: "Při vytváření <NAME> neznal <NAME> základy programování a byl neustále frustrován svou neschopností implementovat vlastní nápady. Zkoušel se naučit programovat, ale lekce programování byly na něj příliš pomalé. Jeho spolubydlící se rozhodl o rekvalifikaci a tak zkusil Codeacademy, ale brzy toho nechal s tím, že je to příliš velká nuda. Týden co týden se někdo z Georgových přátel pokoušel využít Codeacademyk učení programování, ale po chvíli odpadl. Uvědomili jsme si, že se jedná o stejný problém, který jsme již vyřešili při tvorbě <NAME>u: lidé se pokouší učit na pomalých, intenzivních teoretických lekcích, ale místo toho potřebují rychlé, ale obsáhlé praktické cvičení. A na tento problém známe řešení."
why_paragraph_2: "Potřebujete se naučit programovat? Pak nepotřebujete lekce, potřebuje příležitost psát spoustu kódu a při tom se u toho dobře bavit."
why_paragraph_3_prefix: "To je to o čem musí programování být. Ne rádoby zábava typu"
why_paragraph_3_italic: "hmm, další odznáček"
why_paragraph_3_center: "ale nadšení typu"
why_paragraph_3_italic_caps: "POČKEJ MAMI, MUSÍM DOKONČIT ÚROVEŇ!"
why_paragraph_3_suffix: "Proto je CodeCombat opravdová multiplayer hra, ne lekce kurzu s herními odznáčky. Neskončí, dokud sami nepřestanete, což je tentokrát dobrá věc."
why_paragraph_4: "A jestli se máte stát závislými na nějaké hře, pak ať je to hra tato, a staňte se díky tomu kouzelníky a odborníky v této technické době."
why_ending: "A mimochodem - je to zdarma. "
why_ending_url: "Začněte kouzlit!"
george_description: "CEO, obchodník, návrhář webů i her a šampión všech začátečníků programování."
scott_description: "Výtečný programátor, softwarový architekt, kouzelník v kuchyni i pán financí. <NAME> je v týmu pan rozumný."
nick_description: "Programátorský kouzelník, excentrický motivační mág i experimentátor. <NAME> by mohl dělat de-facto cokoliv, ale zvolil si vytvořit CodeCombat."
jeremy_description: "Mistr zákaznické podpory, tester použitelnosti a organizátor komunity. Je velmi pravděpodobné, že jste si spolu již psali."
michael_description: "Programátor, systémový administrátor a král podsvětí technického zázemí. <NAME> udržuje naše servery online."
# glen_description: "Programmer and passionate game developer, with the motivation to make this world a better place, by developing things that matter. The word impossible can't be found in his dictionary. Learning new skills is his joy!"
legal:
page_title: "Licence"
opensource_intro: "CodeCombat je zdarma a plně open source."
opensource_description_prefix: "Podívejte se na "
github_url: "naši stránku na GitHubu"
opensource_description_center: "a pokud se vám chce, můžete i pomoct! CodeCombat je vystavěn na několika oblíbených svobodných projektech. Podívejte se na"
archmage_wiki_url: "naši wiki Arcikouzelníků "
opensource_description_suffix: "pro seznam projektů, díky kterým může tato hra existovat."
practices_title: "Doporučené postupy"
practices_description: "Toto je příslib našeho přístupu v jednoduchém jazyce."
privacy_title: "Soukromí"
privacy_description: "Neprodáme vaše osobní informace. Náš plán na zhodnocení je založen na poskytování pracovních příležitostí, přesto si můžete být jisti, že vaše osobní informace nebudou distribuovány bez vašeho plného souhlasu."
security_title: "Zabezpečení"
security_description: "Usilujeme o to, abychom udrželi vaše osobní informace v bezpečí. Jako otevřený projekt jsme přístupni komukoliv k provedení kontroly kódu pro zlepšení našich bezpečnostních systémů."
email_title: "Email"
email_description_prefix: "Nebudeme vás zaplavovat nevyžádanou korespondencí. Pomocí "
email_settings_url: " nastavení emailu"
email_description_suffix: "nebo skrze odkazy v odeslaných emailech si můžete nastavit nebo se kdykoliv odhlásit z naší korespondence."
cost_title: "Cena"
cost_description: "Momentálně je CodeCombat 100% zdarma! Naší snahou je udržet přístup zdarma, abychom dali možnost hrát co největšímu množství lidí. V případě nutnosti budeme muset přejít na placený vstup nebo platbu za přístup k určitému obsahu, ale raději bychom se tomu vyhnuli. S trochou štěstí doufáme v následující plán monetizace:"
recruitment_title: "<NAME>"
recruitment_description_prefix: "Zde na CodeCombatu se stanete mocným kouzelníkem a to nejen ve hře, ale i v reálném životě."
url_hire_programmers: "O dobré programátory je stále velký zájem "
recruitment_description_suffix: "takže až se vypracujete a pokud budete souhlasit, budeme demonstrovat vaše nejlepší programátorské úspěchy tisícovkám zaměstnavatelů, kteří by vás rádi zaměstnali. Ti nám zaplatí něco málo, ale vám pak zaplatí "
recruitment_description_italic: "daleko více,"
recruitment_description_ending: "tato hra zůstane zdarma a všichni budou spokojeni. Takový je plán."
copyrights_title: "Copyrights a Licence"
contributor_title: "Licenční ujednání přispívatelů (CLA)"
contributor_description_prefix: "Všichni přispívatelé jak na webu tak do projektu na GitHubu spadají pod naše "
cla_url: "CLA"
contributor_description_suffix: "se kterým je nutno souhlasit před tím, nežli přispějete."
code_title: "Kód - MIT"
code_description_prefix: "Veškerý kód vlastněný CodeCombatem nebo hostovaným na codecombat.com, kód v repozitáři na GitHub repository nebo v databázi codecombat.com, je licencován pod "
mit_license_url: "MIT licencí"
code_description_suffix: "Zahrnut je veškerý kód v systémech a komponentech, které jsou zpřístupněné CodeCombatem pro vytváření úrovní."
art_title: "Art/Hudba - Creative Commons "
art_description_prefix: "Veškerý obecný obsah je dostupný pod "
cc_license_url: "Mezinárodní Licencí Creative Commons Attribution 4.0"
art_description_suffix: "Obecným obsahem se rozumí vše dostupné na CodeCombatu, určené k vytváření úrovní. To zahrnuje:"
art_music: "Hudbu"
art_sound: "Zvuky"
art_artwork: "Umělecká díla"
art_sprites: "Doplňkový kód"
art_other: "A veškeré další kreativní práce použité při vytváření úrovní."
art_access: "Momentálně neexistuje jednoduchý systém pro stažení těchto součástí, částí úrovní a podobně. Lze je stáhnout z URL adres na tomto webu, můžete nás kontaktovat se žádostí o informace nebo nám i pomoci ve sdílení a vytváření systému pro jednoduché sdílení těchto doplňkových součástí."
art_paragraph_1: "Při uvádění zdroje, uvádějte prosím jméno a odkaz na codecombat.com v místech, která jsou vhodná a kde je to možné. Například:"
use_list_1: "Při použití ve filmu uveďte codecombat.com v titulcích."
use_list_2: "Při použití na webu, zahrňte odkaz například pod obrázkem/odkazem, nebo na stránce uvádějící zdroj, kde také zmíníte další Creative Commons díla a další použité open source projekty. Ostatní, na CodeCombat odkazující se práce (například článek na blogu zmiňující CodeCombat) není nutno separátně označovat a uvádět zdroj."
art_paragraph_2: "Využíváte-li obsah vytvořený některým uživatelem na codecombat.com, uvádějte odkaz na zdroj přímo na tohoto autora a následujte doporučení uvádění zdroje daného obsahu, je-li uvedeno."
rights_title: "Práva vyhrazena"
rights_desc: "Všechna práva jsou vyhrazena jednotlivým samostatným úrovním. To zahrnuje"
rights_scripts: "Skripty"
rights_unit: "Unit konfigurace"
rights_description: "Popisy"
rights_writings: "Zápisy"
rights_media: "Média (zvuky, hudba) a další tvořivý obsah vytvořený specificky pro tuto úroveň, který nebyl zpřístupněn při vytváření úrovně."
rights_clarification: "Pro ujasnění - vše, co je dostupné v editoru úrovní při vytváření úrovně spadá pod CC, ale obsah vytvořený v editoru úrovní nebo nahraný při vytváření spadá pod úroveň."
nutshell_title: "Ve zkratce"
nutshell_description: "Vše co je poskytnuto v editoru úrovní je zdarma a mžete toho využít při vytváření úrovní. Ale vyhrazujeme si právo omezit distribuci úrovní samotných (těch, které byly vytvořeny na codecombat.com), takže v budoucnu bude možno tyto zpoplatnit, bude-li to v nejhorším případě nutné"
canonical: "Anglická verze tohoto dokumentu je původní, rozhodující verzí. Nastane-li rozdíl v překladu, Anglická verze bude mít vždy přednost."
contribute:
page_title: "Přispívání"
character_classes_title: "Obsazení rolí"
introduction_desc_intro: "Vkládáme do CodeCombatu velké naděje."
introduction_desc_pref: "Chceme být to místo, ve kterém se všichni programátoři sejdou pro společnou hru a učení, uvedou další do úžasného světa programování a kde se předvede elita. Víme, že toto sami nezvládneme, jsou to lidé, kteří dělají projekty typu GitHub, Stack Overflow a Linux úspěšnými. Za tímto účelem, "
introduction_desc_github_url: "CodeCombat je kompletně open source"
introduction_desc_suf: "a snažíme se jak jen to jde, abychom vám umožnili se do tohoto projektu zapojit."
introduction_desc_ending: "Doufáme, že se k nám přidáte!"
introduction_desc_signature: "- <NAME>, <NAME>, <NAME> <NAME>"
alert_account_message_intro: "Vítejte!"
alert_account_message_pref: "K přihlášení odebírání emailů si nejprve musíte "
alert_account_message_suf: "vytvořit účet"
alert_account_message_create_url: "."
# archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever."
archmage_introduction: "Jedna z nejlepších věcí na vytváření her je to, že se jedná o spojení různých procesů. Grafika, zvuk, síťování v reálném čase, mezilidské vztahy a samozřejmě také spousta běžných aspektů programování, od nízkoúrovňového managementu databáze přes administraci serverů až po tvorbu uživatelská rozhraní. Je zde spousta práce a pokud jste zkušený programátor a všeuměl připravený k ponoření se do hloubek CodeCombatu, tato skupina je pro vás. Budeme moc rádi za vaši pomoc při tvorbě té nejlepší programovací hry."
class_attributes: "Vlastnosti"
archmage_attribute_1_pref: "Znáte "
archmage_attribute_1_suf: "nebo se jej chcete naučit. Je v něm většina našeho kódu. Je-li vaším oblíbeným jazykem Ruby nebo Python, budete se cítit jako doma. Je to JavaScript, ale s lepší syntaxí."
archmage_attribute_2: "Zkušenosti s programováním a osobní iniciativa. Pomůžeme vám se zorientovat, ale nemůžeme vás učit."
how_to_join: "Jak se přidat"
join_desc_1: "Pomoct může kdokoliv! Pro začátek se podívejte na naši stránku na "
join_desc_2: " , zaškrtněte políčko níže - označíte se tím jako statečný Arcimág a začnete dostávat informace o novinkách emailem. Chcete popovídat o tom jak začít? "
join_desc_3: ", nebo se s námi spojte v naší "
join_desc_4: "!"
join_url_email: "Pošlete nám email"
join_url_hipchat: "veřejné HipChat chatovací místnosti"
more_about_archmage: "Dozvědět se více o tom, jak se stát mocným Arcimágem"
archmage_subscribe_desc: "Dostávat emailem oznámení a informacemi nových programovacích příležitostech"
# artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to"
# artisan_summary_suf: "then this class is for you."
artisan_introduction_pref: "Musíme vytvářet další úrovně! Lidé nás prosí o další obsah, ale sami zvládáme vytvořit jen málo. Naším prvním pracovním zastavením je první úroveň. Editor úrovní je tak-tak použitelný i pro jeho vlastní tvůrce. Máte-li vizi pro vytvoření vnořených úrovní alá "
artisan_introduction_suf: "pak neváhejte, toto je vaše destinace."
artisan_attribute_1: "Předchozí zkušenosti s vytvářením podobného obsahu by byly vítány, například z editorů úrovní Blizzardu, ale nejsou vyžadovány!"
artisan_attribute_2: "Připraveni ke spoustě testování a pokusů. K vytvoření dobré úrovně je potřeba je představit ostatním, nechat je hrát a pak je z velké části měnit a opravovat."
artisan_attribute_3: "Pro teď, stejné jako Dobrodruh - tester úrovní. Náš editor úrovní je ve velmi raném stádiu a frustrující při používání. Varovali jsme vás!"
artisan_join_desc: "Použijte editor úrovní v těchto postupných krocích:"
artisan_join_step1: "Přečtěte si dokumentaci."
artisan_join_step2: "Vytvořte novou úroveň a prozkoumejte existující úrovně."
artisan_join_step3: "Požádejte nás o pomoc ve veřejné HipChat místnosti."
artisan_join_step4: "Zveřejněte vaši úroveň na fóru pro připomínkování."
more_about_artisan: "Dozvědět se více o tom, jak se stát kreativním Řemeslníkem"
artisan_subscribe_desc: "Dostávat emailem oznámení a informace o aktualizacích editoru úrovní."
# adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you."
adventurer_introduction: "Ujasněme si dopředu jednu věc o vaší roli: budete jako tank. Projdete ohněm. Potřebujeme někoho, kdo odzkouší zbrusu nové úrovně a pomůže identifikovat kde je možno je zlepšit. Ten boj bude ohromný - tvorba her je dlouhý proces, který nikdo nezvládne na první pokus. Máte-li na to a vydržíte-li to, pak toto je vaše skupina."
adventurer_attribute_1: "Touha po učení se. Vy se chcete naučit programovat a my vás to chceme naučit. Jenom, v tomto případě to budete vy, kdo bude vyučovat."
adventurer_attribute_2: "Charismatický. Buďte mírný a pečlivě artikulujte co a jak je potřeba zlepšit."
adventurer_join_pref: "Buďto se spojte (nebo si najděte!) <NAME> a pracujte s ním, nebo zaškrtněte políčko níže a dostávejte emaily o dostupnosti nových úrovní k testování. Budeme také posílat informace o nových úrovních k recenzím na sociálních webech, "
adventurer_forum_url: " našem fóru"
adventurer_join_suf: "takže pokud chcete být v obraze, připojte se k nám!"
more_about_adventurer: "Dozvědět se více o tom, jak se stát statečným <NAME>hem"
adventurer_subscribe_desc: "Dostávat emailem oznámení a informace nových úrovních k testování."
# scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the "
# scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you."
scribe_introduction_pref: "CodeCombat nebude pouze kupa úrovní. Bude také zahrnovat informační zdroje a wiki programovacích konceptů na které se úrovně mohou navázat. Takto, namísto toho aby každý Řemeslník musel sám do detailu popsatco který operátor dělá, mohou jednoduše nalinkovat svoji úroveň na článek existující k edukaci hráčů. Něco ve stylu "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jestliže vás baví popisovat a předávat koncept programování v Markdown editoru, pak tato role může být právě pro vás."
scribe_attribute_1: "Zkušenost s psaním je jediné co budete potřebovat. Nejen gramatika, ale také schopnost popsat složité koncepty a myšlenky ostatním."
contact_us_url: "Spojte se s námi"
scribe_join_description: "dejte nám o vás vědět, o vašich zkušenostech s programováním a o čm byste rádi psali. Od toho začneme!"
more_about_scribe: "Dozvědět se více o tom, jak se stát pilným Pisálkem"
scribe_subscribe_desc: "Dostávat emailem oznámení a informace o článcích."
# diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you."
diplomat_introduction_pref: "Jedna z věcí, kterou jsme zjistili během "
diplomat_launch_url: "zahájení v Říjnu"
diplomat_introduction_suf: "bylo, že o CodeCombat je velký zájem i v jiných zemích, obzvláště v Brazílii! Chystáme regiment překladatelů ke zpřístupnění CodeCombatu světu. Pokud chcete nakouknout pod pokličku, dozvědět se o připravovaných novinkách a zpřístupnit úrovně vašim národním kolegům, toto je role pro vás."
diplomat_attribute_1: "Plynulost v angličtině a v jazyce do kterého budete překládat. Při předávání komplexních myšlenek je důležité si být jistí v kramflecích v obou jazycích!"
# diplomat_join_pref_github: "Find your language locale file "
# diplomat_github_url: "on GitHub"
# diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!"
more_about_diplomat: "Dozvědět se více o tom, jak se stát Diplomatem"
diplomat_subscribe_desc: "Dostávat emailem oznámení a informace o internacionalizaci a o úrovních k překladu."
# ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you."
ambassador_introduction: "Zde se tvoří komunita a vy jste její spojení. Využíváme chat, emaily a sociální sítě se spoustou lidí k informování a diskuzím a seznámení s naší hrou. Chcete-li pomoci lidem se přidat a pobavit se a získat dobrý náhled na CodeCombat a kam směřujeme, pak toto je vaše role."
ambassador_attribute_1: "Komunikační schopnosti. Schopnost identifikovat problémy hráčů a pomoci jim je řešit. Naslouchat co hráči říkají, co mají rádi a co rádi nemají a komunikovat to zpět ostatním!"
ambassador_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Od toho začneme!"
ambassador_join_note_strong: "Poznámka"
ambassador_join_note_desc: "Jedna z našich priorit je vytvoření vícehráčové hry, kde hráč, který má problém s řešením úrovní může oslovit a požádat o pomoc zkušenější kouzelníky. To je přesně ten případ a místo pro pomoc Velvyslance . Dáme vám vědět více!"
more_about_ambassador: "Dozvědět se více o tom, jak se stát nápomocným Velvyslancem"
ambassador_subscribe_desc: "Dostávat emailem oznámení a informace o vývoji v podpoře a vícehráčové hře."
# counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you."
counselor_introduction_1: "Máte životní zkušenosti? Máte odlišný náhled na věci a jste schopni nám tímto pomoci v dalším vývoji CodeCombatu? Jedna z důležitých rolí i když asi nejméně časově náročná, nicméně každá individualita je schopná udělat velký rozdíl. Hledáme zkušené odborníky, zvláště pak v oblastech vzdělávání, vývoji her managementu open source, source project management, náboru lidských zdrojů, podnikání nebo designu."
counselor_introduction_2: "Nebo cokoliv, co je relevantní ve vývoji CodeCombatu. Máte-li znalosti a jste-li ochotni se o ně podělit pro další růst tohoto projektu , pak toto je role pro vás."
counselor_attribute_1: "Zkušenosti ve výše zmíněných oblastech, nebo něco, čím byste mohli být nápomocni."
counselor_attribute_2: "Troška volného času!"
counselor_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Přidáme si vás do seznamu a budeme vás kontaktovat v případě, že to bude potřeba (ne moc často)."
more_about_counselor: "Dozvědět se více o tom, jak se stát Poradcem"
changes_auto_save: "Změny jsou automaticky uloženy při kliknutí na zaškrtávací políčka."
diligent_scribes: "Naši pilní Písaři:"
powerful_archmages: "Naši mocní Arcimágové:"
creative_artisans: "Naši kreativní Řemeslníci:"
brave_adventurers: "Naši stateční Dobrodruzi:"
translating_diplomats: "Naši překladatelští Diplomati:"
helpful_ambassadors: "Naši nápomocní Velvyslanci:"
classes:
archmage_title: "Arcikouzelník"
archmage_title_description: "(Programátor)"
artisan_title: "Řemeslník"
artisan_title_description: "(Tvůrce úrovní)"
adventurer_title: "<NAME>"
adventurer_title_description: "(Tester úrovní)"
scribe_title: "P<NAME>"
scribe_title_description: "(Editor článků)"
diplomat_title: "Diplomat"
diplomat_title_description: "(Překladatel)"
ambassador_title: "Velvyslanec"
ambassador_title_description: "(Podpora)"
counselor_title: "Poradce"
counselor_title_description: "(Odborník)"
# ladder:
# please_login: "Please log in first before playing a ladder game."
# my_matches: "My Matches"
# simulate: "Simulate"
# simulation_explanation: "By simulating games you can get your game ranked faster!"
# simulate_games: "Simulate Games!"
# simulate_all: "RESET AND SIMULATE GAMES"
# games_simulated_by: "Games simulated by you:"
# games_simulated_for: "Games simulated for you:"
# leaderboard: "Leaderboard"
# battle_as: "Battle as "
# summary_your: "Your "
# summary_matches: "Matches - "
# summary_wins: " <NAME>, "
# summary_losses: " Losses"
# rank_no_code: "No New Code to Rank"
# rank_my_game: "Rank My Game!"
# rank_submitting: "Submitting..."
# rank_submitted: "Submitted for Ranking"
# rank_failed: "Failed to Rank"
# rank_being_ranked: "Game Being Ranked"
# code_being_simulated: "Your new code is being simulated by other players for ranking. This will refresh as new matches come in."
# no_ranked_matches_pre: "No ranked matches for the "
# no_ranked_matches_post: " team! Play against some competitors and then come back here to get your game ranked."
# choose_opponent: "Choose an Opponent"
# tutorial_play: "Play Tutorial"
# tutorial_recommended: "Recommended if you've never played before"
# tutorial_skip: "Skip Tutorial"
# tutorial_not_sure: "Not sure what's going on?"
# tutorial_play_first: "Play the Tutorial first."
# simple_ai: "Simple AI"
# warmup: "Warmup"
# vs: "VS"
# multiplayer_launch:
# introducing_dungeon_arena: "Introducing Dungeon Arena"
# new_way: "March 17, 2014: The new way to compete with code."
# to_battle: "To Battle, Developers!"
# modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here."
# arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here."
# ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even"
# fork_our_arenas: "fork our arenas"
# create_worlds: "and create your own worlds."
# javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a"
# tutorial: "tutorial"
# new_to_programming: ". New to programming? Hit our beginner campaign to skill up."
# so_ready: "I Am So Ready for This"
| true | module.exports = nativeDescription: "čeština", englishDescription: "Czech", translation:
common:
loading: "Načítání..."
saving: "Ukládání..."
sending: "Odesílání..."
cancel: "Zrušit"
save: "Uložit"
delay_1_sec: "1 vteřina"
delay_3_sec: "3 vteřiny"
delay_5_sec: "5 vteřin"
manual: "Ručně"
fork: "Klonovat"
play: "Přehrát"
modal:
close: "Zavřít"
okay: "Budiž"
not_found:
page_not_found: "Stránka nenalezena"
nav:
play: "Úrovně"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Domů"
contribute: "Přispívat"
legal: "Licence"
about: "O programu"
contact: "Kontakt"
twitter_follow: "Sledovat na twitteru"
employers: "Pro zaměstnavatele"
versions:
save_version_title: "Uložit novou Verzi"
new_major_version: "Nová hlavní Verze"
cla_prefix: "Před uložením musíte souhlasit s"
cla_url: "licencí"
cla_suffix: "."
cla_agree: "SOUHLASÍM"
login:
sign_up: "Vytvořit účet"
log_in: "Přihlásit"
log_out: "Odhlásit"
recover: "obnovit účet"
recover:
recover_account_title: "Obnovení účtu"
send_password: "PI:PASSWORD:<PASSWORD>END_PI"
signup:
create_account_title: "Vytvořit účet k uložení úrovně"
description: "Registrace je zdarma. Vyplňte pouze několik údajů:"
email_announcements: "Dostávat novinky emailem"
coppa: "starší 13 let nebo nejste z USA "
coppa_why: "(Proč?)"
creating: "Vytvářím účet..."
sign_up: "Přihlášení"
log_in: "zadejte vaše heslo"
home:
slogan: "Naučte se programování JavaScriptu při hraní více-hráčové programovací hry."
no_ie: "Omlouváme se, ale CodeCombat boužel nefunguje v Internet Exploreru 9 nebo starším."
no_mobile: "CodeCombat není navržen pro mobilní zařízení a nemusí fungovat správně!"
play: "Hrát"
# old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!"
# old_browser_suffix: "You can try anyway, but it probably won't work."
# campaign: "Campaign"
# for_beginners: "For Beginners"
# multiplayer: "Multiplayer"
# for_developers: "For Developers"
play:
choose_your_level: "Zvolte si úroveň"
adventurer_prefix: "Můžete přejít do dalších úrovní, nebo debatovat o úrovních na "
adventurer_forum: "fóru Dobrodruhů"
adventurer_suffix: "."
campaign_beginner: "Začátečnická úroveň"
campaign_beginner_description: "...ve které se naučíte kouzla programování."
campaign_dev: "Náhodné težší úrovně"
campaign_dev_description: "...ve kterých se dozvíte více o prostředí při plnění těžších úkolů."
campaign_multiplayer: "Multiplayer Aréna"
campaign_multiplayer_description: "...ve které programujete proti jiným hráčům."
campaign_player_created: "Uživatelsky vytvořené úrovně"
campaign_player_created_description: "...ve kterých bojujete proti kreativitě ostatních <a href=\"/contribute#artisan\">Zdatných Kouzelníků</a>."
level_difficulty: "Obtížnost: "
# play_as: "Play As"
# spectate: "Spectate"
contact:
contact_us: "Konktujte CodeCombat"
welcome: "Rádi od vás uslyšíme. Použijte tento formulář pro odeslání emailu. "
contribute_prefix: "Chcete-li nám přispět, prohlédněte si naši stránku "
contribute_page: "přispivatelů"
contribute_suffix: "!"
forum_prefix: "Pro ostatní veřejné věci, prosím zkuste "
forum_page: "naše fórum"
forum_suffix: "."
send: "Odeslat připomínku"
diplomat_suggestion:
title: "Pomozte přeložit CodeCombat!"
sub_heading: "Potřebujeme vaše dovednosti."
pitch_body: "Přestože vyvíjíme CodeCombat v angličtině, máme spoustu hráčů z celého světa a mnozí z nich by si rádi zahráli česky, neboť anglicky neumí. Pokud anglicky umíte, přihlaste se prosím jako Diplomat a pomozte nám v překladu webu i jednotlivých úrovní."
missing_translations: "Dokud nebude vše přeloženo, bude se vám na zatím nepřeložených místech zobrazovat text anglicky."
learn_more: "Dozvědět se více o Diplomatech"
subscribe_as_diplomat: "Přihlásit se jako Diplomat"
wizard_settings:
title: "Nastavení Kouzelníka"
customize_avatar: "Upravte vás Avatar"
# clothes: "Clothes"
# trim: "Trim"
# cloud: "Cloud"
# spell: "Spell"
# boots: "Boots"
# hue: "Hue"
# saturation: "Saturation"
# lightness: "Lightness"
account_settings:
title: "Nastavení účtu"
not_logged_in: "Přihlaste se, nebo vytvořte si účet pro uložení nastavení."
autosave: "Automatické ukládání změn"
me_tab: "O mne"
picture_tab: "Obrázek"
wizard_tab: "Kouzelník"
password_tab: "PI:PASSWORD:<PASSWORD>END_PI"
emails_tab: "Emaily"
# admin: "Admin"
gravatar_select: "Zvolte kterou Gravatar fotografii použít"
gravatar_add_photos: "Přidat náhledy a fotografie do Gravatar účtu pro zvolení obrázku"
gravatar_add_more_photos: "Přidat do vašeho Gravatar účtu další fotografie."
wizard_color: "Barva Kouzelníkova oblečení"
new_password: "PI:PASSWORD:<PASSWORD>END_PI"
new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI"
email_subscriptions: "Doručovat emailem"
email_announcements: "Oznámení"
# email_notifications: "Notifications"
email_notifications_description: "Zasílat na váš účet opakovaná oznámení."
email_announcements_description: "Zasílat emaily o posledních novinkách a o postupu ve vývoji CodeCombat."
contributor_emails: "Emaily pro přispívatele"
contribute_prefix: "Hledáme další přispívatele! Čtěte prosím "
contribute_page: "stránku přispívatelům"
contribute_suffix: " pro více informací."
email_toggle: "Zvolit vše"
error_saving: "Chyba při ukládání"
saved: "Změny uloženy"
password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI."
account_profile:
edit_settings: "Editovat Nastavení"
profile_for_prefix: "Profil pro "
# profile_for_suffix: ""
profile: "Profil"
user_not_found: "Uživatel nenalezen. Zkontrolujte adresu URL?"
gravatar_not_found_mine: "Nenalezli jsme profil asociovaný s:"
gravatar_not_found_email_suffix: "."
gravatar_signup_prefix: "Přihlásit se "
gravatar_signup_suffix: " k nastavení!"
gravatar_not_found_other: "Bohužel, neexistuje profil asociovaný s touto emailovou adresou."
gravatar_contact: "Kontakt"
gravatar_websites: "Weby"
gravatar_accounts: "Jak zobrazeno na"
gravatar_profile_link: "Účet Gravatar"
play_level:
level_load_error: "Úroveň se nepodařilo otevřít: "
done: "Hotovo"
grid: "Mřížka"
customize_wizard: "Upravit Kouzelníka"
home: "Domů"
guide: "Průvodce"
multiplayer: "Multiplayer"
restart: "Restartovat"
goals: "Cíl"
action_timeline: "Časová osa"
click_to_select: "Vyberte kliknutím."
reload_title: "Znovunačíst veškerý kód?"
reload_really: "Opravdu chcete resetovat tuto úroveň do počátečního stavu?"
reload_confirm: "Znovu načíst vše"
# victory_title_prefix: ""
victory_title_suffix: " Hotovo"
victory_sign_up: "Přihlásit se pro uložení postupu"
victory_sign_up_poke: "Chcete uložit váš kód? Vytvořte si účet zdarma!"
victory_rate_the_level: "Ohodnoťte tuto úroveň: "
# victory_rank_my_game: "Rank My Game"
# victory_ranking_game: "Submitting..."
# victory_return_to_ladder: "Return to Ladder"
victory_play_next_level: "Hrát další úroveň"
victory_go_home: "Přejít domů"
victory_review: "Připomínky!"
victory_hour_of_code_done: "Skončili jste?"
victory_hour_of_code_done_yes: "Ano, pro dnešek jsem skončil!"
multiplayer_title: "Nastavení Multiplayeru"
multiplayer_link_description: "Sdílejte tento odkaz s lidmi, kteří se k vám mohou přidat ve hře."
multiplayer_hint_label: "Tip:"
multiplayer_hint: " Klikněte na odkaz pro jeho výběr, poté stiskněte ⌘-C nebo Ctrl-C pro kopírování odkazu."
multiplayer_coming_soon: "Další vlastnosti multiplayeru jsou na cestě!"
guide_title: "Průvodce"
tome_minion_spells: "Vaše oblíbená kouzla"
tome_read_only_spells: "Kouzla jen pro čtení"
tome_other_units: "Ostatní jednotky"
tome_cast_button_castable: "Spustit"
tome_cast_button_casting: "Spouštění"
tome_cast_button_cast: "Spustit Kouzlo"
tome_autocast_delay: "Prodleva Autospouštení"
tome_select_spell: "Zvolte Kouzlo"
tome_select_a_thang: "Zvolte někoho pro "
tome_available_spells: "Dostupná kouzla"
hud_continue: "Pokračovat (stiskněte shift-mezera)"
spell_saved: "Kouzlo uloženo"
# skip_tutorial: "Skip (esc)"
# editor_config: "Editor Config"
# editor_config_title: "Editor Configuration"
# editor_config_keybindings_label: "Key Bindings"
# editor_config_keybindings_default: "Default (Ace)"
# editor_config_keybindings_description: "Adds additional shortcuts known from the common editors."
# editor_config_invisibles_label: "Show Invisibles"
# editor_config_invisibles_description: "Displays invisibles such as spaces or tabs."
# editor_config_indentguides_label: "Show Indent Guides"
# editor_config_indentguides_description: "Displays vertical lines to see indentation better."
# editor_config_behaviors_label: "Smart Behaviors"
# editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes."
# loading_ready: "Ready!"
# tip_insert_positions: "Shift+Click a point on the map to insert it into the spell editor."
# tip_toggle_play: "Toggle play/paused with Ctrl+P."
# tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward."
# tip_guide_exists: "Click the guide at the top of the page for useful info."
# tip_open_source: "CodeCombat is 100% open source!"
# tip_beta_launch: "CodeCombat launched its beta in October, 2013."
# tip_js_beginning: "JavaScript is just the beginning."
# tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button."
# tip_baby_coders: "In the future, even babies will be Archmages."
# tip_morale_improves: "Loading will continue until morale improves."
# tip_all_species: "We believe in equal opportunities to learn programming for all species."
# tip_reticulating: "Reticulating spines."
# tip_harry: "Yer a Wizard, "
admin:
av_title: "Administrátorský pohled"
av_entities_sub_title: "Entity"
av_entities_users_url: "Uživatelé"
av_entities_active_instances_url: "Aktivní instance"
av_other_sub_title: "Ostatní"
av_other_debug_base_url: "Base (pro debugování base.jade)"
u_title: "Seznam uživatelů"
lg_title: "Poslední hry"
# clas: "CLAs"
editor:
main_title: "Editory CodeCombatu"
main_description: "Vytvořte vlastní úrovně, kampaně, jednotky a vzdělávací obsah. My vám poskytujeme všechny potřebné nástroje!"
article_title: "Editor článků"
article_description: "Napište články, které objasní hráčům koncepty programování využitelné v úrovních a kampaních."
thang_title: "Editor Thangů - objektů"
thang_description: "Vytvořte jednotky, definujte jejich logiku, vlastnosti, grafiku a zvuk. Momentálně jsou podporovány pouze importy vektorové grafiky exportované z Flashe."
level_title: "Editor úrovní"
level_description: "Zahrnuje pomůcky pro skriptování, nahrávání audia a tvorbu vlastní logiky pro vytvoření vlastních úrovní. Obsahuje vše, čeho využíváme k tvorbě úrovní my!"
security_notice: "Velké množství důležitých funkcí těchto editorů je standardně vypnuto. Jak postupem času vylepšujeme bezpečnost celého systému, jsou tyto funkce uvolňovány k veřejnému použití. Potřebujete-li některé funkce dříve, "
contact_us: "kontaktujte nás!"
hipchat_prefix: "Můžete nás také najít v naší"
hipchat_url: "HipChat diskusní místnosti."
# revert: "Revert"
# revert_models: "Revert Models"
level_some_options: "Volby?"
level_tab_thangs: "Thangy"
level_tab_scripts: "Skripty"
level_tab_settings: "Nastavení"
level_tab_components: "Komponenty"
level_tab_systems: "Systémy"
level_tab_thangs_title: "Současné Thangy"
level_tab_thangs_conditions: "Výchozí prostředí"
level_tab_thangs_add: "Přidat Thangy"
level_settings_title: "Nastavení"
level_component_tab_title: "Současné komponenty"
level_component_btn_new: "Vytvořit novou komponentu"
level_systems_tab_title: "Současné systémy"
level_systems_btn_new: "Vytvořit nový systém"
level_systems_btn_add: "Přidat systém"
level_components_title: "Zpět na všechny Thangy"
level_components_type: "Druh"
level_component_edit_title: "Editovat komponentu"
# level_component_config_schema: "Config Schema"
# level_component_settings: "Settings"
level_system_edit_title: "Editovat systém"
create_system_title: "Vytvořit nový systém"
new_component_title: "Vytvořit novou komponentu"
new_component_field_system: "Systém"
# new_article_title: "Create a New Article"
# new_thang_title: "Create a New Thang Type"
# new_level_title: "Create a New Level"
# article_search_title: "Search Articles Here"
# thang_search_title: "Search Thang Types Here"
# level_search_title: "Search Levels Here"
article:
edit_btn_preview: "Náhled"
edit_article_title: "Editovat článek"
general:
and: "a"
name: "Jméno"
body: "Tělo"
version: "Verze"
commit_msg: "Popisek ukládání"
# history: "History"
version_history_for: "Verze historie pro: "
# result: "Result"
results: "Výsledky"
description: "Popis"
or: "nebo"
email: "Email"
# password: "PI:PASSWORD:<PASSWORD>END_PI"
message: "Zpráva"
# code: "Code"
# ladder: "Ladder"
# when: "When"
# opponent: "Opponent"
# rank: "Rank"
# score: "Score"
# win: "Win"
# loss: "Loss"
# tie: "Tie"
# easy: "Easy"
# medium: "Medium"
# hard: "Hard"
about:
who_is_codecombat: "Kdo je CodeCombat?"
why_codecombat: "Proč CodeCombat?"
who_description_prefix: "společně přišli s projektem CodeCombat v roce 2013. V roce 2008 jsme vytvořili také "
who_description_suffix: ", jedničku mezi webovými a IOS aplikacemi pro učení psaní japonských a čínských znaků."
who_description_ending: "Nyní nastal čas pomoci lidem s programováním."
why_paragraph_1: "Při vytváření PI:NAME:<NAME>END_PI neznal PI:NAME:<NAME>END_PI základy programování a byl neustále frustrován svou neschopností implementovat vlastní nápady. Zkoušel se naučit programovat, ale lekce programování byly na něj příliš pomalé. Jeho spolubydlící se rozhodl o rekvalifikaci a tak zkusil Codeacademy, ale brzy toho nechal s tím, že je to příliš velká nuda. Týden co týden se někdo z Georgových přátel pokoušel využít Codeacademyk učení programování, ale po chvíli odpadl. Uvědomili jsme si, že se jedná o stejný problém, který jsme již vyřešili při tvorbě PI:NAME:<NAME>END_PIu: lidé se pokouší učit na pomalých, intenzivních teoretických lekcích, ale místo toho potřebují rychlé, ale obsáhlé praktické cvičení. A na tento problém známe řešení."
why_paragraph_2: "Potřebujete se naučit programovat? Pak nepotřebujete lekce, potřebuje příležitost psát spoustu kódu a při tom se u toho dobře bavit."
why_paragraph_3_prefix: "To je to o čem musí programování být. Ne rádoby zábava typu"
why_paragraph_3_italic: "hmm, další odznáček"
why_paragraph_3_center: "ale nadšení typu"
why_paragraph_3_italic_caps: "POČKEJ MAMI, MUSÍM DOKONČIT ÚROVEŇ!"
why_paragraph_3_suffix: "Proto je CodeCombat opravdová multiplayer hra, ne lekce kurzu s herními odznáčky. Neskončí, dokud sami nepřestanete, což je tentokrát dobrá věc."
why_paragraph_4: "A jestli se máte stát závislými na nějaké hře, pak ať je to hra tato, a staňte se díky tomu kouzelníky a odborníky v této technické době."
why_ending: "A mimochodem - je to zdarma. "
why_ending_url: "Začněte kouzlit!"
george_description: "CEO, obchodník, návrhář webů i her a šampión všech začátečníků programování."
scott_description: "Výtečný programátor, softwarový architekt, kouzelník v kuchyni i pán financí. PI:NAME:<NAME>END_PI je v týmu pan rozumný."
nick_description: "Programátorský kouzelník, excentrický motivační mág i experimentátor. PI:NAME:<NAME>END_PI by mohl dělat de-facto cokoliv, ale zvolil si vytvořit CodeCombat."
jeremy_description: "Mistr zákaznické podpory, tester použitelnosti a organizátor komunity. Je velmi pravděpodobné, že jste si spolu již psali."
michael_description: "Programátor, systémový administrátor a král podsvětí technického zázemí. PI:NAME:<NAME>END_PI udržuje naše servery online."
# glen_description: "Programmer and passionate game developer, with the motivation to make this world a better place, by developing things that matter. The word impossible can't be found in his dictionary. Learning new skills is his joy!"
legal:
page_title: "Licence"
opensource_intro: "CodeCombat je zdarma a plně open source."
opensource_description_prefix: "Podívejte se na "
github_url: "naši stránku na GitHubu"
opensource_description_center: "a pokud se vám chce, můžete i pomoct! CodeCombat je vystavěn na několika oblíbených svobodných projektech. Podívejte se na"
archmage_wiki_url: "naši wiki Arcikouzelníků "
opensource_description_suffix: "pro seznam projektů, díky kterým může tato hra existovat."
practices_title: "Doporučené postupy"
practices_description: "Toto je příslib našeho přístupu v jednoduchém jazyce."
privacy_title: "Soukromí"
privacy_description: "Neprodáme vaše osobní informace. Náš plán na zhodnocení je založen na poskytování pracovních příležitostí, přesto si můžete být jisti, že vaše osobní informace nebudou distribuovány bez vašeho plného souhlasu."
security_title: "Zabezpečení"
security_description: "Usilujeme o to, abychom udrželi vaše osobní informace v bezpečí. Jako otevřený projekt jsme přístupni komukoliv k provedení kontroly kódu pro zlepšení našich bezpečnostních systémů."
email_title: "Email"
email_description_prefix: "Nebudeme vás zaplavovat nevyžádanou korespondencí. Pomocí "
email_settings_url: " nastavení emailu"
email_description_suffix: "nebo skrze odkazy v odeslaných emailech si můžete nastavit nebo se kdykoliv odhlásit z naší korespondence."
cost_title: "Cena"
cost_description: "Momentálně je CodeCombat 100% zdarma! Naší snahou je udržet přístup zdarma, abychom dali možnost hrát co největšímu množství lidí. V případě nutnosti budeme muset přejít na placený vstup nebo platbu za přístup k určitému obsahu, ale raději bychom se tomu vyhnuli. S trochou štěstí doufáme v následující plán monetizace:"
recruitment_title: "PI:NAME:<NAME>END_PI"
recruitment_description_prefix: "Zde na CodeCombatu se stanete mocným kouzelníkem a to nejen ve hře, ale i v reálném životě."
url_hire_programmers: "O dobré programátory je stále velký zájem "
recruitment_description_suffix: "takže až se vypracujete a pokud budete souhlasit, budeme demonstrovat vaše nejlepší programátorské úspěchy tisícovkám zaměstnavatelů, kteří by vás rádi zaměstnali. Ti nám zaplatí něco málo, ale vám pak zaplatí "
recruitment_description_italic: "daleko více,"
recruitment_description_ending: "tato hra zůstane zdarma a všichni budou spokojeni. Takový je plán."
copyrights_title: "Copyrights a Licence"
contributor_title: "Licenční ujednání přispívatelů (CLA)"
contributor_description_prefix: "Všichni přispívatelé jak na webu tak do projektu na GitHubu spadají pod naše "
cla_url: "CLA"
contributor_description_suffix: "se kterým je nutno souhlasit před tím, nežli přispějete."
code_title: "Kód - MIT"
code_description_prefix: "Veškerý kód vlastněný CodeCombatem nebo hostovaným na codecombat.com, kód v repozitáři na GitHub repository nebo v databázi codecombat.com, je licencován pod "
mit_license_url: "MIT licencí"
code_description_suffix: "Zahrnut je veškerý kód v systémech a komponentech, které jsou zpřístupněné CodeCombatem pro vytváření úrovní."
art_title: "Art/Hudba - Creative Commons "
art_description_prefix: "Veškerý obecný obsah je dostupný pod "
cc_license_url: "Mezinárodní Licencí Creative Commons Attribution 4.0"
art_description_suffix: "Obecným obsahem se rozumí vše dostupné na CodeCombatu, určené k vytváření úrovní. To zahrnuje:"
art_music: "Hudbu"
art_sound: "Zvuky"
art_artwork: "Umělecká díla"
art_sprites: "Doplňkový kód"
art_other: "A veškeré další kreativní práce použité při vytváření úrovní."
art_access: "Momentálně neexistuje jednoduchý systém pro stažení těchto součástí, částí úrovní a podobně. Lze je stáhnout z URL adres na tomto webu, můžete nás kontaktovat se žádostí o informace nebo nám i pomoci ve sdílení a vytváření systému pro jednoduché sdílení těchto doplňkových součástí."
art_paragraph_1: "Při uvádění zdroje, uvádějte prosím jméno a odkaz na codecombat.com v místech, která jsou vhodná a kde je to možné. Například:"
use_list_1: "Při použití ve filmu uveďte codecombat.com v titulcích."
use_list_2: "Při použití na webu, zahrňte odkaz například pod obrázkem/odkazem, nebo na stránce uvádějící zdroj, kde také zmíníte další Creative Commons díla a další použité open source projekty. Ostatní, na CodeCombat odkazující se práce (například článek na blogu zmiňující CodeCombat) není nutno separátně označovat a uvádět zdroj."
art_paragraph_2: "Využíváte-li obsah vytvořený některým uživatelem na codecombat.com, uvádějte odkaz na zdroj přímo na tohoto autora a následujte doporučení uvádění zdroje daného obsahu, je-li uvedeno."
rights_title: "Práva vyhrazena"
rights_desc: "Všechna práva jsou vyhrazena jednotlivým samostatným úrovním. To zahrnuje"
rights_scripts: "Skripty"
rights_unit: "Unit konfigurace"
rights_description: "Popisy"
rights_writings: "Zápisy"
rights_media: "Média (zvuky, hudba) a další tvořivý obsah vytvořený specificky pro tuto úroveň, který nebyl zpřístupněn při vytváření úrovně."
rights_clarification: "Pro ujasnění - vše, co je dostupné v editoru úrovní při vytváření úrovně spadá pod CC, ale obsah vytvořený v editoru úrovní nebo nahraný při vytváření spadá pod úroveň."
nutshell_title: "Ve zkratce"
nutshell_description: "Vše co je poskytnuto v editoru úrovní je zdarma a mžete toho využít při vytváření úrovní. Ale vyhrazujeme si právo omezit distribuci úrovní samotných (těch, které byly vytvořeny na codecombat.com), takže v budoucnu bude možno tyto zpoplatnit, bude-li to v nejhorším případě nutné"
canonical: "Anglická verze tohoto dokumentu je původní, rozhodující verzí. Nastane-li rozdíl v překladu, Anglická verze bude mít vždy přednost."
contribute:
page_title: "Přispívání"
character_classes_title: "Obsazení rolí"
introduction_desc_intro: "Vkládáme do CodeCombatu velké naděje."
introduction_desc_pref: "Chceme být to místo, ve kterém se všichni programátoři sejdou pro společnou hru a učení, uvedou další do úžasného světa programování a kde se předvede elita. Víme, že toto sami nezvládneme, jsou to lidé, kteří dělají projekty typu GitHub, Stack Overflow a Linux úspěšnými. Za tímto účelem, "
introduction_desc_github_url: "CodeCombat je kompletně open source"
introduction_desc_suf: "a snažíme se jak jen to jde, abychom vám umožnili se do tohoto projektu zapojit."
introduction_desc_ending: "Doufáme, že se k nám přidáte!"
introduction_desc_signature: "- PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
alert_account_message_intro: "Vítejte!"
alert_account_message_pref: "K přihlášení odebírání emailů si nejprve musíte "
alert_account_message_suf: "vytvořit účet"
alert_account_message_create_url: "."
# archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever."
archmage_introduction: "Jedna z nejlepších věcí na vytváření her je to, že se jedná o spojení různých procesů. Grafika, zvuk, síťování v reálném čase, mezilidské vztahy a samozřejmě také spousta běžných aspektů programování, od nízkoúrovňového managementu databáze přes administraci serverů až po tvorbu uživatelská rozhraní. Je zde spousta práce a pokud jste zkušený programátor a všeuměl připravený k ponoření se do hloubek CodeCombatu, tato skupina je pro vás. Budeme moc rádi za vaši pomoc při tvorbě té nejlepší programovací hry."
class_attributes: "Vlastnosti"
archmage_attribute_1_pref: "Znáte "
archmage_attribute_1_suf: "nebo se jej chcete naučit. Je v něm většina našeho kódu. Je-li vaším oblíbeným jazykem Ruby nebo Python, budete se cítit jako doma. Je to JavaScript, ale s lepší syntaxí."
archmage_attribute_2: "Zkušenosti s programováním a osobní iniciativa. Pomůžeme vám se zorientovat, ale nemůžeme vás učit."
how_to_join: "Jak se přidat"
join_desc_1: "Pomoct může kdokoliv! Pro začátek se podívejte na naši stránku na "
join_desc_2: " , zaškrtněte políčko níže - označíte se tím jako statečný Arcimág a začnete dostávat informace o novinkách emailem. Chcete popovídat o tom jak začít? "
join_desc_3: ", nebo se s námi spojte v naší "
join_desc_4: "!"
join_url_email: "Pošlete nám email"
join_url_hipchat: "veřejné HipChat chatovací místnosti"
more_about_archmage: "Dozvědět se více o tom, jak se stát mocným Arcimágem"
archmage_subscribe_desc: "Dostávat emailem oznámení a informacemi nových programovacích příležitostech"
# artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to"
# artisan_summary_suf: "then this class is for you."
artisan_introduction_pref: "Musíme vytvářet další úrovně! Lidé nás prosí o další obsah, ale sami zvládáme vytvořit jen málo. Naším prvním pracovním zastavením je první úroveň. Editor úrovní je tak-tak použitelný i pro jeho vlastní tvůrce. Máte-li vizi pro vytvoření vnořených úrovní alá "
artisan_introduction_suf: "pak neváhejte, toto je vaše destinace."
artisan_attribute_1: "Předchozí zkušenosti s vytvářením podobného obsahu by byly vítány, například z editorů úrovní Blizzardu, ale nejsou vyžadovány!"
artisan_attribute_2: "Připraveni ke spoustě testování a pokusů. K vytvoření dobré úrovně je potřeba je představit ostatním, nechat je hrát a pak je z velké části měnit a opravovat."
artisan_attribute_3: "Pro teď, stejné jako Dobrodruh - tester úrovní. Náš editor úrovní je ve velmi raném stádiu a frustrující při používání. Varovali jsme vás!"
artisan_join_desc: "Použijte editor úrovní v těchto postupných krocích:"
artisan_join_step1: "Přečtěte si dokumentaci."
artisan_join_step2: "Vytvořte novou úroveň a prozkoumejte existující úrovně."
artisan_join_step3: "Požádejte nás o pomoc ve veřejné HipChat místnosti."
artisan_join_step4: "Zveřejněte vaši úroveň na fóru pro připomínkování."
more_about_artisan: "Dozvědět se více o tom, jak se stát kreativním Řemeslníkem"
artisan_subscribe_desc: "Dostávat emailem oznámení a informace o aktualizacích editoru úrovní."
# adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you."
adventurer_introduction: "Ujasněme si dopředu jednu věc o vaší roli: budete jako tank. Projdete ohněm. Potřebujeme někoho, kdo odzkouší zbrusu nové úrovně a pomůže identifikovat kde je možno je zlepšit. Ten boj bude ohromný - tvorba her je dlouhý proces, který nikdo nezvládne na první pokus. Máte-li na to a vydržíte-li to, pak toto je vaše skupina."
adventurer_attribute_1: "Touha po učení se. Vy se chcete naučit programovat a my vás to chceme naučit. Jenom, v tomto případě to budete vy, kdo bude vyučovat."
adventurer_attribute_2: "Charismatický. Buďte mírný a pečlivě artikulujte co a jak je potřeba zlepšit."
adventurer_join_pref: "Buďto se spojte (nebo si najděte!) PI:NAME:<NAME>END_PI a pracujte s ním, nebo zaškrtněte políčko níže a dostávejte emaily o dostupnosti nových úrovní k testování. Budeme také posílat informace o nových úrovních k recenzím na sociálních webech, "
adventurer_forum_url: " našem fóru"
adventurer_join_suf: "takže pokud chcete být v obraze, připojte se k nám!"
more_about_adventurer: "Dozvědět se více o tom, jak se stát statečným PI:NAME:<NAME>END_PIhem"
adventurer_subscribe_desc: "Dostávat emailem oznámení a informace nových úrovních k testování."
# scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the "
# scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you."
scribe_introduction_pref: "CodeCombat nebude pouze kupa úrovní. Bude také zahrnovat informační zdroje a wiki programovacích konceptů na které se úrovně mohou navázat. Takto, namísto toho aby každý Řemeslník musel sám do detailu popsatco který operátor dělá, mohou jednoduše nalinkovat svoji úroveň na článek existující k edukaci hráčů. Něco ve stylu "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jestliže vás baví popisovat a předávat koncept programování v Markdown editoru, pak tato role může být právě pro vás."
scribe_attribute_1: "Zkušenost s psaním je jediné co budete potřebovat. Nejen gramatika, ale také schopnost popsat složité koncepty a myšlenky ostatním."
contact_us_url: "Spojte se s námi"
scribe_join_description: "dejte nám o vás vědět, o vašich zkušenostech s programováním a o čm byste rádi psali. Od toho začneme!"
more_about_scribe: "Dozvědět se více o tom, jak se stát pilným Pisálkem"
scribe_subscribe_desc: "Dostávat emailem oznámení a informace o článcích."
# diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you."
diplomat_introduction_pref: "Jedna z věcí, kterou jsme zjistili během "
diplomat_launch_url: "zahájení v Říjnu"
diplomat_introduction_suf: "bylo, že o CodeCombat je velký zájem i v jiných zemích, obzvláště v Brazílii! Chystáme regiment překladatelů ke zpřístupnění CodeCombatu světu. Pokud chcete nakouknout pod pokličku, dozvědět se o připravovaných novinkách a zpřístupnit úrovně vašim národním kolegům, toto je role pro vás."
diplomat_attribute_1: "Plynulost v angličtině a v jazyce do kterého budete překládat. Při předávání komplexních myšlenek je důležité si být jistí v kramflecích v obou jazycích!"
# diplomat_join_pref_github: "Find your language locale file "
# diplomat_github_url: "on GitHub"
# diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!"
more_about_diplomat: "Dozvědět se více o tom, jak se stát Diplomatem"
diplomat_subscribe_desc: "Dostávat emailem oznámení a informace o internacionalizaci a o úrovních k překladu."
# ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you."
ambassador_introduction: "Zde se tvoří komunita a vy jste její spojení. Využíváme chat, emaily a sociální sítě se spoustou lidí k informování a diskuzím a seznámení s naší hrou. Chcete-li pomoci lidem se přidat a pobavit se a získat dobrý náhled na CodeCombat a kam směřujeme, pak toto je vaše role."
ambassador_attribute_1: "Komunikační schopnosti. Schopnost identifikovat problémy hráčů a pomoci jim je řešit. Naslouchat co hráči říkají, co mají rádi a co rádi nemají a komunikovat to zpět ostatním!"
ambassador_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Od toho začneme!"
ambassador_join_note_strong: "Poznámka"
ambassador_join_note_desc: "Jedna z našich priorit je vytvoření vícehráčové hry, kde hráč, který má problém s řešením úrovní může oslovit a požádat o pomoc zkušenější kouzelníky. To je přesně ten případ a místo pro pomoc Velvyslance . Dáme vám vědět více!"
more_about_ambassador: "Dozvědět se více o tom, jak se stát nápomocným Velvyslancem"
ambassador_subscribe_desc: "Dostávat emailem oznámení a informace o vývoji v podpoře a vícehráčové hře."
# counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you."
counselor_introduction_1: "Máte životní zkušenosti? Máte odlišný náhled na věci a jste schopni nám tímto pomoci v dalším vývoji CodeCombatu? Jedna z důležitých rolí i když asi nejméně časově náročná, nicméně každá individualita je schopná udělat velký rozdíl. Hledáme zkušené odborníky, zvláště pak v oblastech vzdělávání, vývoji her managementu open source, source project management, náboru lidských zdrojů, podnikání nebo designu."
counselor_introduction_2: "Nebo cokoliv, co je relevantní ve vývoji CodeCombatu. Máte-li znalosti a jste-li ochotni se o ně podělit pro další růst tohoto projektu , pak toto je role pro vás."
counselor_attribute_1: "Zkušenosti ve výše zmíněných oblastech, nebo něco, čím byste mohli být nápomocni."
counselor_attribute_2: "Troška volného času!"
counselor_join_desc: "dejte nám o sobě vědět, o tom co děláte a co byste rádi dělali. Přidáme si vás do seznamu a budeme vás kontaktovat v případě, že to bude potřeba (ne moc často)."
more_about_counselor: "Dozvědět se více o tom, jak se stát Poradcem"
changes_auto_save: "Změny jsou automaticky uloženy při kliknutí na zaškrtávací políčka."
diligent_scribes: "Naši pilní Písaři:"
powerful_archmages: "Naši mocní Arcimágové:"
creative_artisans: "Naši kreativní Řemeslníci:"
brave_adventurers: "Naši stateční Dobrodruzi:"
translating_diplomats: "Naši překladatelští Diplomati:"
helpful_ambassadors: "Naši nápomocní Velvyslanci:"
classes:
archmage_title: "Arcikouzelník"
archmage_title_description: "(Programátor)"
artisan_title: "Řemeslník"
artisan_title_description: "(Tvůrce úrovní)"
adventurer_title: "PI:NAME:<NAME>END_PI"
adventurer_title_description: "(Tester úrovní)"
scribe_title: "PPI:NAME:<NAME>END_PI"
scribe_title_description: "(Editor článků)"
diplomat_title: "Diplomat"
diplomat_title_description: "(Překladatel)"
ambassador_title: "Velvyslanec"
ambassador_title_description: "(Podpora)"
counselor_title: "Poradce"
counselor_title_description: "(Odborník)"
# ladder:
# please_login: "Please log in first before playing a ladder game."
# my_matches: "My Matches"
# simulate: "Simulate"
# simulation_explanation: "By simulating games you can get your game ranked faster!"
# simulate_games: "Simulate Games!"
# simulate_all: "RESET AND SIMULATE GAMES"
# games_simulated_by: "Games simulated by you:"
# games_simulated_for: "Games simulated for you:"
# leaderboard: "Leaderboard"
# battle_as: "Battle as "
# summary_your: "Your "
# summary_matches: "Matches - "
# summary_wins: " PI:NAME:<NAME>END_PI, "
# summary_losses: " Losses"
# rank_no_code: "No New Code to Rank"
# rank_my_game: "Rank My Game!"
# rank_submitting: "Submitting..."
# rank_submitted: "Submitted for Ranking"
# rank_failed: "Failed to Rank"
# rank_being_ranked: "Game Being Ranked"
# code_being_simulated: "Your new code is being simulated by other players for ranking. This will refresh as new matches come in."
# no_ranked_matches_pre: "No ranked matches for the "
# no_ranked_matches_post: " team! Play against some competitors and then come back here to get your game ranked."
# choose_opponent: "Choose an Opponent"
# tutorial_play: "Play Tutorial"
# tutorial_recommended: "Recommended if you've never played before"
# tutorial_skip: "Skip Tutorial"
# tutorial_not_sure: "Not sure what's going on?"
# tutorial_play_first: "Play the Tutorial first."
# simple_ai: "Simple AI"
# warmup: "Warmup"
# vs: "VS"
# multiplayer_launch:
# introducing_dungeon_arena: "Introducing Dungeon Arena"
# new_way: "March 17, 2014: The new way to compete with code."
# to_battle: "To Battle, Developers!"
# modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here."
# arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here."
# ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even"
# fork_our_arenas: "fork our arenas"
# create_worlds: "and create your own worlds."
# javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a"
# tutorial: "tutorial"
# new_to_programming: ". New to programming? Hit our beginner campaign to skill up."
# so_ready: "I Am So Ready for This"
|
[
{
"context": "/_____/\n\n gtl.js ~ v0.1.0 ~ https://github.com/kossnocorp/gtl\n\n Greater than less\n\n The MIT License\n\n Co",
"end": 205,
"score": 0.7675294280052185,
"start": 197,
"tag": "USERNAME",
"value": "ssnocorp"
},
{
"context": "than less\n\n The MIT License\n\n Copyright (c) 2012 Sasha Koss\n###\n\n# Define main object\ngtl = {}\n\n###\n Interna",
"end": 282,
"score": 0.999803900718689,
"start": 272,
"tag": "NAME",
"value": "Sasha Koss"
}
] | src/gtl.coffee | kossnocorp/gtl | 1 | ###
______ ______ __
/\ ___\ /\__ _\ /\ \
\ \ \__ \ \/_/\ \/ \ \ \____
\ \_____\ \ \_\ \ \_____\
\/_____/ \/_/ \/_____/
gtl.js ~ v0.1.0 ~ https://github.com/kossnocorp/gtl
Greater than less
The MIT License
Copyright (c) 2012 Sasha Koss
###
# Define main object
gtl = {}
###
Internal: clone array
###
clone = (array) -> array.slice()
###
Internal: merge objects
###
merge = (a = {}, b = {}) ->
result = {}
copyPropsToResult = (obj) ->
for own key, value of obj
result[key] = value
copyPropsToResult(a)
copyPropsToResult(b)
result
###
Internal: get element by path
###
getByPath = (obj, path) ->
if path.constructor == String
getByPath(obj, path.split('.'))
else
if path.length == 1
obj[path]
else
getByPath(obj[path[0]], path.slice(1))
###
Internal: is satisfied to iterator rule
###
isSatisfiedToIteratorRule = (rule, results) ->
switch rule
when 'or'
results.indexOf(true) != -1
when 'and'
results.indexOf(false) == -1
###
Internal: filter array by rule and return copy
###
filter = (array, comparator, rule, iterator) ->
result = []
for elm in array
satisfied = false
if iterator.constructor == Function
satisfied = true if comparator(iterator(elm), rule)
else
satisfied = true
# Each iterator rule (or, and)
for iteratorRule in iterator
do ->
results = []
compare = (iterator) ->
results.push \
comparator(getByPath(elm, iterator), rule)
switch iteratorRule.iterator.constructor
when String
compare(iteratorRule.iterator)
when Array
compare(i) for i in iteratorRule.iterator
unless isSatisfiedToIteratorRule(iteratorRule.rule, results)
satisfied = false
result.push(elm) if satisfied
result
###
Private: create filter function
###
createFilter = (rulesObj) ->
(array, rules, iterator) ->
result = clone(array)
unless iterator
iterator = []
if rules.or or rules.in
iterator.push(rule: 'or', iterator: rules.or || rules.in)
if rules.and
iterator.push(rule: 'and', iterator: rules.and)
if iterator.length == 0
iterator = (elm) -> elm
for name, rule of rules
if ['or', 'in', 'and'].indexOf(name) == -1
result = filter(result, rulesObj[name], rule, iterator)
result
# Define rules object
gtl.rules = {}
# Define filter function
gtl.filter = createFilter(gtl.rules)
###
Public: greater than comparator
###
gtl.rules.gt = gtl.rules.greaterThan = (a, b) -> a > b
###
Public: greater than or equal to comparator
###
gtl.rules.gte = gtl.rules.gteq = gtl.rules.greaterThanOrEqualTo =
(a, b) -> a >= b
###
Public: less than comparator
###
gtl.rules.lt = gtl.rules.lessThan = (a, b) -> a < b
###
Public: less than or equal to comparator
###
gtl.rules.lte = gtl.rules.lteq = gtl.rules.lessThanOrEqualTo =
(a, b) -> a <= b
###
Public: only comparator
###
gtl.rules.only = (a, bs) ->
if bs.constructor == Array
bs.indexOf(a) != -1
else
a == bs
###
Public: except comparator
###
gtl.rules.not = gtl.rules.except = (a, bs) ->
not gtl.rules.only(a, bs)
###
Public: grep comparator
###
gtl.rules.grep = (str, substr) ->
str.search(substr) != -1
###
Public: fuzzy comparator
###
gtl.rules.fuzzy = (str, searchStr) ->
subStr = str
for char in searchStr
if -1 != i = subStr.search(char)
subStr = subStr.slice(i + 1)
else
return false
true
###
Public: curry function
###
gtl.curry = (curriedRules, curriedIterator) ->
(array, userRules, userIterator = curriedIterator) ->
if userRules and userRules.constructor == Function
rules = curriedRules
iterator = userRules
else
rules = merge(curriedRules, userRules)
iterator = userIterator
gtl.filter(array, rules, iterator)
###
Public: clone gtl object
###
gtl.clone = ->
newGtl = merge(gtl)
newGtl.rules = merge(gtl.rules)
newGtl.filter = createFilter(newGtl.rules)
newGtl
# Export gtl to global scope
if window?
window.gtl = gtl
else
module.exports = gtl
| 224075 | ###
______ ______ __
/\ ___\ /\__ _\ /\ \
\ \ \__ \ \/_/\ \/ \ \ \____
\ \_____\ \ \_\ \ \_____\
\/_____/ \/_/ \/_____/
gtl.js ~ v0.1.0 ~ https://github.com/kossnocorp/gtl
Greater than less
The MIT License
Copyright (c) 2012 <NAME>
###
# Define main object
gtl = {}
###
Internal: clone array
###
clone = (array) -> array.slice()
###
Internal: merge objects
###
merge = (a = {}, b = {}) ->
result = {}
copyPropsToResult = (obj) ->
for own key, value of obj
result[key] = value
copyPropsToResult(a)
copyPropsToResult(b)
result
###
Internal: get element by path
###
getByPath = (obj, path) ->
if path.constructor == String
getByPath(obj, path.split('.'))
else
if path.length == 1
obj[path]
else
getByPath(obj[path[0]], path.slice(1))
###
Internal: is satisfied to iterator rule
###
isSatisfiedToIteratorRule = (rule, results) ->
switch rule
when 'or'
results.indexOf(true) != -1
when 'and'
results.indexOf(false) == -1
###
Internal: filter array by rule and return copy
###
filter = (array, comparator, rule, iterator) ->
result = []
for elm in array
satisfied = false
if iterator.constructor == Function
satisfied = true if comparator(iterator(elm), rule)
else
satisfied = true
# Each iterator rule (or, and)
for iteratorRule in iterator
do ->
results = []
compare = (iterator) ->
results.push \
comparator(getByPath(elm, iterator), rule)
switch iteratorRule.iterator.constructor
when String
compare(iteratorRule.iterator)
when Array
compare(i) for i in iteratorRule.iterator
unless isSatisfiedToIteratorRule(iteratorRule.rule, results)
satisfied = false
result.push(elm) if satisfied
result
###
Private: create filter function
###
createFilter = (rulesObj) ->
(array, rules, iterator) ->
result = clone(array)
unless iterator
iterator = []
if rules.or or rules.in
iterator.push(rule: 'or', iterator: rules.or || rules.in)
if rules.and
iterator.push(rule: 'and', iterator: rules.and)
if iterator.length == 0
iterator = (elm) -> elm
for name, rule of rules
if ['or', 'in', 'and'].indexOf(name) == -1
result = filter(result, rulesObj[name], rule, iterator)
result
# Define rules object
gtl.rules = {}
# Define filter function
gtl.filter = createFilter(gtl.rules)
###
Public: greater than comparator
###
gtl.rules.gt = gtl.rules.greaterThan = (a, b) -> a > b
###
Public: greater than or equal to comparator
###
gtl.rules.gte = gtl.rules.gteq = gtl.rules.greaterThanOrEqualTo =
(a, b) -> a >= b
###
Public: less than comparator
###
gtl.rules.lt = gtl.rules.lessThan = (a, b) -> a < b
###
Public: less than or equal to comparator
###
gtl.rules.lte = gtl.rules.lteq = gtl.rules.lessThanOrEqualTo =
(a, b) -> a <= b
###
Public: only comparator
###
gtl.rules.only = (a, bs) ->
if bs.constructor == Array
bs.indexOf(a) != -1
else
a == bs
###
Public: except comparator
###
gtl.rules.not = gtl.rules.except = (a, bs) ->
not gtl.rules.only(a, bs)
###
Public: grep comparator
###
gtl.rules.grep = (str, substr) ->
str.search(substr) != -1
###
Public: fuzzy comparator
###
gtl.rules.fuzzy = (str, searchStr) ->
subStr = str
for char in searchStr
if -1 != i = subStr.search(char)
subStr = subStr.slice(i + 1)
else
return false
true
###
Public: curry function
###
gtl.curry = (curriedRules, curriedIterator) ->
(array, userRules, userIterator = curriedIterator) ->
if userRules and userRules.constructor == Function
rules = curriedRules
iterator = userRules
else
rules = merge(curriedRules, userRules)
iterator = userIterator
gtl.filter(array, rules, iterator)
###
Public: clone gtl object
###
gtl.clone = ->
newGtl = merge(gtl)
newGtl.rules = merge(gtl.rules)
newGtl.filter = createFilter(newGtl.rules)
newGtl
# Export gtl to global scope
if window?
window.gtl = gtl
else
module.exports = gtl
| true | ###
______ ______ __
/\ ___\ /\__ _\ /\ \
\ \ \__ \ \/_/\ \/ \ \ \____
\ \_____\ \ \_\ \ \_____\
\/_____/ \/_/ \/_____/
gtl.js ~ v0.1.0 ~ https://github.com/kossnocorp/gtl
Greater than less
The MIT License
Copyright (c) 2012 PI:NAME:<NAME>END_PI
###
# Define main object
gtl = {}
###
Internal: clone array
###
clone = (array) -> array.slice()
###
Internal: merge objects
###
merge = (a = {}, b = {}) ->
result = {}
copyPropsToResult = (obj) ->
for own key, value of obj
result[key] = value
copyPropsToResult(a)
copyPropsToResult(b)
result
###
Internal: get element by path
###
getByPath = (obj, path) ->
if path.constructor == String
getByPath(obj, path.split('.'))
else
if path.length == 1
obj[path]
else
getByPath(obj[path[0]], path.slice(1))
###
Internal: is satisfied to iterator rule
###
isSatisfiedToIteratorRule = (rule, results) ->
switch rule
when 'or'
results.indexOf(true) != -1
when 'and'
results.indexOf(false) == -1
###
Internal: filter array by rule and return copy
###
filter = (array, comparator, rule, iterator) ->
result = []
for elm in array
satisfied = false
if iterator.constructor == Function
satisfied = true if comparator(iterator(elm), rule)
else
satisfied = true
# Each iterator rule (or, and)
for iteratorRule in iterator
do ->
results = []
compare = (iterator) ->
results.push \
comparator(getByPath(elm, iterator), rule)
switch iteratorRule.iterator.constructor
when String
compare(iteratorRule.iterator)
when Array
compare(i) for i in iteratorRule.iterator
unless isSatisfiedToIteratorRule(iteratorRule.rule, results)
satisfied = false
result.push(elm) if satisfied
result
###
Private: create filter function
###
createFilter = (rulesObj) ->
(array, rules, iterator) ->
result = clone(array)
unless iterator
iterator = []
if rules.or or rules.in
iterator.push(rule: 'or', iterator: rules.or || rules.in)
if rules.and
iterator.push(rule: 'and', iterator: rules.and)
if iterator.length == 0
iterator = (elm) -> elm
for name, rule of rules
if ['or', 'in', 'and'].indexOf(name) == -1
result = filter(result, rulesObj[name], rule, iterator)
result
# Define rules object
gtl.rules = {}
# Define filter function
gtl.filter = createFilter(gtl.rules)
###
Public: greater than comparator
###
gtl.rules.gt = gtl.rules.greaterThan = (a, b) -> a > b
###
Public: greater than or equal to comparator
###
gtl.rules.gte = gtl.rules.gteq = gtl.rules.greaterThanOrEqualTo =
(a, b) -> a >= b
###
Public: less than comparator
###
gtl.rules.lt = gtl.rules.lessThan = (a, b) -> a < b
###
Public: less than or equal to comparator
###
gtl.rules.lte = gtl.rules.lteq = gtl.rules.lessThanOrEqualTo =
(a, b) -> a <= b
###
Public: only comparator
###
gtl.rules.only = (a, bs) ->
if bs.constructor == Array
bs.indexOf(a) != -1
else
a == bs
###
Public: except comparator
###
gtl.rules.not = gtl.rules.except = (a, bs) ->
not gtl.rules.only(a, bs)
###
Public: grep comparator
###
gtl.rules.grep = (str, substr) ->
str.search(substr) != -1
###
Public: fuzzy comparator
###
gtl.rules.fuzzy = (str, searchStr) ->
subStr = str
for char in searchStr
if -1 != i = subStr.search(char)
subStr = subStr.slice(i + 1)
else
return false
true
###
Public: curry function
###
gtl.curry = (curriedRules, curriedIterator) ->
(array, userRules, userIterator = curriedIterator) ->
if userRules and userRules.constructor == Function
rules = curriedRules
iterator = userRules
else
rules = merge(curriedRules, userRules)
iterator = userIterator
gtl.filter(array, rules, iterator)
###
Public: clone gtl object
###
gtl.clone = ->
newGtl = merge(gtl)
newGtl.rules = merge(gtl.rules)
newGtl.filter = createFilter(newGtl.rules)
newGtl
# Export gtl to global scope
if window?
window.gtl = gtl
else
module.exports = gtl
|
[
{
"context": "###\n *\n * jQuery Tooltips by Gary Hepting - https://github.com/ghepting/jquery-tooltips\n * ",
"end": 42,
"score": 0.9998958706855774,
"start": 30,
"tag": "NAME",
"value": "Gary Hepting"
},
{
"context": "ery Tooltips by Gary Hepting - https://github.com/ghepting/jquery-tooltips\n * \n * Open source under the MI",
"end": 72,
"score": 0.9996638894081116,
"start": 64,
"tag": "USERNAME",
"value": "ghepting"
},
{
"context": "ce under the MIT License. \n *\n * Copyright © 2013 Gary Hepting. All rights reserved.\n *\n###\n\n(($) ->\n $.fn.tool",
"end": 170,
"score": 0.9998883008956909,
"start": 158,
"tag": "NAME",
"value": "Gary Hepting"
}
] | src/coffee/plugins/jquery-tooltip.coffee | Shipow/groundwork | 1 | ###
*
* jQuery Tooltips by Gary Hepting - https://github.com/ghepting/jquery-tooltips
*
* Open source under the MIT License.
*
* Copyright © 2013 Gary Hepting. All rights reserved.
*
###
(($) ->
$.fn.tooltip = (options) ->
defaults =
topOffset: 0
delay: 100 # delay before showing (ms)
speed: 100 # animation speed (ms)
options = $.extend(defaults, options)
tooltip = $('#tooltip') # tooltip element
delayShow = '' # delayed open
trigger = '' # store trigger
if $('#tooltip').length != 1
# add tooltip element to DOM
tooltip = $("<div id=\"tooltip\"></div>")
tooltip.appendTo("body").hide()
getElementPosition = (el) ->
offset = el.offset()
win = $(window)
top: top = offset.top - win.scrollTop()
left: left = offset.left - win.scrollLeft()
bottom: bottom = win.height() - top - el.outerHeight()
right: right = win.width() - left - el.outerWidth()
setPosition = (trigger) ->
coords = getElementPosition(trigger)
if tooltip.outerWidth() > ($(window).width() - 20)
tooltip.css('width',$(window).width() - 20)
attrs = {}
tooltip.css('max-width',
Math.min(
($(window).width()-parseInt($('body').css('padding-left'))-parseInt($('body').css('padding-right'))),
parseInt(tooltip.css('max-width'))
)
)
width = tooltip.outerWidth()
height = tooltip.outerHeight()
if coords.left <= coords.right
tooltip.addClass('left')
attrs.left = coords.left
else
tooltip.addClass('right')
attrs.right = coords.right
if (coords.top-options.topOffset) > (height+20)
tooltip.addClass('top')
attrs.top = (trigger.offset().top - height) - 20
else
tooltip.addClass('bottom')
attrs.top = trigger.offset().top + trigger.outerHeight() - 4
tooltip.css attrs
resettooltip = ->
tooltip.text('').removeClass().css
left: 'auto'
right: 'auto'
top: 'auto'
bottom: 'auto'
width: 'auto'
'padding-left': 'auto'
'padding-right': 'auto'
closetooltip = ->
tooltip.stop().hide()
resettooltip()
$('[role=tooltip]').removeClass('on')
showtooltip = (trigger) ->
clearTimeout(delayShow)
delayShow = setTimeout ->
tooltip.css({"opacity": 0, "display": "block"}).text(trigger.attr('data-title'))
$.each ['disabled', 'info', 'alert', 'warning', 'error', 'success', 'green', 'turquoise', 'blue', 'purple', 'pink', 'yellow', 'orange', 'red', 'asphalt'], (index, value) ->
if trigger.hasClass(value)
tooltip.addClass(value)
setPosition(trigger)
trigger.addClass('on')
tooltip.animate
top: "+=10"
opacity: 1
, options.speed
, options.delay
@each ->
$this = $(this)
$this.attr('role','tooltip').attr('data-title',$this.attr('title'))
$this.removeAttr "title"
$('body').on(
'focus', '[role=tooltip]', ->
showtooltip($(this))
).on(
'blur', '[role=tooltip]', ->
clearTimeout(delayShow)
closetooltip()
).on(
'mouseenter', '[role=tooltip]:not(input,select,textarea)', ->
showtooltip($(this))
).on(
'mouseleave', '[role=tooltip]:not(input,select,textarea)', ->
clearTimeout(delayShow)
closetooltip()
)
$(window).on
scroll: ->
trigger = $('[role=tooltip].on')
if trigger.length
setPosition(trigger)
$('#tooltip').css
top: "+=10"
) jQuery
$(document).ready ->
$('.tooltip[title]').tooltip()
| 130913 | ###
*
* jQuery Tooltips by <NAME> - https://github.com/ghepting/jquery-tooltips
*
* Open source under the MIT License.
*
* Copyright © 2013 <NAME>. All rights reserved.
*
###
(($) ->
$.fn.tooltip = (options) ->
defaults =
topOffset: 0
delay: 100 # delay before showing (ms)
speed: 100 # animation speed (ms)
options = $.extend(defaults, options)
tooltip = $('#tooltip') # tooltip element
delayShow = '' # delayed open
trigger = '' # store trigger
if $('#tooltip').length != 1
# add tooltip element to DOM
tooltip = $("<div id=\"tooltip\"></div>")
tooltip.appendTo("body").hide()
getElementPosition = (el) ->
offset = el.offset()
win = $(window)
top: top = offset.top - win.scrollTop()
left: left = offset.left - win.scrollLeft()
bottom: bottom = win.height() - top - el.outerHeight()
right: right = win.width() - left - el.outerWidth()
setPosition = (trigger) ->
coords = getElementPosition(trigger)
if tooltip.outerWidth() > ($(window).width() - 20)
tooltip.css('width',$(window).width() - 20)
attrs = {}
tooltip.css('max-width',
Math.min(
($(window).width()-parseInt($('body').css('padding-left'))-parseInt($('body').css('padding-right'))),
parseInt(tooltip.css('max-width'))
)
)
width = tooltip.outerWidth()
height = tooltip.outerHeight()
if coords.left <= coords.right
tooltip.addClass('left')
attrs.left = coords.left
else
tooltip.addClass('right')
attrs.right = coords.right
if (coords.top-options.topOffset) > (height+20)
tooltip.addClass('top')
attrs.top = (trigger.offset().top - height) - 20
else
tooltip.addClass('bottom')
attrs.top = trigger.offset().top + trigger.outerHeight() - 4
tooltip.css attrs
resettooltip = ->
tooltip.text('').removeClass().css
left: 'auto'
right: 'auto'
top: 'auto'
bottom: 'auto'
width: 'auto'
'padding-left': 'auto'
'padding-right': 'auto'
closetooltip = ->
tooltip.stop().hide()
resettooltip()
$('[role=tooltip]').removeClass('on')
showtooltip = (trigger) ->
clearTimeout(delayShow)
delayShow = setTimeout ->
tooltip.css({"opacity": 0, "display": "block"}).text(trigger.attr('data-title'))
$.each ['disabled', 'info', 'alert', 'warning', 'error', 'success', 'green', 'turquoise', 'blue', 'purple', 'pink', 'yellow', 'orange', 'red', 'asphalt'], (index, value) ->
if trigger.hasClass(value)
tooltip.addClass(value)
setPosition(trigger)
trigger.addClass('on')
tooltip.animate
top: "+=10"
opacity: 1
, options.speed
, options.delay
@each ->
$this = $(this)
$this.attr('role','tooltip').attr('data-title',$this.attr('title'))
$this.removeAttr "title"
$('body').on(
'focus', '[role=tooltip]', ->
showtooltip($(this))
).on(
'blur', '[role=tooltip]', ->
clearTimeout(delayShow)
closetooltip()
).on(
'mouseenter', '[role=tooltip]:not(input,select,textarea)', ->
showtooltip($(this))
).on(
'mouseleave', '[role=tooltip]:not(input,select,textarea)', ->
clearTimeout(delayShow)
closetooltip()
)
$(window).on
scroll: ->
trigger = $('[role=tooltip].on')
if trigger.length
setPosition(trigger)
$('#tooltip').css
top: "+=10"
) jQuery
$(document).ready ->
$('.tooltip[title]').tooltip()
| true | ###
*
* jQuery Tooltips by PI:NAME:<NAME>END_PI - https://github.com/ghepting/jquery-tooltips
*
* Open source under the MIT License.
*
* Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved.
*
###
(($) ->
$.fn.tooltip = (options) ->
defaults =
topOffset: 0
delay: 100 # delay before showing (ms)
speed: 100 # animation speed (ms)
options = $.extend(defaults, options)
tooltip = $('#tooltip') # tooltip element
delayShow = '' # delayed open
trigger = '' # store trigger
if $('#tooltip').length != 1
# add tooltip element to DOM
tooltip = $("<div id=\"tooltip\"></div>")
tooltip.appendTo("body").hide()
getElementPosition = (el) ->
offset = el.offset()
win = $(window)
top: top = offset.top - win.scrollTop()
left: left = offset.left - win.scrollLeft()
bottom: bottom = win.height() - top - el.outerHeight()
right: right = win.width() - left - el.outerWidth()
setPosition = (trigger) ->
coords = getElementPosition(trigger)
if tooltip.outerWidth() > ($(window).width() - 20)
tooltip.css('width',$(window).width() - 20)
attrs = {}
tooltip.css('max-width',
Math.min(
($(window).width()-parseInt($('body').css('padding-left'))-parseInt($('body').css('padding-right'))),
parseInt(tooltip.css('max-width'))
)
)
width = tooltip.outerWidth()
height = tooltip.outerHeight()
if coords.left <= coords.right
tooltip.addClass('left')
attrs.left = coords.left
else
tooltip.addClass('right')
attrs.right = coords.right
if (coords.top-options.topOffset) > (height+20)
tooltip.addClass('top')
attrs.top = (trigger.offset().top - height) - 20
else
tooltip.addClass('bottom')
attrs.top = trigger.offset().top + trigger.outerHeight() - 4
tooltip.css attrs
resettooltip = ->
tooltip.text('').removeClass().css
left: 'auto'
right: 'auto'
top: 'auto'
bottom: 'auto'
width: 'auto'
'padding-left': 'auto'
'padding-right': 'auto'
closetooltip = ->
tooltip.stop().hide()
resettooltip()
$('[role=tooltip]').removeClass('on')
showtooltip = (trigger) ->
clearTimeout(delayShow)
delayShow = setTimeout ->
tooltip.css({"opacity": 0, "display": "block"}).text(trigger.attr('data-title'))
$.each ['disabled', 'info', 'alert', 'warning', 'error', 'success', 'green', 'turquoise', 'blue', 'purple', 'pink', 'yellow', 'orange', 'red', 'asphalt'], (index, value) ->
if trigger.hasClass(value)
tooltip.addClass(value)
setPosition(trigger)
trigger.addClass('on')
tooltip.animate
top: "+=10"
opacity: 1
, options.speed
, options.delay
@each ->
$this = $(this)
$this.attr('role','tooltip').attr('data-title',$this.attr('title'))
$this.removeAttr "title"
$('body').on(
'focus', '[role=tooltip]', ->
showtooltip($(this))
).on(
'blur', '[role=tooltip]', ->
clearTimeout(delayShow)
closetooltip()
).on(
'mouseenter', '[role=tooltip]:not(input,select,textarea)', ->
showtooltip($(this))
).on(
'mouseleave', '[role=tooltip]:not(input,select,textarea)', ->
clearTimeout(delayShow)
closetooltip()
)
$(window).on
scroll: ->
trigger = $('[role=tooltip].on')
if trigger.length
setPosition(trigger)
$('#tooltip').css
top: "+=10"
) jQuery
$(document).ready ->
$('.tooltip[title]').tooltip()
|
[
{
"context": "taging-api.joukou.com'\n else\n 'http://127.0.0.1:2101'\n\n getFQDN: ->\n switch self.getEnvironme",
"end": 957,
"score": 0.9996768236160278,
"start": 948,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " 'http://localhost:2100'\n 'http://127.0.0.1:2100'\n ]\n else\n [\n 'h",
"end": 1627,
"score": 0.9996253252029419,
"start": 1618,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " 'http://localhost:2100'\n 'http://127.0.0.1:2100'\n ]\n\n getOrigin: ->\n return self.",
"end": 1726,
"score": 0.9996193647384644,
"start": 1717,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " clientId = \"REPLACEME\"\n clientSecret = \"REPLACEME\"\n when 'staging'\n clientId = \"REPLACE",
"end": 2149,
"score": 0.916741669178009,
"start": 2140,
"tag": "KEY",
"value": "REPLACEME"
},
{
"context": " clientId = \"REPLACEME\"\n clientSecret = \"REPLACEME\"\n else\n clientId = \"3b349282176a33f7f",
"end": 2236,
"score": 0.8255376219749451,
"start": 2227,
"tag": "KEY",
"value": "REPLACEME"
},
{
"context": "cret = \"REPLACEME\"\n else\n clientId = \"3b349282176a33f7f42e\"\n clientSecret = \"6befeffabcecf885ebeb8e9b",
"end": 2289,
"score": 0.8905969858169556,
"start": 2269,
"tag": "KEY",
"value": "3b349282176a33f7f42e"
},
{
"context": " = \"3b349282176a33f7f42e\"\n clientSecret = \"6befeffabcecf885ebeb8e9b95695c5a4c021461\"\n\n {\n clientId: clientId\n clientSecr",
"end": 2355,
"score": 0.9997232556343079,
"start": 2315,
"tag": "KEY",
"value": "6befeffabcecf885ebeb8e9b95695c5a4c021461"
}
] | src/env.coffee | joukou/joukou-api | 0 | ###*
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.
###
module.exports = self =
getEnvironment: ->
switch process.env.NODE_ENV
when 'production'
'production'
when 'staging'
'staging'
else
'development'
getHost: ->
switch self.getEnvironment()
when 'production'
'https://api.joukou.com'
when 'staging'
'https://staging-api.joukou.com'
else
'http://127.0.0.1:2101'
getFQDN: ->
switch self.getEnvironment()
when 'production'
'api.joukou.com'
when 'staging'
'staging-api.joukou.com'
else
'localhost'
getServerName: ->
switch self.getEnvironment()
when 'production', 'staging'
self.getFQDN()
else
require( '../package.json' ).name
getVersion: ->
require( '../package.json' ).version
getOrigins: ->
switch self.getEnvironment()
when 'production'
[
'https://joukou.com'
]
when 'staging'
[
'https://staging.joukou.com'
'http://localhost:2100'
'http://127.0.0.1:2100'
]
else
[
'http://localhost:2100'
'http://127.0.0.1:2100'
]
getOrigin: ->
return self.getOrigins()[0]
getJWTKey: ->
return 'abc'
getGithubAuth: ->
origin = self.getOrigin()
host = self.getHost()
clientId = null
clientSecret = null
if self.getEnvironment() is 'development'
origin += '/build/testing'
switch self.getEnvironment()
when 'production'
clientId = "REPLACEME"
clientSecret = "REPLACEME"
when 'staging'
clientId = "REPLACEME"
clientSecret = "REPLACEME"
else
clientId = "3b349282176a33f7f42e"
clientSecret = "6befeffabcecf885ebeb8e9b95695c5a4c021461"
{
clientId: clientId
clientSecret: clientSecret
callbackUrl: host + "/agent/authenticate/callback"
failedUrl: origin + "/index.html#/auth/callback/failed"
successUrl: origin + "/index.html#/auth/callback/success"
scope: [
# Associate user with email
'user:email'
# See public and private repositories
'repo'
# Get deployment statuses
'repo_deployment'
# Grants read and ping access to hooks
'read:repo_hook'
# Associate user with other users
'read:org'
]
}
| 57443 | ###*
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.
###
module.exports = self =
getEnvironment: ->
switch process.env.NODE_ENV
when 'production'
'production'
when 'staging'
'staging'
else
'development'
getHost: ->
switch self.getEnvironment()
when 'production'
'https://api.joukou.com'
when 'staging'
'https://staging-api.joukou.com'
else
'http://127.0.0.1:2101'
getFQDN: ->
switch self.getEnvironment()
when 'production'
'api.joukou.com'
when 'staging'
'staging-api.joukou.com'
else
'localhost'
getServerName: ->
switch self.getEnvironment()
when 'production', 'staging'
self.getFQDN()
else
require( '../package.json' ).name
getVersion: ->
require( '../package.json' ).version
getOrigins: ->
switch self.getEnvironment()
when 'production'
[
'https://joukou.com'
]
when 'staging'
[
'https://staging.joukou.com'
'http://localhost:2100'
'http://127.0.0.1:2100'
]
else
[
'http://localhost:2100'
'http://127.0.0.1:2100'
]
getOrigin: ->
return self.getOrigins()[0]
getJWTKey: ->
return 'abc'
getGithubAuth: ->
origin = self.getOrigin()
host = self.getHost()
clientId = null
clientSecret = null
if self.getEnvironment() is 'development'
origin += '/build/testing'
switch self.getEnvironment()
when 'production'
clientId = "REPLACEME"
clientSecret = "<KEY>"
when 'staging'
clientId = "REPLACEME"
clientSecret = "<KEY>"
else
clientId = "<KEY>"
clientSecret = "<KEY>"
{
clientId: clientId
clientSecret: clientSecret
callbackUrl: host + "/agent/authenticate/callback"
failedUrl: origin + "/index.html#/auth/callback/failed"
successUrl: origin + "/index.html#/auth/callback/success"
scope: [
# Associate user with email
'user:email'
# See public and private repositories
'repo'
# Get deployment statuses
'repo_deployment'
# Grants read and ping access to hooks
'read:repo_hook'
# Associate user with other users
'read:org'
]
}
| true | ###*
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.
###
module.exports = self =
getEnvironment: ->
switch process.env.NODE_ENV
when 'production'
'production'
when 'staging'
'staging'
else
'development'
getHost: ->
switch self.getEnvironment()
when 'production'
'https://api.joukou.com'
when 'staging'
'https://staging-api.joukou.com'
else
'http://127.0.0.1:2101'
getFQDN: ->
switch self.getEnvironment()
when 'production'
'api.joukou.com'
when 'staging'
'staging-api.joukou.com'
else
'localhost'
getServerName: ->
switch self.getEnvironment()
when 'production', 'staging'
self.getFQDN()
else
require( '../package.json' ).name
getVersion: ->
require( '../package.json' ).version
getOrigins: ->
switch self.getEnvironment()
when 'production'
[
'https://joukou.com'
]
when 'staging'
[
'https://staging.joukou.com'
'http://localhost:2100'
'http://127.0.0.1:2100'
]
else
[
'http://localhost:2100'
'http://127.0.0.1:2100'
]
getOrigin: ->
return self.getOrigins()[0]
getJWTKey: ->
return 'abc'
getGithubAuth: ->
origin = self.getOrigin()
host = self.getHost()
clientId = null
clientSecret = null
if self.getEnvironment() is 'development'
origin += '/build/testing'
switch self.getEnvironment()
when 'production'
clientId = "REPLACEME"
clientSecret = "PI:KEY:<KEY>END_PI"
when 'staging'
clientId = "REPLACEME"
clientSecret = "PI:KEY:<KEY>END_PI"
else
clientId = "PI:KEY:<KEY>END_PI"
clientSecret = "PI:KEY:<KEY>END_PI"
{
clientId: clientId
clientSecret: clientSecret
callbackUrl: host + "/agent/authenticate/callback"
failedUrl: origin + "/index.html#/auth/callback/failed"
successUrl: origin + "/index.html#/auth/callback/success"
scope: [
# Associate user with email
'user:email'
# See public and private repositories
'repo'
# Get deployment statuses
'repo_deployment'
# Grants read and ping access to hooks
'read:repo_hook'
# Associate user with other users
'read:org'
]
}
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.999884307384491,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 96,
"score": 0.9999343752861023,
"start": 76,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "ArrayInput is a set of inputs as Array\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass ArrayInput extends",
"end": 407,
"score": 0.9998857378959656,
"start": 394,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "set of inputs as Array\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass ArrayInput extends Input\n\n\n\tconstructor:",
"end": 429,
"score": 0.999934196472168,
"start": 409,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Console/Input/ArrayInput.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Input = use('@Konsserto/Component/Console/Input/Input')
Tools = use('@Konsserto/Component/Static/Tools')
#
# ArrayInput is a set of inputs as Array
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class ArrayInput extends Input
constructor:(@parameters,definition) ->
super definition
getFirstArgument:() ->
for key,value of @parameters
if (key && '-' == key[0])
continue
return value
hasParameterOption:(values) ->
for k,v of @parameters
if !Tools.isInt(k)
v = k
if values.indexOf(v) >= 0
return true
return false
getParameterOption:(values,cdef) ->
for k,v of @parameters
if !Tools.isInt(k) && values.indexOf(v) >= 0
return true
else if values.indexOf(v) >= 0
return v
return cdef
__toString:() ->
params = []
for k,v of @parameters
if ('-' == k.charAt(0))
params.push(k +( if '' != v then '='+@escapeToken(v) else ''))
else
params.push(@escapeToken(v))
return params.join(' ')
parse:() ->
for key,value of @parameters
if key.indexOf('--') >= 0
@addLongOption(key.substr(2), value)
else if ('-' == key[0])
@addShortOption(key.substr(1), value)
else
@addArgument(key, value)
addShortOption:(shortcut, value) ->
if !@definition.hasShortcut(shortcut)
throw new Error('The -'+shortcut+' option does not exist.')
@addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value)
addLongOption:(name, value) ->
if !@definition.hasOption(name)
throw new Error('The -'+name+' option does not exist.')
option = @definition.getOption(name)
if (null == value)
if option.isValueRequired()
throw new Error('The -'+name+' option requires a value.')
value = if option.isValueOptional() then option.getDefault() else tru
@options[name] = value
addArgument:(name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
module.exports = ArrayInput; | 14439 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Input = use('@Konsserto/Component/Console/Input/Input')
Tools = use('@Konsserto/Component/Static/Tools')
#
# ArrayInput is a set of inputs as Array
#
# @author <NAME> <<EMAIL>>
#
class ArrayInput extends Input
constructor:(@parameters,definition) ->
super definition
getFirstArgument:() ->
for key,value of @parameters
if (key && '-' == key[0])
continue
return value
hasParameterOption:(values) ->
for k,v of @parameters
if !Tools.isInt(k)
v = k
if values.indexOf(v) >= 0
return true
return false
getParameterOption:(values,cdef) ->
for k,v of @parameters
if !Tools.isInt(k) && values.indexOf(v) >= 0
return true
else if values.indexOf(v) >= 0
return v
return cdef
__toString:() ->
params = []
for k,v of @parameters
if ('-' == k.charAt(0))
params.push(k +( if '' != v then '='+@escapeToken(v) else ''))
else
params.push(@escapeToken(v))
return params.join(' ')
parse:() ->
for key,value of @parameters
if key.indexOf('--') >= 0
@addLongOption(key.substr(2), value)
else if ('-' == key[0])
@addShortOption(key.substr(1), value)
else
@addArgument(key, value)
addShortOption:(shortcut, value) ->
if !@definition.hasShortcut(shortcut)
throw new Error('The -'+shortcut+' option does not exist.')
@addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value)
addLongOption:(name, value) ->
if !@definition.hasOption(name)
throw new Error('The -'+name+' option does not exist.')
option = @definition.getOption(name)
if (null == value)
if option.isValueRequired()
throw new Error('The -'+name+' option requires a value.')
value = if option.isValueOptional() then option.getDefault() else tru
@options[name] = value
addArgument:(name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
module.exports = ArrayInput; | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Input = use('@Konsserto/Component/Console/Input/Input')
Tools = use('@Konsserto/Component/Static/Tools')
#
# ArrayInput is a set of inputs as Array
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class ArrayInput extends Input
constructor:(@parameters,definition) ->
super definition
getFirstArgument:() ->
for key,value of @parameters
if (key && '-' == key[0])
continue
return value
hasParameterOption:(values) ->
for k,v of @parameters
if !Tools.isInt(k)
v = k
if values.indexOf(v) >= 0
return true
return false
getParameterOption:(values,cdef) ->
for k,v of @parameters
if !Tools.isInt(k) && values.indexOf(v) >= 0
return true
else if values.indexOf(v) >= 0
return v
return cdef
__toString:() ->
params = []
for k,v of @parameters
if ('-' == k.charAt(0))
params.push(k +( if '' != v then '='+@escapeToken(v) else ''))
else
params.push(@escapeToken(v))
return params.join(' ')
parse:() ->
for key,value of @parameters
if key.indexOf('--') >= 0
@addLongOption(key.substr(2), value)
else if ('-' == key[0])
@addShortOption(key.substr(1), value)
else
@addArgument(key, value)
addShortOption:(shortcut, value) ->
if !@definition.hasShortcut(shortcut)
throw new Error('The -'+shortcut+' option does not exist.')
@addLongOption(@definition.getOptionForShortcut(shortcut).getName(), value)
addLongOption:(name, value) ->
if !@definition.hasOption(name)
throw new Error('The -'+name+' option does not exist.')
option = @definition.getOption(name)
if (null == value)
if option.isValueRequired()
throw new Error('The -'+name+' option requires a value.')
value = if option.isValueOptional() then option.getDefault() else tru
@options[name] = value
addArgument:(name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
module.exports = ArrayInput; |
[
{
"context": "X math rendering on the web.\n# https://github.com/Khan/KaTeX\n###\nclass Katex\n\tconstructor: ->\n\t\t@delimit",
"end": 114,
"score": 0.9990551471710205,
"start": 110,
"tag": "USERNAME",
"value": "Khan"
},
{
"context": "nder_func = (latex, displayMode) =>\n\t\t\t\t\ttoken = \"=&=#{Random.id()}=&=\"\n\n\t\t\t\t\tmessage.tokens.push\n\t\t\t\t\t\ttoken: token\n\t\t\t\t",
"end": 4211,
"score": 0.9856526851654053,
"start": 4191,
"tag": "KEY",
"value": "&=#{Random.id()}=&=\""
}
] | packages/rocketchat-katex/katex.coffee | Cosecha/rocket-chat-stable | 2 | ###
# KaTeX is a fast, easy-to-use JavaScript library for TeX math rendering on the web.
# https://github.com/Khan/KaTeX
###
class Katex
constructor: ->
@delimiters_map = [
{ opener: '\\[', closer: '\\]', displayMode: true , enabled: () => @parenthesis_syntax_enabled() },
{ opener: '\\(', closer: '\\)', displayMode: false, enabled: () => @parenthesis_syntax_enabled() },
{ opener: '$$' , closer: '$$' , displayMode: true , enabled: () => @dollar_syntax_enabled() },
{ opener: '$' , closer: '$' , displayMode: false, enabled: () => @dollar_syntax_enabled() },
]
# Searches for the first opening delimiter in the string from a given position
find_opening_delimiter: (str, start) -> # Search the string for each opening delimiter
matches = ({options: o, pos: str.indexOf(o.opener, start)} for o in @delimiters_map when o.enabled())
positions = (m.pos for m in matches when m.pos >= 0)
# No opening delimiters were found
if positions.length == 0
return null
# Take the first delimiter found
pos = Math.min.apply Math, positions
match_index = (m.pos for m in matches).indexOf(pos)
match = matches[match_index]
return match
class Boundary
length: ->
return @end - @start
extract: (str) ->
return str.substr @start, @length()
# Returns the outer and inner boundaries of the latex block starting
# at the given opening delimiter
get_latex_boundaries: (str, opening_delimiter_match) ->
inner = new Boundary
outer = new Boundary
# The closing delimiter matching to the opening one
closer = opening_delimiter_match.options.closer
outer.start = opening_delimiter_match.pos
inner.start = opening_delimiter_match.pos + closer.length
# Search for a closer delimiter after the opening one
closer_index = str.substr(inner.start).indexOf(closer)
if closer_index < 0
return null
inner.end = inner.start + closer_index
outer.end = inner.end + closer.length
return {
outer: outer
inner: inner
}
# Searches for the first latex block in the given string
find_latex: (str) ->
start = 0
while (opening_delimiter_match = @find_opening_delimiter str, start++)?
match = @get_latex_boundaries str, opening_delimiter_match
if match?.inner.extract(str).trim().length
match.options = opening_delimiter_match.options
return match
return null
# Breaks a message to what comes before, after and to the content of a
# matched latex block
extract_latex: (str, match) ->
before = str.substr 0, match.outer.start
after = str.substr match.outer.end
latex = match.inner.extract str
latex = s.unescapeHTML latex
return { before: before, latex : latex, after : after }
# Takes a latex math string and the desired display mode and renders it
# to HTML using the KaTeX library
render_latex: (latex, displayMode) ->
try
rendered = katex.renderToString latex , {displayMode: displayMode}
catch e
display_mode = if displayMode then "block" else "inline"
rendered = "<div class=\"katex-error katex-#{display_mode}-error\">"
rendered += "#{s.escapeHTML e.message}"
rendered += "</div>"
return rendered
# Takes a string and renders all latex blocks inside it
render: (str, render_func) ->
result = ''
loop
# Find the first latex block in the string
match = @find_latex str
unless match?
result += str
break
parts = @extract_latex str, match
# Add to the reuslt what comes before the latex block as well as
# the rendered latex content
rendered = render_func parts.latex, match.options.displayMode
result += parts.before + rendered
# Set what comes after the latex block to be examined next
str = parts.after
return result
# Takes a rocketchat message and renders latex in its content
render_message: (message) ->
# Render only if enabled in admin panel
if @katex_enabled()
msg = message
if not _.isString message
if _.trim message.html
msg = message.html
else
return message
if _.isString message
render_func = (latex, displayMode) =>
return @render_latex latex, displayMode
else
message.tokens ?= []
render_func = (latex, displayMode) =>
token = "=&=#{Random.id()}=&="
message.tokens.push
token: token
text: @render_latex latex, displayMode
return token
msg = @render msg, render_func
if not _.isString message
message.html = msg
else
message = msg
return message
katex_enabled: ->
return RocketChat.settings.get('Katex_Enabled')
dollar_syntax_enabled: ->
return RocketChat.settings.get('Katex_Dollar_Syntax')
parenthesis_syntax_enabled: ->
return RocketChat.settings.get('Katex_Parenthesis_Syntax')
RocketChat.katex = new Katex
cb = RocketChat.katex.render_message.bind(RocketChat.katex)
RocketChat.callbacks.add 'renderMessage', cb, RocketChat.callbacks.priority.HIGH - 1
if Meteor.isClient
Blaze.registerHelper 'RocketChatKatex', (text) ->
return RocketChat.katex.render_message text
| 82407 | ###
# KaTeX is a fast, easy-to-use JavaScript library for TeX math rendering on the web.
# https://github.com/Khan/KaTeX
###
class Katex
constructor: ->
@delimiters_map = [
{ opener: '\\[', closer: '\\]', displayMode: true , enabled: () => @parenthesis_syntax_enabled() },
{ opener: '\\(', closer: '\\)', displayMode: false, enabled: () => @parenthesis_syntax_enabled() },
{ opener: '$$' , closer: '$$' , displayMode: true , enabled: () => @dollar_syntax_enabled() },
{ opener: '$' , closer: '$' , displayMode: false, enabled: () => @dollar_syntax_enabled() },
]
# Searches for the first opening delimiter in the string from a given position
find_opening_delimiter: (str, start) -> # Search the string for each opening delimiter
matches = ({options: o, pos: str.indexOf(o.opener, start)} for o in @delimiters_map when o.enabled())
positions = (m.pos for m in matches when m.pos >= 0)
# No opening delimiters were found
if positions.length == 0
return null
# Take the first delimiter found
pos = Math.min.apply Math, positions
match_index = (m.pos for m in matches).indexOf(pos)
match = matches[match_index]
return match
class Boundary
length: ->
return @end - @start
extract: (str) ->
return str.substr @start, @length()
# Returns the outer and inner boundaries of the latex block starting
# at the given opening delimiter
get_latex_boundaries: (str, opening_delimiter_match) ->
inner = new Boundary
outer = new Boundary
# The closing delimiter matching to the opening one
closer = opening_delimiter_match.options.closer
outer.start = opening_delimiter_match.pos
inner.start = opening_delimiter_match.pos + closer.length
# Search for a closer delimiter after the opening one
closer_index = str.substr(inner.start).indexOf(closer)
if closer_index < 0
return null
inner.end = inner.start + closer_index
outer.end = inner.end + closer.length
return {
outer: outer
inner: inner
}
# Searches for the first latex block in the given string
find_latex: (str) ->
start = 0
while (opening_delimiter_match = @find_opening_delimiter str, start++)?
match = @get_latex_boundaries str, opening_delimiter_match
if match?.inner.extract(str).trim().length
match.options = opening_delimiter_match.options
return match
return null
# Breaks a message to what comes before, after and to the content of a
# matched latex block
extract_latex: (str, match) ->
before = str.substr 0, match.outer.start
after = str.substr match.outer.end
latex = match.inner.extract str
latex = s.unescapeHTML latex
return { before: before, latex : latex, after : after }
# Takes a latex math string and the desired display mode and renders it
# to HTML using the KaTeX library
render_latex: (latex, displayMode) ->
try
rendered = katex.renderToString latex , {displayMode: displayMode}
catch e
display_mode = if displayMode then "block" else "inline"
rendered = "<div class=\"katex-error katex-#{display_mode}-error\">"
rendered += "#{s.escapeHTML e.message}"
rendered += "</div>"
return rendered
# Takes a string and renders all latex blocks inside it
render: (str, render_func) ->
result = ''
loop
# Find the first latex block in the string
match = @find_latex str
unless match?
result += str
break
parts = @extract_latex str, match
# Add to the reuslt what comes before the latex block as well as
# the rendered latex content
rendered = render_func parts.latex, match.options.displayMode
result += parts.before + rendered
# Set what comes after the latex block to be examined next
str = parts.after
return result
# Takes a rocketchat message and renders latex in its content
render_message: (message) ->
# Render only if enabled in admin panel
if @katex_enabled()
msg = message
if not _.isString message
if _.trim message.html
msg = message.html
else
return message
if _.isString message
render_func = (latex, displayMode) =>
return @render_latex latex, displayMode
else
message.tokens ?= []
render_func = (latex, displayMode) =>
token = "=<KEY>
message.tokens.push
token: token
text: @render_latex latex, displayMode
return token
msg = @render msg, render_func
if not _.isString message
message.html = msg
else
message = msg
return message
katex_enabled: ->
return RocketChat.settings.get('Katex_Enabled')
dollar_syntax_enabled: ->
return RocketChat.settings.get('Katex_Dollar_Syntax')
parenthesis_syntax_enabled: ->
return RocketChat.settings.get('Katex_Parenthesis_Syntax')
RocketChat.katex = new Katex
cb = RocketChat.katex.render_message.bind(RocketChat.katex)
RocketChat.callbacks.add 'renderMessage', cb, RocketChat.callbacks.priority.HIGH - 1
if Meteor.isClient
Blaze.registerHelper 'RocketChatKatex', (text) ->
return RocketChat.katex.render_message text
| true | ###
# KaTeX is a fast, easy-to-use JavaScript library for TeX math rendering on the web.
# https://github.com/Khan/KaTeX
###
class Katex
constructor: ->
@delimiters_map = [
{ opener: '\\[', closer: '\\]', displayMode: true , enabled: () => @parenthesis_syntax_enabled() },
{ opener: '\\(', closer: '\\)', displayMode: false, enabled: () => @parenthesis_syntax_enabled() },
{ opener: '$$' , closer: '$$' , displayMode: true , enabled: () => @dollar_syntax_enabled() },
{ opener: '$' , closer: '$' , displayMode: false, enabled: () => @dollar_syntax_enabled() },
]
# Searches for the first opening delimiter in the string from a given position
find_opening_delimiter: (str, start) -> # Search the string for each opening delimiter
matches = ({options: o, pos: str.indexOf(o.opener, start)} for o in @delimiters_map when o.enabled())
positions = (m.pos for m in matches when m.pos >= 0)
# No opening delimiters were found
if positions.length == 0
return null
# Take the first delimiter found
pos = Math.min.apply Math, positions
match_index = (m.pos for m in matches).indexOf(pos)
match = matches[match_index]
return match
class Boundary
length: ->
return @end - @start
extract: (str) ->
return str.substr @start, @length()
# Returns the outer and inner boundaries of the latex block starting
# at the given opening delimiter
get_latex_boundaries: (str, opening_delimiter_match) ->
inner = new Boundary
outer = new Boundary
# The closing delimiter matching to the opening one
closer = opening_delimiter_match.options.closer
outer.start = opening_delimiter_match.pos
inner.start = opening_delimiter_match.pos + closer.length
# Search for a closer delimiter after the opening one
closer_index = str.substr(inner.start).indexOf(closer)
if closer_index < 0
return null
inner.end = inner.start + closer_index
outer.end = inner.end + closer.length
return {
outer: outer
inner: inner
}
# Searches for the first latex block in the given string
find_latex: (str) ->
start = 0
while (opening_delimiter_match = @find_opening_delimiter str, start++)?
match = @get_latex_boundaries str, opening_delimiter_match
if match?.inner.extract(str).trim().length
match.options = opening_delimiter_match.options
return match
return null
# Breaks a message to what comes before, after and to the content of a
# matched latex block
extract_latex: (str, match) ->
before = str.substr 0, match.outer.start
after = str.substr match.outer.end
latex = match.inner.extract str
latex = s.unescapeHTML latex
return { before: before, latex : latex, after : after }
# Takes a latex math string and the desired display mode and renders it
# to HTML using the KaTeX library
render_latex: (latex, displayMode) ->
try
rendered = katex.renderToString latex , {displayMode: displayMode}
catch e
display_mode = if displayMode then "block" else "inline"
rendered = "<div class=\"katex-error katex-#{display_mode}-error\">"
rendered += "#{s.escapeHTML e.message}"
rendered += "</div>"
return rendered
# Takes a string and renders all latex blocks inside it
render: (str, render_func) ->
result = ''
loop
# Find the first latex block in the string
match = @find_latex str
unless match?
result += str
break
parts = @extract_latex str, match
# Add to the reuslt what comes before the latex block as well as
# the rendered latex content
rendered = render_func parts.latex, match.options.displayMode
result += parts.before + rendered
# Set what comes after the latex block to be examined next
str = parts.after
return result
# Takes a rocketchat message and renders latex in its content
render_message: (message) ->
# Render only if enabled in admin panel
if @katex_enabled()
msg = message
if not _.isString message
if _.trim message.html
msg = message.html
else
return message
if _.isString message
render_func = (latex, displayMode) =>
return @render_latex latex, displayMode
else
message.tokens ?= []
render_func = (latex, displayMode) =>
token = "=PI:KEY:<KEY>END_PI
message.tokens.push
token: token
text: @render_latex latex, displayMode
return token
msg = @render msg, render_func
if not _.isString message
message.html = msg
else
message = msg
return message
katex_enabled: ->
return RocketChat.settings.get('Katex_Enabled')
dollar_syntax_enabled: ->
return RocketChat.settings.get('Katex_Dollar_Syntax')
parenthesis_syntax_enabled: ->
return RocketChat.settings.get('Katex_Parenthesis_Syntax')
RocketChat.katex = new Katex
cb = RocketChat.katex.render_message.bind(RocketChat.katex)
RocketChat.callbacks.add 'renderMessage', cb, RocketChat.callbacks.priority.HIGH - 1
if Meteor.isClient
Blaze.registerHelper 'RocketChatKatex', (text) ->
return RocketChat.katex.render_message text
|
[
{
"context": "x_size = 0\n\n for word in word_lst\n key = word.split('').sort().join('')\n anagrams[key] ?= []\n a",
"end": 138,
"score": 0.620293378829956,
"start": 133,
"tag": "KEY",
"value": "split"
},
{
"context": "= 0\n\n for word in word_lst\n key = word.split('').sort().join('')\n anagrams[key] ?= []\n anagrams[key].pus",
"end": 154,
"score": 0.7814235687255859,
"start": 143,
"tag": "KEY",
"value": "sort().join"
}
] | Task/Anagrams/CoffeeScript/anagrams-1.coffee | djgoku/RosettaCodeData | 1 | http = require 'http'
show_large_anagram_sets = (word_lst) ->
anagrams = {}
max_size = 0
for word in word_lst
key = word.split('').sort().join('')
anagrams[key] ?= []
anagrams[key].push word
size = anagrams[key].length
max_size = size if size > max_size
for key, variations of anagrams
if variations.length == max_size
console.log variations.join ' '
get_word_list = (process) ->
options =
host: "www.puzzlers.org"
path: "/pub/wordlists/unixdict.txt"
req = http.request options, (res) ->
s = ''
res.on 'data', (chunk) ->
s += chunk
res.on 'end', ->
process s.split '\n'
req.end()
get_word_list show_large_anagram_sets
| 217389 | http = require 'http'
show_large_anagram_sets = (word_lst) ->
anagrams = {}
max_size = 0
for word in word_lst
key = word.<KEY>('').<KEY>('')
anagrams[key] ?= []
anagrams[key].push word
size = anagrams[key].length
max_size = size if size > max_size
for key, variations of anagrams
if variations.length == max_size
console.log variations.join ' '
get_word_list = (process) ->
options =
host: "www.puzzlers.org"
path: "/pub/wordlists/unixdict.txt"
req = http.request options, (res) ->
s = ''
res.on 'data', (chunk) ->
s += chunk
res.on 'end', ->
process s.split '\n'
req.end()
get_word_list show_large_anagram_sets
| true | http = require 'http'
show_large_anagram_sets = (word_lst) ->
anagrams = {}
max_size = 0
for word in word_lst
key = word.PI:KEY:<KEY>END_PI('').PI:KEY:<KEY>END_PI('')
anagrams[key] ?= []
anagrams[key].push word
size = anagrams[key].length
max_size = size if size > max_size
for key, variations of anagrams
if variations.length == max_size
console.log variations.join ' '
get_word_list = (process) ->
options =
host: "www.puzzlers.org"
path: "/pub/wordlists/unixdict.txt"
req = http.request options, (res) ->
s = ''
res.on 'data', (chunk) ->
s += chunk
res.on 'end', ->
process s.split '\n'
req.end()
get_word_list show_large_anagram_sets
|
[
{
"context": "\": [{ \"value\": \"1\" }],\n \"name\": {\"given\":[\"John\"], \"family\": [\"Smith\"]},\n \"gender\": \"M\",\n ",
"end": 1809,
"score": 0.9998725652694702,
"start": 1805,
"tag": "NAME",
"value": "John"
},
{
"context": "],\n \"name\": {\"given\":[\"John\"], \"family\": [\"Smith\"]},\n \"gender\": \"M\",\n \"birthDate\" : ",
"end": 1830,
"score": 0.9998067021369934,
"start": 1825,
"tag": "NAME",
"value": "Smith"
},
{
"context": "\": [{ \"value\": \"2\" }],\n \"name\": {\"given\":[\"Sally\"], \"family\": [\"Smith\"]},\n \"gender\": \"F\",\n ",
"end": 2338,
"score": 0.9997384548187256,
"start": 2333,
"tag": "NAME",
"value": "Sally"
},
{
"context": ",\n \"name\": {\"given\":[\"Sally\"], \"family\": [\"Smith\"]},\n \"gender\": \"F\",\n \"birthDate\" : ",
"end": 2359,
"score": 0.9997479915618896,
"start": 2354,
"tag": "NAME",
"value": "Smith"
}
] | src/example/exec-cms146v2_CQM.coffee | luis1van/cql-execution-1 | 2 | cql = require '../cql'
codes = require '../cql-code-service'
measure = require './CMS146v2_CQM'
cservice = new codes.CodeService {
"1.2.3.4.5": {
"1": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "GHI",
"system": "5.4.3.4.5",
"version": "3"
}
],
"2": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "JKL",
"system": "5.4.3.2.1",
"version": "3"
}
]
},
"6.7.8.9.0": {
"A": [
{
"code": "MNO",
"system": "2.4.6.8.0",
"version": "3"
}, {
"code": "PQR",
"system": "2.4.6.8.0",
"version": "2"
}, {
"code": "STU",
"system": "2.4.6.8.0",
"version": "1"
}
]
}
}
lib = new cql.Library(measure)
parameters = {
MeasurementPeriod: new cql.Interval(cql.DateTime.parse('2013-01-01'), cql.DateTime.parse('2014-01-01'), true, false)
}
executor = new cql.Executor(lib, cservice, parameters)
psource = new cql.PatientSource [ {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "1",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "1" }],
"name": {"given":["John"], "family": ["Smith"]},
"gender": "M",
"birthDate" : "1980-02-17T06:15"}
}
]
}, {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "2",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "2" }],
"name": {"given":["Sally"], "family": ["Smith"]},
"gender": "F",
"birthDate" : "2007-08-02T11:47"}
}
]
} ]
result = executor.exec(psource)
console.log JSON.stringify(result, undefined, 2)
| 191684 | cql = require '../cql'
codes = require '../cql-code-service'
measure = require './CMS146v2_CQM'
cservice = new codes.CodeService {
"1.2.3.4.5": {
"1": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "GHI",
"system": "5.4.3.4.5",
"version": "3"
}
],
"2": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "JKL",
"system": "5.4.3.2.1",
"version": "3"
}
]
},
"6.7.8.9.0": {
"A": [
{
"code": "MNO",
"system": "2.4.6.8.0",
"version": "3"
}, {
"code": "PQR",
"system": "2.4.6.8.0",
"version": "2"
}, {
"code": "STU",
"system": "2.4.6.8.0",
"version": "1"
}
]
}
}
lib = new cql.Library(measure)
parameters = {
MeasurementPeriod: new cql.Interval(cql.DateTime.parse('2013-01-01'), cql.DateTime.parse('2014-01-01'), true, false)
}
executor = new cql.Executor(lib, cservice, parameters)
psource = new cql.PatientSource [ {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "1",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "1" }],
"name": {"given":["<NAME>"], "family": ["<NAME>"]},
"gender": "M",
"birthDate" : "1980-02-17T06:15"}
}
]
}, {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "2",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "2" }],
"name": {"given":["<NAME>"], "family": ["<NAME>"]},
"gender": "F",
"birthDate" : "2007-08-02T11:47"}
}
]
} ]
result = executor.exec(psource)
console.log JSON.stringify(result, undefined, 2)
| true | cql = require '../cql'
codes = require '../cql-code-service'
measure = require './CMS146v2_CQM'
cservice = new codes.CodeService {
"1.2.3.4.5": {
"1": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "GHI",
"system": "5.4.3.4.5",
"version": "3"
}
],
"2": [
{
"code": "ABC",
"system": "5.4.3.2.1",
"version": "1"
}, {
"code": "DEF",
"system": "5.4.3.2.1",
"version": "2"
}, {
"code": "JKL",
"system": "5.4.3.2.1",
"version": "3"
}
]
},
"6.7.8.9.0": {
"A": [
{
"code": "MNO",
"system": "2.4.6.8.0",
"version": "3"
}, {
"code": "PQR",
"system": "2.4.6.8.0",
"version": "2"
}, {
"code": "STU",
"system": "2.4.6.8.0",
"version": "1"
}
]
}
}
lib = new cql.Library(measure)
parameters = {
MeasurementPeriod: new cql.Interval(cql.DateTime.parse('2013-01-01'), cql.DateTime.parse('2014-01-01'), true, false)
}
executor = new cql.Executor(lib, cservice, parameters)
psource = new cql.PatientSource [ {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "1",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "1" }],
"name": {"given":["PI:NAME:<NAME>END_PI"], "family": ["PI:NAME:<NAME>END_PI"]},
"gender": "M",
"birthDate" : "1980-02-17T06:15"}
}
]
}, {
"resourceType": "Bundle",
"id": "example1",
"meta": {
"versionId": "1",
"lastUpdated": "2014-08-18T01:43:30Z"
},
"base": "http://example.com/base",
"entry" : [{
"resource": {
"id" : "2",
"meta" :{ "profile" : ["patient-qicore-qicore-patient"]},
"resourceType" : "Patient",
"identifier": [{ "value": "2" }],
"name": {"given":["PI:NAME:<NAME>END_PI"], "family": ["PI:NAME:<NAME>END_PI"]},
"gender": "F",
"birthDate" : "2007-08-02T11:47"}
}
]
} ]
result = executor.exec(psource)
console.log JSON.stringify(result, undefined, 2)
|
[
{
"context": "'../../mail-rules-templates'\n\nRulesJSONBlobKey = \"MailRules-V2\"\n\nclass MailRulesStore extends NylasStore\n const",
"end": 523,
"score": 0.99937504529953,
"start": 511,
"tag": "KEY",
"value": "MailRules-V2"
}
] | packages/client-app/src/flux/stores/mail-rules-store.coffee | cnheider/nylas-mail | 24,369 | NylasStore = require 'nylas-store'
_ = require 'underscore'
Rx = require 'rx-lite'
AccountStore = require('./account-store').default
DatabaseStore = require('./database-store').default
TaskQueueStatusStore = require './task-queue-status-store'
ReprocessMailRulesTask = require('../tasks/reprocess-mail-rules-task').default
Utils = require '../models/utils'
Actions = require('../actions').default
{ConditionMode, ConditionTemplates, ActionTemplates} = require '../../mail-rules-templates'
RulesJSONBlobKey = "MailRules-V2"
class MailRulesStore extends NylasStore
constructor: ->
@_rules = []
query = DatabaseStore.findJSONBlob(RulesJSONBlobKey)
@_subscription = Rx.Observable.fromQuery(query).subscribe (rules) =>
@_rules = rules ? []
@trigger()
@listenTo Actions.addMailRule, @_onAddMailRule
@listenTo Actions.deleteMailRule, @_onDeleteMailRule
@listenTo Actions.reorderMailRule, @_onReorderMailRule
@listenTo Actions.updateMailRule, @_onUpdateMailRule
@listenTo Actions.disableMailRule, @_onDisableMailRule
rules: =>
@_rules
rulesForAccountId: (accountId) =>
@_rules.filter (f) => f.accountId is accountId
disabledRules: (accountId) =>
@_rules.filter (f) => f.disabled
_onDeleteMailRule: (id) =>
@_rules = @_rules.filter (f) -> f.id isnt id
@_saveMailRules()
@trigger()
_onReorderMailRule: (id, newIdx) =>
currentIdx = _.findIndex(@_rules, _.matcher({id}))
return if currentIdx is -1
rule = @_rules[currentIdx]
@_rules.splice(currentIdx, 1)
@_rules.splice(newIdx, 0, rule)
@_saveMailRules()
@trigger()
_onAddMailRule: (properties) =>
defaults =
id: Utils.generateTempId()
name: "Untitled Rule"
conditionMode: ConditionMode.All
conditions: [ConditionTemplates[0].createDefaultInstance()]
actions: [ActionTemplates[0].createDefaultInstance()]
disabled: false
unless properties.accountId
throw new Error("AddMailRule: you must provide an account id.")
@_rules.push(_.extend(defaults, properties))
@_saveMailRules()
@trigger()
_onUpdateMailRule: (id, properties) =>
existing = _.find @_rules, (f) -> id is f.id
existing[key] = val for key, val of properties
@_saveMailRules()
@trigger()
_onDisableMailRule: (id, reason) =>
existing = _.find @_rules, (f) -> id is f.id
return if not existing or existing.disabled is true
# Disable the task
existing.disabled = true
existing.disabledReason = reason
@_saveMailRules()
# Cancel all bulk processing jobs
for task in TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {})
Actions.dequeueTask(task.id)
@trigger()
_saveMailRules: =>
@_saveMailRulesDebounced ?= _.debounce =>
DatabaseStore.inTransaction (t) =>
t.persistJSONBlob(RulesJSONBlobKey, @_rules)
,1000
@_saveMailRulesDebounced()
module.exports = new MailRulesStore()
| 82243 | NylasStore = require 'nylas-store'
_ = require 'underscore'
Rx = require 'rx-lite'
AccountStore = require('./account-store').default
DatabaseStore = require('./database-store').default
TaskQueueStatusStore = require './task-queue-status-store'
ReprocessMailRulesTask = require('../tasks/reprocess-mail-rules-task').default
Utils = require '../models/utils'
Actions = require('../actions').default
{ConditionMode, ConditionTemplates, ActionTemplates} = require '../../mail-rules-templates'
RulesJSONBlobKey = "<KEY>"
class MailRulesStore extends NylasStore
constructor: ->
@_rules = []
query = DatabaseStore.findJSONBlob(RulesJSONBlobKey)
@_subscription = Rx.Observable.fromQuery(query).subscribe (rules) =>
@_rules = rules ? []
@trigger()
@listenTo Actions.addMailRule, @_onAddMailRule
@listenTo Actions.deleteMailRule, @_onDeleteMailRule
@listenTo Actions.reorderMailRule, @_onReorderMailRule
@listenTo Actions.updateMailRule, @_onUpdateMailRule
@listenTo Actions.disableMailRule, @_onDisableMailRule
rules: =>
@_rules
rulesForAccountId: (accountId) =>
@_rules.filter (f) => f.accountId is accountId
disabledRules: (accountId) =>
@_rules.filter (f) => f.disabled
_onDeleteMailRule: (id) =>
@_rules = @_rules.filter (f) -> f.id isnt id
@_saveMailRules()
@trigger()
_onReorderMailRule: (id, newIdx) =>
currentIdx = _.findIndex(@_rules, _.matcher({id}))
return if currentIdx is -1
rule = @_rules[currentIdx]
@_rules.splice(currentIdx, 1)
@_rules.splice(newIdx, 0, rule)
@_saveMailRules()
@trigger()
_onAddMailRule: (properties) =>
defaults =
id: Utils.generateTempId()
name: "Untitled Rule"
conditionMode: ConditionMode.All
conditions: [ConditionTemplates[0].createDefaultInstance()]
actions: [ActionTemplates[0].createDefaultInstance()]
disabled: false
unless properties.accountId
throw new Error("AddMailRule: you must provide an account id.")
@_rules.push(_.extend(defaults, properties))
@_saveMailRules()
@trigger()
_onUpdateMailRule: (id, properties) =>
existing = _.find @_rules, (f) -> id is f.id
existing[key] = val for key, val of properties
@_saveMailRules()
@trigger()
_onDisableMailRule: (id, reason) =>
existing = _.find @_rules, (f) -> id is f.id
return if not existing or existing.disabled is true
# Disable the task
existing.disabled = true
existing.disabledReason = reason
@_saveMailRules()
# Cancel all bulk processing jobs
for task in TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {})
Actions.dequeueTask(task.id)
@trigger()
_saveMailRules: =>
@_saveMailRulesDebounced ?= _.debounce =>
DatabaseStore.inTransaction (t) =>
t.persistJSONBlob(RulesJSONBlobKey, @_rules)
,1000
@_saveMailRulesDebounced()
module.exports = new MailRulesStore()
| true | NylasStore = require 'nylas-store'
_ = require 'underscore'
Rx = require 'rx-lite'
AccountStore = require('./account-store').default
DatabaseStore = require('./database-store').default
TaskQueueStatusStore = require './task-queue-status-store'
ReprocessMailRulesTask = require('../tasks/reprocess-mail-rules-task').default
Utils = require '../models/utils'
Actions = require('../actions').default
{ConditionMode, ConditionTemplates, ActionTemplates} = require '../../mail-rules-templates'
RulesJSONBlobKey = "PI:KEY:<KEY>END_PI"
class MailRulesStore extends NylasStore
constructor: ->
@_rules = []
query = DatabaseStore.findJSONBlob(RulesJSONBlobKey)
@_subscription = Rx.Observable.fromQuery(query).subscribe (rules) =>
@_rules = rules ? []
@trigger()
@listenTo Actions.addMailRule, @_onAddMailRule
@listenTo Actions.deleteMailRule, @_onDeleteMailRule
@listenTo Actions.reorderMailRule, @_onReorderMailRule
@listenTo Actions.updateMailRule, @_onUpdateMailRule
@listenTo Actions.disableMailRule, @_onDisableMailRule
rules: =>
@_rules
rulesForAccountId: (accountId) =>
@_rules.filter (f) => f.accountId is accountId
disabledRules: (accountId) =>
@_rules.filter (f) => f.disabled
_onDeleteMailRule: (id) =>
@_rules = @_rules.filter (f) -> f.id isnt id
@_saveMailRules()
@trigger()
_onReorderMailRule: (id, newIdx) =>
currentIdx = _.findIndex(@_rules, _.matcher({id}))
return if currentIdx is -1
rule = @_rules[currentIdx]
@_rules.splice(currentIdx, 1)
@_rules.splice(newIdx, 0, rule)
@_saveMailRules()
@trigger()
_onAddMailRule: (properties) =>
defaults =
id: Utils.generateTempId()
name: "Untitled Rule"
conditionMode: ConditionMode.All
conditions: [ConditionTemplates[0].createDefaultInstance()]
actions: [ActionTemplates[0].createDefaultInstance()]
disabled: false
unless properties.accountId
throw new Error("AddMailRule: you must provide an account id.")
@_rules.push(_.extend(defaults, properties))
@_saveMailRules()
@trigger()
_onUpdateMailRule: (id, properties) =>
existing = _.find @_rules, (f) -> id is f.id
existing[key] = val for key, val of properties
@_saveMailRules()
@trigger()
_onDisableMailRule: (id, reason) =>
existing = _.find @_rules, (f) -> id is f.id
return if not existing or existing.disabled is true
# Disable the task
existing.disabled = true
existing.disabledReason = reason
@_saveMailRules()
# Cancel all bulk processing jobs
for task in TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {})
Actions.dequeueTask(task.id)
@trigger()
_saveMailRules: =>
@_saveMailRulesDebounced ?= _.debounce =>
DatabaseStore.inTransaction (t) =>
t.persistJSONBlob(RulesJSONBlobKey, @_rules)
,1000
@_saveMailRulesDebounced()
module.exports = new MailRulesStore()
|
[
{
"context": "e\n\n cat = {}\n cat.setName = setName\n cat.setName 'Mittens'\n console.log cat.name\n\n pig = {}\n setName.apply ",
"end": 89,
"score": 0.9995630383491516,
"start": 82,
"tag": "NAME",
"value": "Mittens"
},
{
"context": "sole.log cat.name\n\n pig = {}\n setName.apply pig,['Babe']\n console.log pig.name\n setName.call pig,'Babe1'",
"end": 149,
"score": 0.9972540140151978,
"start": 145,
"tag": "NAME",
"value": "Babe"
},
{
"context": "['Babe']\n console.log pig.name\n setName.call pig,'Babe1'\n console.log pig.name\n\n horse = {}\n cat.setName.",
"end": 198,
"score": 0.9937894344329834,
"start": 193,
"tag": "NAME",
"value": "Babe1"
},
{
"context": "g.name\n\n horse = {}\n cat.setName.apply horse,['Mr. Ed']\n console.log horse.name\n\n ringFireAlarm = (isDr",
"end": 268,
"score": 0.9895094037055969,
"start": 266,
"tag": "NAME",
"value": "Ed"
}
] | project/web/assets/coffee/js/one3.coffee | kongwen/zhubao1 | 0 | setName = (name) -> @name = name
cat = {}
cat.setName = setName
cat.setName 'Mittens'
console.log cat.name
pig = {}
setName.apply pig,['Babe']
console.log pig.name
setName.call pig,'Babe1'
console.log pig.name
horse = {}
cat.setName.apply horse,['Mr. Ed']
console.log horse.name
ringFireAlarm = (isDrill) ->
isDrill = true unless isDrill? | 193797 | setName = (name) -> @name = name
cat = {}
cat.setName = setName
cat.setName '<NAME>'
console.log cat.name
pig = {}
setName.apply pig,['<NAME>']
console.log pig.name
setName.call pig,'<NAME>'
console.log pig.name
horse = {}
cat.setName.apply horse,['Mr. <NAME>']
console.log horse.name
ringFireAlarm = (isDrill) ->
isDrill = true unless isDrill? | true | setName = (name) -> @name = name
cat = {}
cat.setName = setName
cat.setName 'PI:NAME:<NAME>END_PI'
console.log cat.name
pig = {}
setName.apply pig,['PI:NAME:<NAME>END_PI']
console.log pig.name
setName.call pig,'PI:NAME:<NAME>END_PI'
console.log pig.name
horse = {}
cat.setName.apply horse,['Mr. PI:NAME:<NAME>END_PI']
console.log horse.name
ringFireAlarm = (isDrill) ->
isDrill = true unless isDrill? |
[
{
"context": "ew event is triggered.\n#\n# See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs\n#\n\nmo",
"end": 810,
"score": 0.9965683817863464,
"start": 803,
"tag": "USERNAME",
"value": "bugsnag"
},
{
"context": "be easy to fix\"\n event.user =\n name: \"John Smith\"\n\n if config.reopened\n delete config.reop",
"end": 4440,
"score": 0.9925174713134766,
"start": 4430,
"tag": "NAME",
"value": "John Smith"
}
] | notification-plugin.coffee | jacobmarshall-etc/bugsnag-notification-plugins | 0 | require "sugar"
fs = require "fs"
path = require "path"
Handlebars = require "handlebars"
Table = require('cli-table')
argv = require("optimist").argv
Handlebars.registerHelper "eachSummaryFrame", (stack, options) ->
NotificationPlugin.getSummaryStacktrace(stack).map((line) ->
options.fn line
).join ""
#
# The base Bugsnag NotificationPlugin class
# Extend this class to create your own Bugsnag notification plugins:
#
# NotificationPlugin = require "../../notification-plugin.js"
# class MyPlugin extends NotificationPlugin
# @receiveEvent = (config, event) ->
# ...
# module.exports = MyPlugin
#
# All notification plugins must override the receiveEvent function to perform
# the notification. This method is fired when a new event is triggered.
#
# See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs
#
module.exports = class NotificationPlugin
# Load templates
@markdownTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.md.hbs", "utf8"))
@htmlTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.html.hbs", "utf8"))
@textTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.text.hbs", "utf8"))
# Utility methods for http requests
@request = require "superagent"
# Fired when a new event is triggered for notification
# Plugins MUST override this method
@receiveEvent = (config, event, callback) ->
throw new Error("Plugins must override receiveEvent")
# Utility methods for generating notification content
@stacktraceLineString = (stacktraceLine) ->
stacktraceLine.file + ":" + stacktraceLine.lineNumber + " - " + stacktraceLine.method
@basicStacktrace = (stacktrace) ->
@getSummaryStacktrace(stacktrace).map((line) ->
@stacktraceLineString line
, this).join "\n"
# Returns the first line of a stacktrace (formatted)
@firstStacktraceLine = (stacktrace) ->
@stacktraceLineString @getSummaryStacktrace(stacktrace)[0]
# Utility to determine whether a stacktrace line is `inProject`
@inProjectStacktraceLine = (line) ->
line? and "inProject" of line and line.inProject
# Utility for getting all the stacktrace lines that are `inProject`
@getSummaryStacktrace = (stacktrace) ->
filtered = undefined
# If there are no 'inProject' stacktrace lines
filtered = stacktrace.slice(0, 3) unless (filtered = stacktrace.filter(@inProjectStacktraceLine)).length
filtered
@title = (event) ->
event.error.exceptionClass + " in " + event.error.context
@markdownBody = (event) ->
@markdownTemplate event
@htmlBody = (event) ->
@htmlTemplate event
@textBody = (event) ->
@textTemplate event
# Fire a test event to your notification plugin (do not override)
@fireTestEvent = (config, callback) ->
event =
error:
exceptionClass: "ExampleException"
message: "Something really bad happened"
context: "home#example"
appVersion: "1.0.0"
releaseStage: "production"
occurrences: 42
firstReceived: new Date()
usersAffected: 20
url: "http://bugsnag.com/errors/example/events/example"
stacktrace: [
{
file: "app/controllers/home_controller.rb"
lineNumber: 123
method: "example"
inProject: true
}
{
file: "app/controllers/other_controller.rb"
lineNumber: 12
method: "broken"
inProject: true
}
{
file: "gems/junk/junkfile.rb"
lineNumber: 999
method: "something"
inProject: false
}
{
file: "lib/important/magic.rb"
lineNumber: 4
method: "load_something"
inProject: true
}
]
project:
name: "Example.com"
url: "http://bugsnag.com/projects/example"
trigger:
type: "firstException"
message: "New exception"
if config.spike
delete config.spike
event.trigger =
type: "projectSpiking"
message: "Project Spiking"
rate: 103
if config.comment
delete config.comment
event.trigger =
type: "comment"
message: "Comment Added"
event.comment =
message: "I think this should be easy to fix"
event.user =
name: "John Smith"
if config.reopened
delete config.reopened
event.trigger =
type: "reopened"
message: "Resolved error re-occurred"
if config.createdIssue
info = config.createdIssue.split(",")
event.error.createdIssue = {}
event.error.createdIssue[info[0]] = info[1]
delete config.createdIssue
@receiveEvent config, event, callback
return
# Configuration validation methods (do not override)
@validateConfig = (config, pluginConfigFile) ->
pluginConfig = require pluginConfigFile
if pluginConfig.fields
pluginConfig.fields.each (option) ->
configValue = config[option.name]
# Validate all non-optional config fields are present
throw new Error("ConfigurationError: Required configuration option '" + option.name + "' is missing") unless configValue isnt `undefined` or option.optional or (option.type is "boolean" and option.defaultValue isnt `undefined`)
# Validate fields with allowed values
throw new Error("ConfigurationError: Invalid value for '" + option.name + "'") if configValue isnt `undefined` and option.allowedValues and option.allowedValues.none(configValue)
# Fill in default values
config[option.name] = option.defaultValue if not configValue? and option.defaultValue isnt `undefined`
return
return
printHelp = (configFile) ->
table = new Table(
chars:
'top': ''
'top-mid': ''
'top-left': ''
'top-right': ''
'bottom': ''
'bottom-mid': ''
'bottom-left': ''
'bottom-right': ''
'left': ''
'left-mid': ''
'mid': ''
'mid-mid': ''
'right': ''
'right-mid': ''
'middle': ' '
style:
'padding-left': 5
'padding-right': 0
)
configFile.fields.forEach (field) ->
fieldDesc = "--#{field.name}=#{field.type || "string"}"
fieldDesc = fieldDesc + " (optional)" if field.optional
table.push [fieldDesc, field.description]
table.push ["",""]
table.push ["--reopened (optional)", "Simulate an error reopening"]
table.push ["--createdIssue=string,string (optional)", "Simulate created issue metadata key,value"]
table.push ["--comment (optional)", "Simulate a comment"]
table.push ["--spike (optional)", "Simulate a project spike"]
console.log ""
console.log "Attempting to test the #{path.basename(path.dirname(module.parent.filename))} integration"
console.log table.toString()
# If running plugins from the command line, allow them to fire test events
if module.parent and module.parent.parent is null
pluginConfigFile = require(path.dirname(module.parent.filename) + "/config.json")
# Parse command line flags
flags = Object.keys(argv).exclude("_", "$0")
config = {}
if flags.indexOf("help") != -1
return printHelp(pluginConfigFile)
flags.each (flag) ->
config[flag] = argv[flag] if argv[flag]? and argv[flag] isnt ""
# Validate configuration
try
NotificationPlugin.validateConfig config, path.dirname(module.parent.filename) + "/config.json"
catch err
console.error err.message
printHelp(pluginConfigFile)
return
# Fire a test event
plugin = require(module.parent.filename)
plugin.fireTestEvent config, (err, data) ->
if err
console.error "Error firing notification\n", err
else
console.log "Fired test event successfully\n", data
| 175947 | require "sugar"
fs = require "fs"
path = require "path"
Handlebars = require "handlebars"
Table = require('cli-table')
argv = require("optimist").argv
Handlebars.registerHelper "eachSummaryFrame", (stack, options) ->
NotificationPlugin.getSummaryStacktrace(stack).map((line) ->
options.fn line
).join ""
#
# The base Bugsnag NotificationPlugin class
# Extend this class to create your own Bugsnag notification plugins:
#
# NotificationPlugin = require "../../notification-plugin.js"
# class MyPlugin extends NotificationPlugin
# @receiveEvent = (config, event) ->
# ...
# module.exports = MyPlugin
#
# All notification plugins must override the receiveEvent function to perform
# the notification. This method is fired when a new event is triggered.
#
# See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs
#
module.exports = class NotificationPlugin
# Load templates
@markdownTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.md.hbs", "utf8"))
@htmlTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.html.hbs", "utf8"))
@textTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.text.hbs", "utf8"))
# Utility methods for http requests
@request = require "superagent"
# Fired when a new event is triggered for notification
# Plugins MUST override this method
@receiveEvent = (config, event, callback) ->
throw new Error("Plugins must override receiveEvent")
# Utility methods for generating notification content
@stacktraceLineString = (stacktraceLine) ->
stacktraceLine.file + ":" + stacktraceLine.lineNumber + " - " + stacktraceLine.method
@basicStacktrace = (stacktrace) ->
@getSummaryStacktrace(stacktrace).map((line) ->
@stacktraceLineString line
, this).join "\n"
# Returns the first line of a stacktrace (formatted)
@firstStacktraceLine = (stacktrace) ->
@stacktraceLineString @getSummaryStacktrace(stacktrace)[0]
# Utility to determine whether a stacktrace line is `inProject`
@inProjectStacktraceLine = (line) ->
line? and "inProject" of line and line.inProject
# Utility for getting all the stacktrace lines that are `inProject`
@getSummaryStacktrace = (stacktrace) ->
filtered = undefined
# If there are no 'inProject' stacktrace lines
filtered = stacktrace.slice(0, 3) unless (filtered = stacktrace.filter(@inProjectStacktraceLine)).length
filtered
@title = (event) ->
event.error.exceptionClass + " in " + event.error.context
@markdownBody = (event) ->
@markdownTemplate event
@htmlBody = (event) ->
@htmlTemplate event
@textBody = (event) ->
@textTemplate event
# Fire a test event to your notification plugin (do not override)
@fireTestEvent = (config, callback) ->
event =
error:
exceptionClass: "ExampleException"
message: "Something really bad happened"
context: "home#example"
appVersion: "1.0.0"
releaseStage: "production"
occurrences: 42
firstReceived: new Date()
usersAffected: 20
url: "http://bugsnag.com/errors/example/events/example"
stacktrace: [
{
file: "app/controllers/home_controller.rb"
lineNumber: 123
method: "example"
inProject: true
}
{
file: "app/controllers/other_controller.rb"
lineNumber: 12
method: "broken"
inProject: true
}
{
file: "gems/junk/junkfile.rb"
lineNumber: 999
method: "something"
inProject: false
}
{
file: "lib/important/magic.rb"
lineNumber: 4
method: "load_something"
inProject: true
}
]
project:
name: "Example.com"
url: "http://bugsnag.com/projects/example"
trigger:
type: "firstException"
message: "New exception"
if config.spike
delete config.spike
event.trigger =
type: "projectSpiking"
message: "Project Spiking"
rate: 103
if config.comment
delete config.comment
event.trigger =
type: "comment"
message: "Comment Added"
event.comment =
message: "I think this should be easy to fix"
event.user =
name: "<NAME>"
if config.reopened
delete config.reopened
event.trigger =
type: "reopened"
message: "Resolved error re-occurred"
if config.createdIssue
info = config.createdIssue.split(",")
event.error.createdIssue = {}
event.error.createdIssue[info[0]] = info[1]
delete config.createdIssue
@receiveEvent config, event, callback
return
# Configuration validation methods (do not override)
@validateConfig = (config, pluginConfigFile) ->
pluginConfig = require pluginConfigFile
if pluginConfig.fields
pluginConfig.fields.each (option) ->
configValue = config[option.name]
# Validate all non-optional config fields are present
throw new Error("ConfigurationError: Required configuration option '" + option.name + "' is missing") unless configValue isnt `undefined` or option.optional or (option.type is "boolean" and option.defaultValue isnt `undefined`)
# Validate fields with allowed values
throw new Error("ConfigurationError: Invalid value for '" + option.name + "'") if configValue isnt `undefined` and option.allowedValues and option.allowedValues.none(configValue)
# Fill in default values
config[option.name] = option.defaultValue if not configValue? and option.defaultValue isnt `undefined`
return
return
printHelp = (configFile) ->
table = new Table(
chars:
'top': ''
'top-mid': ''
'top-left': ''
'top-right': ''
'bottom': ''
'bottom-mid': ''
'bottom-left': ''
'bottom-right': ''
'left': ''
'left-mid': ''
'mid': ''
'mid-mid': ''
'right': ''
'right-mid': ''
'middle': ' '
style:
'padding-left': 5
'padding-right': 0
)
configFile.fields.forEach (field) ->
fieldDesc = "--#{field.name}=#{field.type || "string"}"
fieldDesc = fieldDesc + " (optional)" if field.optional
table.push [fieldDesc, field.description]
table.push ["",""]
table.push ["--reopened (optional)", "Simulate an error reopening"]
table.push ["--createdIssue=string,string (optional)", "Simulate created issue metadata key,value"]
table.push ["--comment (optional)", "Simulate a comment"]
table.push ["--spike (optional)", "Simulate a project spike"]
console.log ""
console.log "Attempting to test the #{path.basename(path.dirname(module.parent.filename))} integration"
console.log table.toString()
# If running plugins from the command line, allow them to fire test events
if module.parent and module.parent.parent is null
pluginConfigFile = require(path.dirname(module.parent.filename) + "/config.json")
# Parse command line flags
flags = Object.keys(argv).exclude("_", "$0")
config = {}
if flags.indexOf("help") != -1
return printHelp(pluginConfigFile)
flags.each (flag) ->
config[flag] = argv[flag] if argv[flag]? and argv[flag] isnt ""
# Validate configuration
try
NotificationPlugin.validateConfig config, path.dirname(module.parent.filename) + "/config.json"
catch err
console.error err.message
printHelp(pluginConfigFile)
return
# Fire a test event
plugin = require(module.parent.filename)
plugin.fireTestEvent config, (err, data) ->
if err
console.error "Error firing notification\n", err
else
console.log "Fired test event successfully\n", data
| true | require "sugar"
fs = require "fs"
path = require "path"
Handlebars = require "handlebars"
Table = require('cli-table')
argv = require("optimist").argv
Handlebars.registerHelper "eachSummaryFrame", (stack, options) ->
NotificationPlugin.getSummaryStacktrace(stack).map((line) ->
options.fn line
).join ""
#
# The base Bugsnag NotificationPlugin class
# Extend this class to create your own Bugsnag notification plugins:
#
# NotificationPlugin = require "../../notification-plugin.js"
# class MyPlugin extends NotificationPlugin
# @receiveEvent = (config, event) ->
# ...
# module.exports = MyPlugin
#
# All notification plugins must override the receiveEvent function to perform
# the notification. This method is fired when a new event is triggered.
#
# See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs
#
module.exports = class NotificationPlugin
# Load templates
@markdownTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.md.hbs", "utf8"))
@htmlTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.html.hbs", "utf8"))
@textTemplate = Handlebars.compile(fs.readFileSync(__dirname + "/templates/error.text.hbs", "utf8"))
# Utility methods for http requests
@request = require "superagent"
# Fired when a new event is triggered for notification
# Plugins MUST override this method
@receiveEvent = (config, event, callback) ->
throw new Error("Plugins must override receiveEvent")
# Utility methods for generating notification content
@stacktraceLineString = (stacktraceLine) ->
stacktraceLine.file + ":" + stacktraceLine.lineNumber + " - " + stacktraceLine.method
@basicStacktrace = (stacktrace) ->
@getSummaryStacktrace(stacktrace).map((line) ->
@stacktraceLineString line
, this).join "\n"
# Returns the first line of a stacktrace (formatted)
@firstStacktraceLine = (stacktrace) ->
@stacktraceLineString @getSummaryStacktrace(stacktrace)[0]
# Utility to determine whether a stacktrace line is `inProject`
@inProjectStacktraceLine = (line) ->
line? and "inProject" of line and line.inProject
# Utility for getting all the stacktrace lines that are `inProject`
@getSummaryStacktrace = (stacktrace) ->
filtered = undefined
# If there are no 'inProject' stacktrace lines
filtered = stacktrace.slice(0, 3) unless (filtered = stacktrace.filter(@inProjectStacktraceLine)).length
filtered
@title = (event) ->
event.error.exceptionClass + " in " + event.error.context
@markdownBody = (event) ->
@markdownTemplate event
@htmlBody = (event) ->
@htmlTemplate event
@textBody = (event) ->
@textTemplate event
# Fire a test event to your notification plugin (do not override)
@fireTestEvent = (config, callback) ->
event =
error:
exceptionClass: "ExampleException"
message: "Something really bad happened"
context: "home#example"
appVersion: "1.0.0"
releaseStage: "production"
occurrences: 42
firstReceived: new Date()
usersAffected: 20
url: "http://bugsnag.com/errors/example/events/example"
stacktrace: [
{
file: "app/controllers/home_controller.rb"
lineNumber: 123
method: "example"
inProject: true
}
{
file: "app/controllers/other_controller.rb"
lineNumber: 12
method: "broken"
inProject: true
}
{
file: "gems/junk/junkfile.rb"
lineNumber: 999
method: "something"
inProject: false
}
{
file: "lib/important/magic.rb"
lineNumber: 4
method: "load_something"
inProject: true
}
]
project:
name: "Example.com"
url: "http://bugsnag.com/projects/example"
trigger:
type: "firstException"
message: "New exception"
if config.spike
delete config.spike
event.trigger =
type: "projectSpiking"
message: "Project Spiking"
rate: 103
if config.comment
delete config.comment
event.trigger =
type: "comment"
message: "Comment Added"
event.comment =
message: "I think this should be easy to fix"
event.user =
name: "PI:NAME:<NAME>END_PI"
if config.reopened
delete config.reopened
event.trigger =
type: "reopened"
message: "Resolved error re-occurred"
if config.createdIssue
info = config.createdIssue.split(",")
event.error.createdIssue = {}
event.error.createdIssue[info[0]] = info[1]
delete config.createdIssue
@receiveEvent config, event, callback
return
# Configuration validation methods (do not override)
@validateConfig = (config, pluginConfigFile) ->
pluginConfig = require pluginConfigFile
if pluginConfig.fields
pluginConfig.fields.each (option) ->
configValue = config[option.name]
# Validate all non-optional config fields are present
throw new Error("ConfigurationError: Required configuration option '" + option.name + "' is missing") unless configValue isnt `undefined` or option.optional or (option.type is "boolean" and option.defaultValue isnt `undefined`)
# Validate fields with allowed values
throw new Error("ConfigurationError: Invalid value for '" + option.name + "'") if configValue isnt `undefined` and option.allowedValues and option.allowedValues.none(configValue)
# Fill in default values
config[option.name] = option.defaultValue if not configValue? and option.defaultValue isnt `undefined`
return
return
printHelp = (configFile) ->
table = new Table(
chars:
'top': ''
'top-mid': ''
'top-left': ''
'top-right': ''
'bottom': ''
'bottom-mid': ''
'bottom-left': ''
'bottom-right': ''
'left': ''
'left-mid': ''
'mid': ''
'mid-mid': ''
'right': ''
'right-mid': ''
'middle': ' '
style:
'padding-left': 5
'padding-right': 0
)
configFile.fields.forEach (field) ->
fieldDesc = "--#{field.name}=#{field.type || "string"}"
fieldDesc = fieldDesc + " (optional)" if field.optional
table.push [fieldDesc, field.description]
table.push ["",""]
table.push ["--reopened (optional)", "Simulate an error reopening"]
table.push ["--createdIssue=string,string (optional)", "Simulate created issue metadata key,value"]
table.push ["--comment (optional)", "Simulate a comment"]
table.push ["--spike (optional)", "Simulate a project spike"]
console.log ""
console.log "Attempting to test the #{path.basename(path.dirname(module.parent.filename))} integration"
console.log table.toString()
# If running plugins from the command line, allow them to fire test events
if module.parent and module.parent.parent is null
pluginConfigFile = require(path.dirname(module.parent.filename) + "/config.json")
# Parse command line flags
flags = Object.keys(argv).exclude("_", "$0")
config = {}
if flags.indexOf("help") != -1
return printHelp(pluginConfigFile)
flags.each (flag) ->
config[flag] = argv[flag] if argv[flag]? and argv[flag] isnt ""
# Validate configuration
try
NotificationPlugin.validateConfig config, path.dirname(module.parent.filename) + "/config.json"
catch err
console.error err.message
printHelp(pluginConfigFile)
return
# Fire a test event
plugin = require(module.parent.filename)
plugin.fireTestEvent config, (err, data) ->
if err
console.error "Error firing notification\n", err
else
console.log "Fired test event successfully\n", data
|
[
{
"context": "readFileSync('./VERSION', 'utf8').trim()\nauthor: 'Jacob Evans <dcrypt@dekz.net>'\n\nlicences: [\n type: 'FEISTY'\n",
"end": 191,
"score": 0.9998903870582581,
"start": 180,
"tag": "NAME",
"value": "Jacob Evans"
},
{
"context": "'./VERSION', 'utf8').trim()\nauthor: 'Jacob Evans <dcrypt@dekz.net>'\n\nlicences: [\n type: 'FEISTY'\n url: 'http://gi",
"end": 208,
"score": 0.9999194741249084,
"start": 193,
"tag": "EMAIL",
"value": "dcrypt@dekz.net"
},
{
"context": "ty/license/raw/master/LICENSE'\n]\n\ncontributors: ['Jacob Evans <jacob@dekz.net>']\n\nrepository:\n type: 'git'\n u",
"end": 332,
"score": 0.9998866319656372,
"start": 321,
"tag": "NAME",
"value": "Jacob Evans"
},
{
"context": "w/master/LICENSE'\n]\n\ncontributors: ['Jacob Evans <jacob@dekz.net>']\n\nrepository:\n type: 'git'\n url: 'https://git",
"end": 348,
"score": 0.9999234080314636,
"start": 334,
"tag": "EMAIL",
"value": "jacob@dekz.net"
},
{
"context": " 'https://github.com/dekz/dcrypt.git'\n private: 'git@github.com:dekz/dcrypt.git'\n web: 'https://github.com/dekz/",
"end": 449,
"score": 0.9995147585868835,
"start": 435,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": " 'https://github.com/dekz/dcrypt'\n\nbugs:\n mail: 'dcrypt@dekz.net'\n web: 'https://github.com/dekz/dcrypt/issues'\n\n",
"end": 538,
"score": 0.9998973608016968,
"start": 523,
"tag": "EMAIL",
"value": "dcrypt@dekz.net"
}
] | package.coffee | jaitengill/crypt-local | 6 | name: 'dcrypt'
description: 'extended openssl bindings'
keywords: ['crypt', 'crypto', 'dcrypt', 'openssl']
version: require('fs').readFileSync('./VERSION', 'utf8').trim()
author: 'Jacob Evans <dcrypt@dekz.net>'
licences: [
type: 'FEISTY'
url: 'http://github.com/feisty/license/raw/master/LICENSE'
]
contributors: ['Jacob Evans <jacob@dekz.net>']
repository:
type: 'git'
url: 'https://github.com/dekz/dcrypt.git'
private: 'git@github.com:dekz/dcrypt.git'
web: 'https://github.com/dekz/dcrypt'
bugs:
mail: 'dcrypt@dekz.net'
web: 'https://github.com/dekz/dcrypt/issues'
main: './dcrypt.js'
dependencies:
'coffee-script': '>= 0.9.5 < 1.1.0'
engines:
node: '>= 0.4.2 < 0.5.0'
npm: '>= 0.3.15 < 1.1.0'
| 116255 | name: 'dcrypt'
description: 'extended openssl bindings'
keywords: ['crypt', 'crypto', 'dcrypt', 'openssl']
version: require('fs').readFileSync('./VERSION', 'utf8').trim()
author: '<NAME> <<EMAIL>>'
licences: [
type: 'FEISTY'
url: 'http://github.com/feisty/license/raw/master/LICENSE'
]
contributors: ['<NAME> <<EMAIL>>']
repository:
type: 'git'
url: 'https://github.com/dekz/dcrypt.git'
private: '<EMAIL>:dekz/dcrypt.git'
web: 'https://github.com/dekz/dcrypt'
bugs:
mail: '<EMAIL>'
web: 'https://github.com/dekz/dcrypt/issues'
main: './dcrypt.js'
dependencies:
'coffee-script': '>= 0.9.5 < 1.1.0'
engines:
node: '>= 0.4.2 < 0.5.0'
npm: '>= 0.3.15 < 1.1.0'
| true | name: 'dcrypt'
description: 'extended openssl bindings'
keywords: ['crypt', 'crypto', 'dcrypt', 'openssl']
version: require('fs').readFileSync('./VERSION', 'utf8').trim()
author: 'PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>'
licences: [
type: 'FEISTY'
url: 'http://github.com/feisty/license/raw/master/LICENSE'
]
contributors: ['PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>']
repository:
type: 'git'
url: 'https://github.com/dekz/dcrypt.git'
private: 'PI:EMAIL:<EMAIL>END_PI:dekz/dcrypt.git'
web: 'https://github.com/dekz/dcrypt'
bugs:
mail: 'PI:EMAIL:<EMAIL>END_PI'
web: 'https://github.com/dekz/dcrypt/issues'
main: './dcrypt.js'
dependencies:
'coffee-script': '>= 0.9.5 < 1.1.0'
engines:
node: '>= 0.4.2 < 0.5.0'
npm: '>= 0.3.15 < 1.1.0'
|
[
{
"context": "# numtel:webcomponent\n# MIT License, ben@latenightsketches.com\n# lib/registerElement.coffee\n\n# Register a Blaze ",
"end": 62,
"score": 0.9999207258224487,
"start": 37,
"tag": "EMAIL",
"value": "ben@latenightsketches.com"
}
] | lib/registerElement.coffee | numtel/meteor-webcomponent | 24 | # numtel:webcomponent
# MIT License, ben@latenightsketches.com
# lib/registerElement.coffee
# Register a Blaze Template as a WebComponent
# @param {string} name - Node name for new element (must include hyphen)
# @param {object} options
# @option {string} css - Rules to apply in Shadow DOM context
# @option {[string]} cssLinks - list of hrefs
Blaze.Template.prototype.registerElement = (name, options) ->
blazeTemplate = @
options = _.defaults options || {},
css: undefined
cssLinks: []
# Build styles from options
styles = ''
if options.css or options.cssLinks
styles += '<style>'
for link in options.cssLinks
styles += '@import url("' + link + '");'
if options.css
styles += options.css
styles += '</style>'
# Blaze Template must be wrapped as jQuery fails to find children
# directly from the shadowRoot.
shadowContent = styles + '<div></div>'
newPrototype = Object.create HTMLElement.prototype
newPrototype.createdCallback = ->
shadow = this.createShadowRoot()
shadow.innerHTML = shadowContent
@childRoot = shadow.querySelector 'div'
@blazeData = {}
@blazeView = Blaze.renderWithData blazeTemplate, @blazeData, @childRoot
@blazeView.autorun =>
_.each @blazeView.dataVar.get(), (name, attr) =>
@childRoot.parentNode.host.setAttribute attr, name
newPrototype.attributeChangedCallback = (name, oldValue, newValue) ->
@blazeData = @blazeView.dataVar.get()
@blazeData[name] = newValue
@blazeView.dataVar.set @blazeData
element = document.registerElement name,
prototype: newPrototype
# Create global reference
nameCamelCase = name.replace /-([a-z])/g, (g) -> g[1].toUpperCase()
window[nameCamelCase] = element
| 183897 | # numtel:webcomponent
# MIT License, <EMAIL>
# lib/registerElement.coffee
# Register a Blaze Template as a WebComponent
# @param {string} name - Node name for new element (must include hyphen)
# @param {object} options
# @option {string} css - Rules to apply in Shadow DOM context
# @option {[string]} cssLinks - list of hrefs
Blaze.Template.prototype.registerElement = (name, options) ->
blazeTemplate = @
options = _.defaults options || {},
css: undefined
cssLinks: []
# Build styles from options
styles = ''
if options.css or options.cssLinks
styles += '<style>'
for link in options.cssLinks
styles += '@import url("' + link + '");'
if options.css
styles += options.css
styles += '</style>'
# Blaze Template must be wrapped as jQuery fails to find children
# directly from the shadowRoot.
shadowContent = styles + '<div></div>'
newPrototype = Object.create HTMLElement.prototype
newPrototype.createdCallback = ->
shadow = this.createShadowRoot()
shadow.innerHTML = shadowContent
@childRoot = shadow.querySelector 'div'
@blazeData = {}
@blazeView = Blaze.renderWithData blazeTemplate, @blazeData, @childRoot
@blazeView.autorun =>
_.each @blazeView.dataVar.get(), (name, attr) =>
@childRoot.parentNode.host.setAttribute attr, name
newPrototype.attributeChangedCallback = (name, oldValue, newValue) ->
@blazeData = @blazeView.dataVar.get()
@blazeData[name] = newValue
@blazeView.dataVar.set @blazeData
element = document.registerElement name,
prototype: newPrototype
# Create global reference
nameCamelCase = name.replace /-([a-z])/g, (g) -> g[1].toUpperCase()
window[nameCamelCase] = element
| true | # numtel:webcomponent
# MIT License, PI:EMAIL:<EMAIL>END_PI
# lib/registerElement.coffee
# Register a Blaze Template as a WebComponent
# @param {string} name - Node name for new element (must include hyphen)
# @param {object} options
# @option {string} css - Rules to apply in Shadow DOM context
# @option {[string]} cssLinks - list of hrefs
Blaze.Template.prototype.registerElement = (name, options) ->
blazeTemplate = @
options = _.defaults options || {},
css: undefined
cssLinks: []
# Build styles from options
styles = ''
if options.css or options.cssLinks
styles += '<style>'
for link in options.cssLinks
styles += '@import url("' + link + '");'
if options.css
styles += options.css
styles += '</style>'
# Blaze Template must be wrapped as jQuery fails to find children
# directly from the shadowRoot.
shadowContent = styles + '<div></div>'
newPrototype = Object.create HTMLElement.prototype
newPrototype.createdCallback = ->
shadow = this.createShadowRoot()
shadow.innerHTML = shadowContent
@childRoot = shadow.querySelector 'div'
@blazeData = {}
@blazeView = Blaze.renderWithData blazeTemplate, @blazeData, @childRoot
@blazeView.autorun =>
_.each @blazeView.dataVar.get(), (name, attr) =>
@childRoot.parentNode.host.setAttribute attr, name
newPrototype.attributeChangedCallback = (name, oldValue, newValue) ->
@blazeData = @blazeView.dataVar.get()
@blazeData[name] = newValue
@blazeView.dataVar.set @blazeData
element = document.registerElement name,
prototype: newPrototype
# Create global reference
nameCamelCase = name.replace /-([a-z])/g, (g) -> g[1].toUpperCase()
window[nameCamelCase] = element
|
[
{
"context": "###\n# lib/seed/users.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Seed the datab",
"end": 50,
"score": 0.9997899532318115,
"start": 39,
"tag": "NAME",
"value": "Dan Nichols"
},
{
"context": "actory.create.bind null, 'user',\n email: \"test1@test.com\"\n password: \"test1\"\n Factory.create.bind ",
"end": 361,
"score": 0.9999260902404785,
"start": 347,
"tag": "EMAIL",
"value": "test1@test.com"
},
{
"context": " email: \"test1@test.com\"\n password: \"test1\"\n Factory.create.bind null, 'user',\n emai",
"end": 385,
"score": 0.9994262456893921,
"start": 380,
"tag": "PASSWORD",
"value": "test1"
},
{
"context": "actory.create.bind null, 'user',\n email: \"test2@test.com\"\n password: \"test2\"\n ], (err, results) ->\n ",
"end": 456,
"score": 0.9999251365661621,
"start": 442,
"tag": "EMAIL",
"value": "test2@test.com"
},
{
"context": " email: \"test2@test.com\"\n password: \"test2\"\n ], (err, results) ->\n done(err)\n return\n",
"end": 480,
"score": 0.9994219541549683,
"start": 475,
"tag": "PASSWORD",
"value": "test2"
}
] | lib/seed/users.coffee | dlnichols/h_media | 0 | ###
# lib/seed/users.coffee
#
# © 2014 Dan Nichols
# See LICENSE for more details
#
# Seed the database with archives
###
'use strict'
# External libs
Async = require 'async'
# Internal libs
Factory = require '../../test/lib/factory'
module.exports = (done, results) ->
Async.parallel [
Factory.create.bind null, 'user',
email: "test1@test.com"
password: "test1"
Factory.create.bind null, 'user',
email: "test2@test.com"
password: "test2"
], (err, results) ->
done(err)
return
| 220432 | ###
# lib/seed/users.coffee
#
# © 2014 <NAME>
# See LICENSE for more details
#
# Seed the database with archives
###
'use strict'
# External libs
Async = require 'async'
# Internal libs
Factory = require '../../test/lib/factory'
module.exports = (done, results) ->
Async.parallel [
Factory.create.bind null, 'user',
email: "<EMAIL>"
password: "<PASSWORD>"
Factory.create.bind null, 'user',
email: "<EMAIL>"
password: "<PASSWORD>"
], (err, results) ->
done(err)
return
| true | ###
# lib/seed/users.coffee
#
# © 2014 PI:NAME:<NAME>END_PI
# See LICENSE for more details
#
# Seed the database with archives
###
'use strict'
# External libs
Async = require 'async'
# Internal libs
Factory = require '../../test/lib/factory'
module.exports = (done, results) ->
Async.parallel [
Factory.create.bind null, 'user',
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
Factory.create.bind null, 'user',
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
], (err, results) ->
done(err)
return
|
[
{
"context": "d) ->\n startAP \n ssid: ssid\n pwd: \"12345678\"\n .then ->\n http\n .createServer (req, re",
"end": 503,
"score": 0.9991912841796875,
"start": 495,
"tag": "PASSWORD",
"value": "12345678"
}
] | proxy/index.coffee | twhtanghk/docker.esp8266 | 1 | http = global.require 'http'
wifi = global.require 'Wifi'
log = require './log.coffee'
mac = ->
new Promise (resolve, reject) ->
wifi.getAPIP (cfg) ->
resolve cfg.mac
startAP = (opts)->
new Promise (resolve, reject) ->
wifi.startAP opts.ssid, {authMode: 'wpa2', password: opts.pwd}, (err) ->
if err?
reject err
else
resolve()
mac()
.then (mac) ->
"TT#{mac.split(':').join('')}"
.then (ssid) ->
startAP
ssid: ssid
pwd: "12345678"
.then ->
http
.createServer (req, res) ->
require './app.coffee'
.process req, res
.listen 80
.catch log.error
| 209877 | http = global.require 'http'
wifi = global.require 'Wifi'
log = require './log.coffee'
mac = ->
new Promise (resolve, reject) ->
wifi.getAPIP (cfg) ->
resolve cfg.mac
startAP = (opts)->
new Promise (resolve, reject) ->
wifi.startAP opts.ssid, {authMode: 'wpa2', password: opts.pwd}, (err) ->
if err?
reject err
else
resolve()
mac()
.then (mac) ->
"TT#{mac.split(':').join('')}"
.then (ssid) ->
startAP
ssid: ssid
pwd: "<PASSWORD>"
.then ->
http
.createServer (req, res) ->
require './app.coffee'
.process req, res
.listen 80
.catch log.error
| true | http = global.require 'http'
wifi = global.require 'Wifi'
log = require './log.coffee'
mac = ->
new Promise (resolve, reject) ->
wifi.getAPIP (cfg) ->
resolve cfg.mac
startAP = (opts)->
new Promise (resolve, reject) ->
wifi.startAP opts.ssid, {authMode: 'wpa2', password: opts.pwd}, (err) ->
if err?
reject err
else
resolve()
mac()
.then (mac) ->
"TT#{mac.split(':').join('')}"
.then (ssid) ->
startAP
ssid: ssid
pwd: "PI:PASSWORD:<PASSWORD>END_PI"
.then ->
http
.createServer (req, res) ->
require './app.coffee'
.process req, res
.listen 80
.catch log.error
|
[
{
"context": "e Music\n * @category Web Components\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c",
"end": 96,
"score": 0.9998931884765625,
"start": 80,
"tag": "NAME",
"value": "Nazar Mokrynskyi"
},
{
"context": "y Web Components\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c) 2014-2015, Nazar Mok",
"end": 118,
"score": 0.9999313354492188,
"start": 98,
"tag": "EMAIL",
"value": "nazar@mokrynskyi.com"
},
{
"context": "ynskyi.com>\n * @copyright Copyright (c) 2014-2015, Nazar Mokrynskyi\n * @license MIT License, see license.txt\n###\n\nd",
"end": 175,
"score": 0.9998952150344849,
"start": 159,
"tag": "NAME",
"value": "Nazar Mokrynskyi"
}
] | html/cs-music-library-action/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
###
document.webL10n.ready ->
music_playlist = cs.music_playlist
player = document.querySelector('cs-music-player')
Polymer(
'cs-music-library-action'
create_playlist_text : _('create-playlist')
add_to_playlist_text : _('add-to-playlist')
items : []
update : (items) ->
@items = items
create_playlist : ->
music_playlist.set(@items, =>
player.next =>
@go_to_screen('player')
)
add_to_playlist : ->
music_playlist.append(@items, =>
@go_back_screen()
)
back : ->
@go_back_screen()
)
| 120569 | ###*
* @package CleverStyle Music
* @category Web Components
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2014-2015, <NAME>
* @license MIT License, see license.txt
###
document.webL10n.ready ->
music_playlist = cs.music_playlist
player = document.querySelector('cs-music-player')
Polymer(
'cs-music-library-action'
create_playlist_text : _('create-playlist')
add_to_playlist_text : _('add-to-playlist')
items : []
update : (items) ->
@items = items
create_playlist : ->
music_playlist.set(@items, =>
player.next =>
@go_to_screen('player')
)
add_to_playlist : ->
music_playlist.append(@items, =>
@go_back_screen()
)
back : ->
@go_back_screen()
)
| 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
###
document.webL10n.ready ->
music_playlist = cs.music_playlist
player = document.querySelector('cs-music-player')
Polymer(
'cs-music-library-action'
create_playlist_text : _('create-playlist')
add_to_playlist_text : _('add-to-playlist')
items : []
update : (items) ->
@items = items
create_playlist : ->
music_playlist.set(@items, =>
player.next =>
@go_to_screen('player')
)
add_to_playlist : ->
music_playlist.append(@items, =>
@go_back_screen()
)
back : ->
@go_back_screen()
)
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero G",
"end": 27,
"score": 0.6362142562866211,
"start": 21,
"tag": "NAME",
"value": "ty Ltd"
},
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999116659164429,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmap-discussions.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 { Main } from './beatmap-discussions/main'
reactTurbolinks.registerPersistent 'beatmap-discussions', Main, true, (target) ->
initial: osu.parseJson 'json-beatmapset-discussion'
container: target
| 532 | # Copyright (c) ppy P<NAME> <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { Main } from './beatmap-discussions/main'
reactTurbolinks.registerPersistent 'beatmap-discussions', Main, true, (target) ->
initial: osu.parseJson 'json-beatmapset-discussion'
container: target
| true | # Copyright (c) ppy PPI:NAME:<NAME>END_PI <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 { Main } from './beatmap-discussions/main'
reactTurbolinks.registerPersistent 'beatmap-discussions', Main, true, (target) ->
initial: osu.parseJson 'json-beatmapset-discussion'
container: target
|
[
{
"context": "sid-####\" in the presence of hubot\n#\n# Author:\n# christianchristensen\n\nmodule.exports = (robot) ->\n robot.hear /(sid-|",
"end": 264,
"score": 0.8482671976089478,
"start": 244,
"tag": "NAME",
"value": "christianchristensen"
}
] | src/scripts/pivotalstorylisten.coffee | TaxiOS/hubot-scripts | 0 | # Description:
# Listen for a specific story from PivotalTracker
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_PIVOTAL_TOKEN
#
# Commands:
# paste a pivotal tracker link or type "sid-####" in the presence of hubot
#
# Author:
# christianchristensen
module.exports = (robot) ->
robot.hear /(sid-|SID-|pivotaltracker.com\/story\/show|pivotaltracker.com\/s\/projects\/\d+\/stories\/\d+)/i, (msg) ->
token = process.env.HUBOT_PIVOTAL_TOKEN
story_id = msg.message.text.match(/\d+$/) # look for some numbers in the string
msg.http("https://www.pivotaltracker.com/services/v5/projects").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
try
projects = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal projects body: #{e}"
for project in projects
msg.http("https://www.pivotaltracker.com/services/v5/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
return if res.statusCode == 404 # No story found in this project
try
story = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal story body: #{e}"
message = "##{story.id} #{story.name}"
message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted"
msg.send message
| 77193 | # Description:
# Listen for a specific story from PivotalTracker
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_PIVOTAL_TOKEN
#
# Commands:
# paste a pivotal tracker link or type "sid-####" in the presence of hubot
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.hear /(sid-|SID-|pivotaltracker.com\/story\/show|pivotaltracker.com\/s\/projects\/\d+\/stories\/\d+)/i, (msg) ->
token = process.env.HUBOT_PIVOTAL_TOKEN
story_id = msg.message.text.match(/\d+$/) # look for some numbers in the string
msg.http("https://www.pivotaltracker.com/services/v5/projects").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
try
projects = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal projects body: #{e}"
for project in projects
msg.http("https://www.pivotaltracker.com/services/v5/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
return if res.statusCode == 404 # No story found in this project
try
story = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal story body: #{e}"
message = "##{story.id} #{story.name}"
message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted"
msg.send message
| true | # Description:
# Listen for a specific story from PivotalTracker
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_PIVOTAL_TOKEN
#
# Commands:
# paste a pivotal tracker link or type "sid-####" in the presence of hubot
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.hear /(sid-|SID-|pivotaltracker.com\/story\/show|pivotaltracker.com\/s\/projects\/\d+\/stories\/\d+)/i, (msg) ->
token = process.env.HUBOT_PIVOTAL_TOKEN
story_id = msg.message.text.match(/\d+$/) # look for some numbers in the string
msg.http("https://www.pivotaltracker.com/services/v5/projects").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
try
projects = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal projects body: #{e}"
for project in projects
msg.http("https://www.pivotaltracker.com/services/v5/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) ->
return msg.send "Pivotal says: #{err}" if err
return if res.statusCode == 404 # No story found in this project
try
story = JSON.parse(body)
catch e
return msg.send "Error parsing pivotal story body: #{e}"
message = "##{story.id} #{story.name}"
message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted"
msg.send message
|
[
{
"context": "rted Siren input type\\\n - https://github.com/kevinswiber/siren#type-3\\\n expect radio checkbox and fil",
"end": 1552,
"score": 0.9997241497039795,
"start": 1541,
"tag": "USERNAME",
"value": "kevinswiber"
},
{
"context": "{\n \"type\": \"password\"\n \"name\": \"password1\"\n }\n {\n \"type\": \"datet",
"end": 2179,
"score": 0.6599880456924438,
"start": 2170,
"tag": "PASSWORD",
"value": "password1"
}
] | src/modules/siren-browser/directives/actionFormSpec.coffee | applicaster/siren-browser | 4 | describe "actionForm directive", ->
ele = undefined
scope = undefined
beforeEach(window.angular.mock.module("SirenBrowser"))
beforeEach inject(($compile, $rootScope) ->
scope = $rootScope
ele = angular.element(
'<action-form ng-model="action"/>'
)
$compile(ele)(scope)
scope.$apply()
)
it "dispaly action form", ->
scope.$apply(->
scope.action =
"name": "add-item"
"title": "Add Item"
"method": "POST"
"href": "http://api.x.io/orders/42/items"
"type": "application/x-www-form-urlencoded"
"fields": [
{ "name": "orderNumber", "type": "hidden", "value": "42" }
{ "name": "productCode", "type": "text" }
{ "name": "quantity", "type": "number" }
]
)
expect(ele.html()).toContain('type="text" name="productCode"')
it "check radio buttons by default if their\
selected attribute is set to true", ->
scope.$apply(->
scope.action =
"fields": [
{
"type":"radio"
"value": [
{
"value": "value1"
"selected": true
}
{
"value": "value2"
}
]
}
]
)
expect(ele.find('input[value="value1"]')
.first().attr('checked')).toBe('checked')
expect(ele.find('input[value="value2"]')
.first().attr('checked')).toBeUndefined()
it "show field for all supported Siren input type\
- https://github.com/kevinswiber/siren#type-3\
expect radio checkbox and file types that have thier\
special UI implementation", ->
scope.$apply(->
scope.action =
"fields": [
{
"type": "hidden"
"name": "datetime1"
}
{
"type": "text"
"name": "text1"
}
{
"type": "search"
"name": "search1"
}
{
"type": "tel"
"name": "tel1"
}
{
"type": "email"
"name": "email1"
}
{
"type": "password"
"name": "password1"
}
{
"type": "datetime"
"name": "datetime1"
}
{
"type": "date"
"name": "date1"
}
{
"type": "month"
"name": "month1"
}
{
"type": "week"
"name": "week1"
}
{
"type": "time"
"name": "time1"
}
{
"type": "datetime-local"
"name": "datetime-local1"
}
{
"type": "number"
"name": "number1"
}
{
"type": "range"
"name": "range1"
}
{
"type": "color"
"name": "color1"
}
{
"type": "image"
"name": "image1"
}
]
)
i = 0
while i < scope.action.fields.length
expect(ele.find('input[type="'+scope.action.fields[i].type+'"]')
.first().attr('name')).toBe(scope.action.fields[i].name)
i++
| 208234 | describe "actionForm directive", ->
ele = undefined
scope = undefined
beforeEach(window.angular.mock.module("SirenBrowser"))
beforeEach inject(($compile, $rootScope) ->
scope = $rootScope
ele = angular.element(
'<action-form ng-model="action"/>'
)
$compile(ele)(scope)
scope.$apply()
)
it "dispaly action form", ->
scope.$apply(->
scope.action =
"name": "add-item"
"title": "Add Item"
"method": "POST"
"href": "http://api.x.io/orders/42/items"
"type": "application/x-www-form-urlencoded"
"fields": [
{ "name": "orderNumber", "type": "hidden", "value": "42" }
{ "name": "productCode", "type": "text" }
{ "name": "quantity", "type": "number" }
]
)
expect(ele.html()).toContain('type="text" name="productCode"')
it "check radio buttons by default if their\
selected attribute is set to true", ->
scope.$apply(->
scope.action =
"fields": [
{
"type":"radio"
"value": [
{
"value": "value1"
"selected": true
}
{
"value": "value2"
}
]
}
]
)
expect(ele.find('input[value="value1"]')
.first().attr('checked')).toBe('checked')
expect(ele.find('input[value="value2"]')
.first().attr('checked')).toBeUndefined()
it "show field for all supported Siren input type\
- https://github.com/kevinswiber/siren#type-3\
expect radio checkbox and file types that have thier\
special UI implementation", ->
scope.$apply(->
scope.action =
"fields": [
{
"type": "hidden"
"name": "datetime1"
}
{
"type": "text"
"name": "text1"
}
{
"type": "search"
"name": "search1"
}
{
"type": "tel"
"name": "tel1"
}
{
"type": "email"
"name": "email1"
}
{
"type": "password"
"name": "<PASSWORD>"
}
{
"type": "datetime"
"name": "datetime1"
}
{
"type": "date"
"name": "date1"
}
{
"type": "month"
"name": "month1"
}
{
"type": "week"
"name": "week1"
}
{
"type": "time"
"name": "time1"
}
{
"type": "datetime-local"
"name": "datetime-local1"
}
{
"type": "number"
"name": "number1"
}
{
"type": "range"
"name": "range1"
}
{
"type": "color"
"name": "color1"
}
{
"type": "image"
"name": "image1"
}
]
)
i = 0
while i < scope.action.fields.length
expect(ele.find('input[type="'+scope.action.fields[i].type+'"]')
.first().attr('name')).toBe(scope.action.fields[i].name)
i++
| true | describe "actionForm directive", ->
ele = undefined
scope = undefined
beforeEach(window.angular.mock.module("SirenBrowser"))
beforeEach inject(($compile, $rootScope) ->
scope = $rootScope
ele = angular.element(
'<action-form ng-model="action"/>'
)
$compile(ele)(scope)
scope.$apply()
)
it "dispaly action form", ->
scope.$apply(->
scope.action =
"name": "add-item"
"title": "Add Item"
"method": "POST"
"href": "http://api.x.io/orders/42/items"
"type": "application/x-www-form-urlencoded"
"fields": [
{ "name": "orderNumber", "type": "hidden", "value": "42" }
{ "name": "productCode", "type": "text" }
{ "name": "quantity", "type": "number" }
]
)
expect(ele.html()).toContain('type="text" name="productCode"')
it "check radio buttons by default if their\
selected attribute is set to true", ->
scope.$apply(->
scope.action =
"fields": [
{
"type":"radio"
"value": [
{
"value": "value1"
"selected": true
}
{
"value": "value2"
}
]
}
]
)
expect(ele.find('input[value="value1"]')
.first().attr('checked')).toBe('checked')
expect(ele.find('input[value="value2"]')
.first().attr('checked')).toBeUndefined()
it "show field for all supported Siren input type\
- https://github.com/kevinswiber/siren#type-3\
expect radio checkbox and file types that have thier\
special UI implementation", ->
scope.$apply(->
scope.action =
"fields": [
{
"type": "hidden"
"name": "datetime1"
}
{
"type": "text"
"name": "text1"
}
{
"type": "search"
"name": "search1"
}
{
"type": "tel"
"name": "tel1"
}
{
"type": "email"
"name": "email1"
}
{
"type": "password"
"name": "PI:PASSWORD:<PASSWORD>END_PI"
}
{
"type": "datetime"
"name": "datetime1"
}
{
"type": "date"
"name": "date1"
}
{
"type": "month"
"name": "month1"
}
{
"type": "week"
"name": "week1"
}
{
"type": "time"
"name": "time1"
}
{
"type": "datetime-local"
"name": "datetime-local1"
}
{
"type": "number"
"name": "number1"
}
{
"type": "range"
"name": "range1"
}
{
"type": "color"
"name": "color1"
}
{
"type": "image"
"name": "image1"
}
]
)
i = 0
while i < scope.action.fields.length
expect(ele.find('input[type="'+scope.action.fields[i].type+'"]')
.first().attr('name')).toBe(scope.action.fields[i].name)
i++
|
[
{
"context": "plits splitRatios, splitKeys\n\n randomVecKey = lightning.createTempKey()\n\n statements = []\n\n statements.push \"",
"end": 36963,
"score": 0.881439208984375,
"start": 36940,
"tag": "KEY",
"value": "lightning.createTempKey"
}
] | src/ext/modules/routines.coffee | pingguo1231/h2oai | 0 | Plotly = require('plotly.js')
{ flatten, compact, keyBy, findIndex, isFunction, isArray,
map, uniq, head, keys, range, escape, sortBy, some,
tail, concat, values } = require('lodash')
{ isObject, isNumber } = require('../../core/modules/prelude')
{ words, typeOf, stringify } = require('../../core/modules/prelude')
{ act, react, lift, link, merge, isSignal, signal, signals } = require("../../core/modules/dataflow")
{ TString, TNumber } = require('../../core/modules/types')
async = require('../../core/modules/async')
html = require('../../core/modules/html')
FlowError = require('../../core/modules/flow-error')
objectBrowser = require('../../core/components/object-browser')
util = require('../../core/modules/util')
gui = require('../../core/modules/gui')
form = require('../../core/components/form')
h2o = require('./h2o')
lightning = require('../../core/modules/lightning')
_assistance =
importFiles:
description: 'Import file(s) into H<sub>2</sub>O'
icon: 'files-o'
importSqlTable:
description: 'Import SQL table into H<sub>2</sub>O'
icon: 'table'
getFrames:
description: 'Get a list of frames in H<sub>2</sub>O'
icon: 'table'
splitFrame:
description: 'Split a frame into two or more frames'
icon: 'scissors'
mergeFrames:
description: 'Merge two frames into one'
icon: 'link'
getModels:
description: 'Get a list of models in H<sub>2</sub>O'
icon: 'cubes'
getGrids:
description: 'Get a list of grid search results in H<sub>2</sub>O'
icon: 'th'
getPredictions:
description: 'Get a list of predictions in H<sub>2</sub>O'
icon: 'bolt'
getJobs:
description: 'Get a list of jobs running in H<sub>2</sub>O'
icon: 'tasks'
runAutoML:
description: 'Automatically train and tune many models'
icon: 'sitemap'
buildModel:
description: 'Build a model'
icon: 'cube'
importModel:
description: 'Import a saved model'
icon: 'cube'
predict:
description: 'Make a prediction'
icon: 'bolt'
parseNumbers = (source) ->
target = new Array source.length
for value, i in source
target[i] = if value is 'NaN'
undefined
else if value is 'Infinity'
Number.POSITIVE_INFINITY #TODO handle formatting
else if value is '-Infinity'
Number.NEGATIVE_INFINITY #TODO handle formatting
else
value
target
convertColumnToVector = (column, data) ->
switch column.type
when 'byte', 'short', 'int', 'integer', 'long'
lightning.createVector column.name, TNumber, parseNumbers data
when 'float', 'double'
lightning.createVector column.name, TNumber, (parseNumbers data), format4f
when 'string'
lightning.createFactor column.name, TString, data
when 'matrix'
lightning.createList column.name, data, formatConfusionMatrix
else
lightning.createList column.name, data
convertTableToFrame = (table, tableName, metadata) ->
#TODO handle format strings and description
vectors = for column, i in table.columns
convertColumnToVector column, table.data[i]
lightning.createDataFrame tableName, vectors, (range table.rowcount), null, metadata
getTwoDimData = (table, columnName) ->
columnIndex = findIndex table.columns, (column) -> column.name is columnName
if columnIndex >= 0
table.data[columnIndex]
else
undefined
format4f = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(4).replace(/\.0+$/, '.0')
else
number
format6fi = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(6).replace(/\.0+$/, '')
else
number
combineTables = (tables) ->
leader = head tables
rowCount = 0
columnCount = leader.data.length
data = new Array columnCount
for table in tables
rowCount += table.rowcount
for i in [0 ... columnCount]
data[i] = columnData = new Array rowCount
index = 0
for table in tables
for element in table.data[i]
columnData[index++] = element
name: leader.name
columns: leader.columns
data: data
rowcount: rowCount
createArrays = (count, length) ->
for i in [0 ... count]
new Array length
parseNaNs = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element is 'NaN' then undefined else element
target
parseNulls = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element? then element else undefined
target
parseAndFormatArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if isNumber element
format6fi element
else
element
else
undefined
target
parseAndFormatObjectArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if element.__meta?.schema_type is 'Key<Model>'
"<a href='#' data-type='model' data-key=#{stringify element.name}>#{escape element.name}</a>"
else if element.__meta?.schema_type is 'Key<Frame>'
"<a href='#' data-type='frame' data-key=#{stringify element.name}>#{escape element.name}</a>"
else
element
else
undefined
target
repeatValues = (count, value) ->
target = new Array count
for i in [0 ... count]
target[i] = value
target
concatArrays = (arrays) ->
switch arrays.length
when 0
[]
when 1
head arrays
else
a = head arrays
a.concat.apply a, tail arrays
computeTruePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
tp / (tp + fn)
computeFalsePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
fp / (fp + tn)
formatConfusionMatrix = (cm) ->
[[tn, fp], [fn, tp]] = cm.matrix
fnr = fn / (tp + fn)
fpr = fp / (fp + tn)
domain = cm.domain
[ table, tbody, tr, strong, normal, yellow ] = html.template 'table.flow-matrix', 'tbody', 'tr', 'td.strong.flow-center', 'td', 'td.bg-yellow'
table [
tbody [
tr [
strong 'Actual/Predicted'
strong domain[0]
strong domain[1]
strong 'Error'
strong 'Rate'
]
tr [
strong domain[0]
yellow tn
normal fp
normal format4f fpr
normal fp + ' / ' + (fp + tn)
]
tr [
strong domain[1]
normal fn
yellow tp
normal format4f fnr
normal fn + ' / ' + (tp + fn)
]
tr [
strong 'Total'
strong tn + fn
strong tp + fp
strong format4f (fn + fp) / (fp + tn + tp + fn)
strong (fn + fp) + ' / ' + (fp + tn + tp + fn)
]
]
]
formulateGetPredictionsOrigin = (opts) ->
if isArray opts
sanitizedOpts = for opt in opts
sanitizedOpt = {}
sanitizedOpt.model = opt.model if opt.model
sanitizedOpt.frame = opt.frame if opt.frame
sanitizedOpt
"getPredictions #{stringify sanitizedOpts}"
else
{ model: modelKey, frame: frameKey } = opts
if modelKey and frameKey
"getPredictions model: #{stringify modelKey}, frame: #{stringify frameKey}"
else if modelKey
"getPredictions model: #{stringify modelKey}"
else if frameKey
"getPredictions frame: #{stringify frameKey}"
else
"getPredictions()"
exports.init = (_) ->
#TODO move these into async
_fork = (f, args...) -> async.fork f, args
_join = (args..., go) -> async.join args, async.applicate go
_call = (go, args...) -> async.join args, async.applicate go
_apply = (go, args) -> async.join args, go
_isFuture = async.isFuture
_async = async.async
_get = async.get
#XXX obsolete
proceed = (func, args, go) ->
go null, render_ {}, -> func.apply null, [_].concat args or []
proceed = (func, args, go) ->
go null, render_.apply null, [ {}, func, ].concat args or []
extendGuiForm = (f) ->
render_ f, form, f
createGui = (controls, go) ->
go null, extendGuiForm signals controls or []
gui = (controls) ->
_fork createGui, controls
gui[name] = f for name, f of gui
flow_ = (raw) ->
raw._flow_ or raw._flow_ = _cache_: {}
#XXX obsolete
render_ = (raw, render) ->
(flow_ raw).render = render
raw
render_ = (raw, render, args...) ->
(flow_ raw).render = (go) ->
# Prepend current context (_) and a continuation (go)
render.apply null, [_, go].concat args
raw
inspect_ = (raw, inspectors) ->
root = flow_ raw
root.inspect = {} unless root.inspect?
for attr, f of inspectors
root.inspect[attr] = f
raw
inspect = (a, b) ->
if arguments.length is 1
inspect$1 a
else
inspect$2 a, b
inspect$1 = (obj) ->
if _isFuture obj
_async inspect, obj
else
if inspectors = obj?._flow_?.inspect
inspections = []
for attr, f of inspectors
inspections.push inspect$2 attr, obj
render_ inspections, h2o.InspectsOutput, inspections
inspections
else
{}
ls = (obj) ->
if _isFuture obj
_async ls, obj
else
if inspectors = obj?._flow_?.inspect
keys inspectors
else
[]
inspect$2 = (attr, obj) ->
return unless attr
return _async inspect, attr, obj if _isFuture obj
return unless obj
return unless root = obj._flow_
return unless inspectors = root.inspect
return cached if cached = root._cache_[ key = "inspect_#{attr}" ]
return unless f = inspectors[attr]
return unless isFunction f
root._cache_[key] = inspection = f()
render_ inspection, h2o.InspectOutput, inspection
inspection
_plot = (render, go) ->
render (error, vis) ->
if error
go new FlowError 'Error rendering vis.', error
else
go null, vis
extendPlot = (vis) ->
render_ vis, h2o.PlotOutput, vis.element
createLightningPlot = (f, go) ->
_plot (f lightning), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plot = (f) ->
if _isFuture f
_fork proceed, h2o.PlotInput, f
else if isFunction f
_fork createLightningPlot, f
else
assist plot
createPlotlyPlot = (f, go) ->
_plot (f Plotly), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plotlyPlot = (f) ->
_fork createPlotlyPlot, f
grid = (f) ->
plot (g) -> g(
g.select()
g.from f
)
transformBinomialMetrics = (metrics) ->
if scores = metrics.thresholds_and_metric_scores
domain = metrics.domain
tps = getTwoDimData scores, 'tps'
tns = getTwoDimData scores, 'tns'
fps = getTwoDimData scores, 'fps'
fns = getTwoDimData scores, 'fns'
cms = for tp, i in tps
domain: domain
matrix: [[tns[i], fps[i]], [fns[i], tp]]
scores.columns.push
name: 'CM'
description: 'CM'
format: 'matrix' #TODO HACK
type: 'matrix'
scores.data.push cms
metrics
extendCloud = (cloud) ->
render_ cloud, h2o.CloudOutput, cloud
extendTimeline = (timeline) ->
render_ timeline, h2o.TimelineOutput, timeline
extendStackTrace = (stackTrace) ->
render_ stackTrace, h2o.StackTraceOutput, stackTrace
extendLogFile = (cloud, nodeIpPort, fileType, logFile) ->
render_ logFile, h2o.LogFileOutput, cloud, nodeIpPort, fileType, logFile
inspectNetworkTestResult = (testResult) -> ->
convertTableToFrame testResult.table, testResult.table.name,
description: testResult.table.name
origin: "testNetwork"
extendNetworkTest = (testResult) ->
inspect_ testResult,
result: inspectNetworkTestResult testResult
render_ testResult, h2o.NetworkTestOutput, testResult
extendProfile = (profile) ->
render_ profile, h2o.ProfileOutput, profile
extendFrames = (frames) ->
render_ frames, h2o.FramesOutput, frames
frames
extendSplitFrameResult = (result) ->
render_ result, h2o.SplitFrameOutput, result
result
extendMergeFramesResult = (result) ->
render_ result, h2o.MergeFramesOutput, result
result
extendPartialDependence= (result) ->
inspections = {}
for data, i in result.partial_dependence_data
origin = "getPartialDependence #{stringify result.destination_key}"
inspections["plot#{i+1}"] = inspectTwoDimTable_ origin, "plot#{i+1}", data
inspect_ result, inspections
render_ result, h2o.PartialDependenceOutput, result
result
# inspectOutputsAcrossModels = (modelCategory, models) -> ->
# switch modelCategory
# when 'Binomial'
# when 'Multinomial'
# when 'Regression'
getModelParameterValue = (type, value) ->
switch type
when 'Key<Frame>', 'Key<Model>'
if value? then value.name else undefined
when 'VecSpecifier'
if value? then value.column_name else undefined
else
if value? then value else undefined
inspectParametersAcrossModels = (models) -> ->
leader = head models
vectors = for parameter, i in leader.parameters
data = for model in models
getModelParameterValue parameter.type, model.parameters[i].actual_value
switch parameter.type
when 'enum', 'Frame', 'string'
lightning.createFactor parameter.label, TString, data
when 'byte', 'short', 'int', 'long', 'float', 'double'
lightning.createVector parameter.label, TNumber, data
when 'string[]', 'byte[]', 'short[]', 'int[]', 'long[]', 'float[]', 'double[]'
lightning.createList parameter.label, data, (a) -> if a then a else undefined
when 'boolean'
lightning.createList parameter.label, data, (a) -> if a then 'true' else 'false'
else
lightning.createList parameter.label, data
modelKeys = (model.model_id.name for model in models)
lightning.createDataFrame 'parameters', vectors, (range models.length), null,
description: "Parameters for models #{modelKeys.join ', '}"
origin: "getModels #{stringify modelKeys}"
inspectModelParameters = (model) -> ->
parameters = model.parameters
attrs = [
'label'
'type'
'level'
'actual_value'
'default_value'
]
vectors = for attr in attrs
data = new Array parameters.length
for parameter, i in parameters
data[i] = if attr is 'actual_value'
getModelParameterValue parameter.type, parameter[attr]
else
parameter[attr]
lightning.createList attr, data
lightning.createDataFrame 'parameters', vectors, (range parameters.length), null,
description: "Parameters for model '#{model.model_id.name}'" #TODO frame model_id
origin: "getModel #{stringify model.model_id.name}"
extendJob = (job) ->
render_ job, h2o.JobOutput, job
extendJobs = (jobs) ->
for job in jobs
extendJob job
render_ jobs, h2o.JobsOutput, jobs
extendCancelJob = (cancellation) ->
render_ cancellation, h2o.CancelJobOutput, cancellation
extendDeletedKeys = (keys) ->
render_ keys, h2o.DeleteObjectsOutput, keys
inspectTwoDimTable_ = (origin, tableName, table) -> ->
convertTableToFrame table, tableName,
description: table.description or ''
origin: origin
inspectRawArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatArray array], (range array.length), null,
description: ''
origin: origin
inspectObjectArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatObjectArray array], (range array.length), null,
description: ''
origin: origin
inspectRawObject_ = (name, origin, description, obj) -> ->
vectors = for k, v of obj
lightning.createList k, [ if v is null then undefined else if isNumber v then format6fi v else v ]
lightning.createDataFrame name, vectors, (range 1), null,
description: ''
origin: origin
_globalHacks =
fields: 'reproducibility_information_table'
_schemaHacks =
KMeansOutput:
fields: 'names domains help'
GBMOutput:
fields: 'names domains help'
GLMOutput:
fields: 'names domains help'
DRFOutput:
fields: 'names domains help'
DeepLearningModelOutput:
fields: 'names domains help'
NaiveBayesOutput:
fields: 'names domains help pcond'
PCAOutput:
fields: 'names domains help'
ModelMetricsBinomialGLM:
fields: null
transform: transformBinomialMetrics
ModelMetricsBinomial:
fields: null
transform: transformBinomialMetrics
ModelMetricsMultinomialGLM:
fields: null
ModelMetricsMultinomial:
fields: null
ModelMetricsRegressionGLM:
fields: null
ModelMetricsRegression:
fields: null
ModelMetricsClustering:
fields: null
ModelMetricsAutoEncoder:
fields: null
ConfusionMatrix:
fields: null
blacklistedAttributesBySchema = do ->
dicts = {}
for schema, attrs of _schemaHacks
dicts[schema] = dict = __meta: yes
if attrs.fields
for field in words attrs.fields
dict[field] = yes
dicts
blacklistedAttributesSchemaIndependent = do ->
dict = {}
for attrs of _globalHacks
if attrs = 'fields'
for field in words _globalHacks[attrs]
dict[field] = yes
dict
schemaTransforms = do ->
transforms = {}
for schema, attrs of _schemaHacks
if transform = attrs.transform
transforms[schema] = transform
transforms
inspectObject = (inspections, name, origin, obj) ->
blacklistedAttributes = blacklistedAttributesSchemaIndependent
schemaType = obj.__meta?.schema_type
if schemaType
if attrs = blacklistedAttributesBySchema[schemaType]
for key, value of attrs
blacklistedAttributes[key] = value
obj = transform obj if transform = schemaTransforms[schemaType]
record = {}
inspections[name] = inspectRawObject_ name, origin, name, record
for k, v of obj when not blacklistedAttributes[k]
if v is null
record[k] = null
else
if v.__meta?.schema_type is 'TwoDimTable'
inspections["#{name} - #{v.name}"] = inspectTwoDimTable_ origin, "#{name} - #{v.name}", v
else
if isArray v
if k is 'cross_validation_models' or k is 'cross_validation_predictions' or (name is 'output' and (k is 'weights' or k is 'biases')) # megahack
inspections[k] = inspectObjectArray_ k, origin, k, v
else
inspections[k] = inspectRawArray_ k, origin, k, v
else if isObject v
if meta = v.__meta
if meta.schema_type is 'Key<Frame>'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Key<Model>'
record[k] = "<a href='#' data-type='model' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Frame'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.frame_id.name}>#{escape v.frame_id.name}</a>"
else
inspectObject inspections, "#{name} - #{k}", origin, v
else
console.log "WARNING: dropping [#{k}] from inspection:", v
else
record[k] = if isNumber v then format6fi v else v
return
extendModel = (model) ->
extend = (model) ->
inspections = {}
inspections.parameters = inspectModelParameters model
origin = "getModel #{stringify model.model_id.name}"
inspectObject inspections, 'output', origin, model.output
# Obviously, an array of 2d tables calls for a megahack.
if model.__meta.schema_type is 'NaiveBayesModel'
if isArray model.output.pcond
for table in model.output.pcond
tableName = "output - pcond - #{table.name}"
inspections[tableName] = inspectTwoDimTable_ origin, tableName, table
inspect_ model, inspections
model
refresh = (go) ->
_.requestModel model.model_id.name, (error, model) ->
if error then go error else go null, extend model
extend model
render_ model, h2o.ModelOutput, model, refresh
extendGrid = (grid, opts) ->
origin = "getGrid #{stringify grid.grid_id.name}"
origin += ", #{stringify opts}" if opts
inspections =
summary: inspectTwoDimTable_ origin, "summary", grid.summary_table
scoring_history: inspectTwoDimTable_ origin, "scoring_history", grid.scoring_history
inspect_ grid, inspections
render_ grid, h2o.GridOutput, grid
extendGrids = (grids) ->
render_ grids, h2o.GridsOutput, grids
extendLeaderboard = (result) ->
render_ result, h2o.LeaderboardOutput, result
extendModels = (models) ->
inspections = {}
algos = uniq (model.algo for model in models)
if algos.length is 1
inspections.parameters = inspectParametersAcrossModels models
# modelCategories = uniq (model.output.model_category for model in models)
# TODO implement model comparision after 2d table cleanup for model metrics
#if modelCategories.length is 1
# inspections.outputs = inspectOutputsAcrossModels (head modelCategories), models
inspect_ models, inspections
render_ models, h2o.ModelsOutput, models
read = (value) -> if value is 'NaN' then null else value
extendPredictions = (opts, predictions) ->
render_ predictions, h2o.PredictsOutput, opts, predictions
predictions
extendPrediction = (result) ->
modelKey = result.model.name
frameKey = result.frame?.name
prediction = head result.model_metrics
predictionFrame = if result.predictions_frame is null then result.frame? else result.predictions_frame
inspections = {}
if prediction
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", prediction
else
prediction = {}
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", { prediction_frame: predictionFrame }
inspect_ prediction, inspections
render_ prediction, h2o.PredictOutput, modelKey, frameKey, predictionFrame, prediction
inspectFrameColumns = (tableLabel, frameKey, frame, frameColumns) -> ->
attrs = [
'label'
'type'
'missing_count|Missing'
'zero_count|Zeros'
'positive_infinity_count|+Inf'
'negative_infinity_count|-Inf'
'min'
'max'
'mean'
'sigma'
'cardinality'
]
toColumnSummaryLink = (label) ->
"<a href='#' data-type='summary-link' data-key=#{stringify label}>#{escape label}</a>"
toConversionLink = (value) ->
[ type, label ] = value.split '\0'
switch type
when 'enum'
"<a href='#' data-type='as-numeric-link' data-key=#{stringify label}>Convert to numeric</a>"
when 'int', 'string'
"<a href='#' data-type='as-factor-link' data-key=#{stringify label}>Convert to enum</a>"
else
undefined
vectors = for attr in attrs
[ name, title ] = attr.split '|'
title = title ? name
switch name
when 'min'
lightning.createVector title, TNumber, (head column.mins for column in frameColumns), format4f
when 'max'
lightning.createVector title, TNumber, (head column.maxs for column in frameColumns), format4f
when 'cardinality'
lightning.createVector title, TNumber, ((if column.type is 'enum' then column.domain_cardinality else undefined) for column in frameColumns)
when 'label'
lightning.createFactor title, TString, (column[name] for column in frameColumns), null, toColumnSummaryLink
when 'type'
lightning.createFactor title, TString, (column[name] for column in frameColumns)
when 'mean', 'sigma'
lightning.createVector title, TNumber, (column[name] for column in frameColumns), format4f
else
lightning.createVector title, TNumber, (column[name] for column in frameColumns)
[ labelVector, typeVector ] = vectors
actionsData = for i in [0 ... frameColumns.length]
"#{typeVector.valueAt i}\0#{labelVector.valueAt i}"
vectors.push lightning.createFactor 'Actions', TString, actionsData, null, toConversionLink
lightning.createDataFrame tableLabel, vectors, (range frameColumns.length), null,
description: "A list of #{tableLabel} in the H2O Frame."
origin: "getFrameSummary #{stringify frameKey}"
plot: "plot inspect '#{tableLabel}', getFrameSummary #{stringify frameKey}"
inspectFrameData = (frameKey, frame) -> ->
frameColumns = frame.columns
vectors = for column in frameColumns
#XXX format functions
switch column.type
when 'int', 'real'
lightning.createVector column.label, TNumber, (parseNaNs column.data), format4f
when 'enum'
domain = column.domain
lightning.createFactor column.label, TString, ((if index? then domain[index] else undefined) for index in column.data)
when 'time'
lightning.createVector column.label, TNumber, parseNaNs column.data
when 'string', 'uuid'
lightning.createList column.label, parseNulls column.string_data
else
lightning.createList column.label, parseNulls column.data
vectors.unshift lightning.createVector 'Row', TNumber, (rowIndex + 1 for rowIndex in [frame.row_offset ... frame.row_count])
lightning.createDataFrame 'data', vectors, (range frame.row_count - frame.row_offset), null,
description: 'A partial list of rows in the H2O Frame.'
origin: "getFrameData #{stringify frameKey}"
extendFrameData = (frameKey, frame) ->
inspections =
data: inspectFrameData frameKey, frame
origin = "getFrameData #{stringify frameKey}"
inspect_ frame, inspections
render_ frame, h2o.FrameDataOutput, frame
extendFrame = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
data: inspectFrameData frameKey, frame
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendFrameSummary = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendColumnSummary = (frameKey, frame, columnName) ->
column = head frame.columns
rowCount = frame.rows
inspectPercentiles = ->
vectors = [
lightning.createVector 'percentile', TNumber, frame.default_percentiles
lightning.createVector 'value', TNumber, column.percentiles
]
lightning.createDataFrame 'percentiles', vectors, (range frame.default_percentiles.length), null,
description: "Percentiles for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDistribution = ->
minBinCount = 32
{ histogram_base:base, histogram_stride:stride, histogram_bins:bins } = column
width = Math.ceil bins.length / minBinCount
interval = stride * width
rows = []
if width > 0
binCount = minBinCount + if bins.length % width > 0 then 1 else 0
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for i in [0 ... binCount]
m = i * width
n = m + width
count = 0
for binIndex in [m ... n] when binIndex < bins.length
count += bins[binIndex]
intervalData[i] = base + i * interval
widthData[i] = interval
countData[i] = count
else
binCount = bins.length
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for count, i in bins
intervalData[i] = base + i * stride
widthData[i] = stride
countData[i] = count
# Trim off empty bins from the end
for i in [binCount - 1 .. 0]
if countData[i] isnt 0
binCount = i + 1
intervalData = intervalData.slice 0, binCount
widthData = widthData.slice 0, binCount
countData = countData.slice 0, binCount
break
vectors = [
lightning.createFactor 'interval', TString, intervalData
lightning.createVector 'width', TNumber, widthData
lightning.createVector 'count', TNumber, countData
]
lightning.createDataFrame 'distribution', vectors, (range binCount), null,
description: "Distribution for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'distribution', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectCharacteristics = ->
{ missing_count, zero_count, positive_infinity_count, negative_infinity_count } = column
other = rowCount - missing_count - zero_count - positive_infinity_count - negative_infinity_count
characteristicData = [ 'Missing', '-Inf', 'Zero', '+Inf', 'Other' ]
countData = [ missing_count, negative_infinity_count, zero_count, positive_infinity_count, other ]
percentData = for count in countData
100 * count / rowCount
vectors = [
lightning.createFactor 'characteristic', TString, characteristicData
lightning.createVector 'count', TNumber, countData
lightning.createVector 'percent', TNumber, percentData
]
lightning.createDataFrame 'characteristics', vectors, (range characteristicData.length), null,
description: "Characteristics for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'characteristics', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectSummary = ->
defaultPercentiles = frame.default_percentiles
percentiles = column.percentiles
mean = column.mean
q1 = percentiles[defaultPercentiles.indexOf 0.25]
q2 = percentiles[defaultPercentiles.indexOf 0.5]
q3 = percentiles[defaultPercentiles.indexOf 0.75]
outliers = uniq concat column.mins, column.maxs
minimum = head column.mins
maximum = head column.maxs
vectors = [
lightning.createFactor 'column', TString, [ columnName ]
lightning.createVector 'mean', TNumber, [ mean ]
lightning.createVector 'q1', TNumber, [ q1 ]
lightning.createVector 'q2', TNumber, [ q2 ]
lightning.createVector 'q3', TNumber, [ q3 ]
lightning.createVector 'min', TNumber, [ minimum ]
lightning.createVector 'max', TNumber, [ maximum ]
]
lightning.createDataFrame 'summary', vectors, (range 1), null,
description: "Summary for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'summary', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDomain = ->
levels = map column.histogram_bins, (count, index) -> count: count, index: index
#TODO sort table in-place when sorting is implemented
sortedLevels = sortBy levels, (level) -> -level.count
[ labels, counts, percents ] = createArrays 3, sortedLevels.length
for level, i in sortedLevels
labels[i] = column.domain[level.index]
counts[i] = level.count
percents[i] = 100 * level.count / rowCount
vectors = [
lightning.createFactor 'label', TString, labels
lightning.createVector 'count', TNumber, counts
lightning.createVector 'percent', TNumber, percents
]
lightning.createDataFrame 'domain', vectors, (range sortedLevels.length), null,
description: "Domain for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'domain', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspections =
characteristics: inspectCharacteristics
switch column.type
when 'int', 'real'
# Skip for columns with all NAs
if column.histogram_bins.length
inspections.distribution = inspectDistribution
# Skip for columns with all NAs
unless (some column.percentiles, (a) -> a is 'NaN')
inspections.summary = inspectSummary
inspections.percentiles = inspectPercentiles
when 'enum'
inspections.domain = inspectDomain
inspect_ frame, inspections
render_ frame, h2o.ColumnSummaryOutput, frameKey, frame, columnName
requestFrame = (frameKey, go) ->
_.requestFrameSlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrame frameKey, frame
requestFrameData = (frameKey, searchTerm, offset, count, go) ->
_.requestFrameSlice frameKey, searchTerm, offset, count, (error, frame) ->
if error
go error
else
go null, extendFrameData frameKey, frame
requestFrameSummarySlice = (frameKey, searchTerm, offset, length, go) ->
_.requestFrameSummarySlice frameKey, searchTerm, offset, length, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestFrameSummary = (frameKey, go) ->
_.requestFrameSummarySlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestColumnSummary = (frameKey, columnName, go) ->
_.requestColumnSummary frameKey, columnName, (error, frame) ->
if error
go error
else
go null, extendColumnSummary frameKey, frame, columnName
requestFrames = (go) ->
_.requestFrames (error, frames) ->
if error
go error
else
go null, extendFrames frames
requestCreateFrame = (opts, go) ->
_.requestCreateFrame opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependence = (opts, go) ->
_.requestPartialDependence opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependenceData = (key, go) ->
_.requestPartialDependenceData key, (error, result) ->
if error
go error
else
go null, extendPartialDependence result
computeSplits = (ratios, keys) ->
parts = []
sum = 0
for key, i in keys.slice(0, ratios.length)
sum += ratio = ratios[i]
parts.push
key: key
ratio: ratio
parts.push
key: keys[keys.length - 1]
ratio: 1 - sum
splits = []
sum = 0
for part in parts
splits.push
min: sum
max: sum + part.ratio
key: part.key
sum += part.ratio
splits
requestBindFrames = (key, sourceKeys, go) ->
_.requestExec "(assign #{key} (cbind #{sourceKeys.join ' '}))", (error, result) ->
if error
go error
else
go null, extendBindFrames key, result
requestSplitFrame = (frameKey, splitRatios, splitKeys, seed, go) ->
if splitRatios.length is splitKeys.length - 1
splits = computeSplits splitRatios, splitKeys
randomVecKey = lightning.createTempKey()
statements = []
statements.push "(tmp= #{randomVecKey} (h2o.runif #{frameKey} #{seed}))"
for part, i in splits
g = if i isnt 0 then "(> #{randomVecKey} #{part.min})" else null
l = if i isnt splits.length - 1 then "(<= #{randomVecKey} #{part.max})" else null
sliceExpr = if g and l
"(& #{g} #{l})"
else if l
l
else
g
statements.push "(assign #{part.key} (rows #{frameKey} #{sliceExpr}))"
statements.push "(rm #{randomVecKey})"
_.requestExec "(, #{statements.join ' '})", (error, result) ->
if error
go error
else
go null, extendSplitFrameResult
keys: splitKeys
ratios: splitRatios
else
go new FlowError 'The number of split ratios should be one less than the number of split keys'
requestMergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows, go) ->
lr = if includeAllLeftRows then 'TRUE' else 'FALSE'
rr = if includeAllRightRows then 'TRUE' else 'FALSE'
statement = "(assign #{destinationKey} (merge #{leftFrameKey} #{rightFrameKey} #{lr} #{rr} #{leftColumnIndex} #{rightColumnIndex} \"radix\"))"
_.requestExec statement, (error, result) ->
if error
go error
else
go null, extendMergeFramesResult
key: destinationKey
createFrame = (opts) ->
if opts
_fork requestCreateFrame, opts
else
assist createFrame
splitFrame = (frameKey, splitRatios, splitKeys, seed=-1) ->
if frameKey and splitRatios and splitKeys
_fork requestSplitFrame, frameKey, splitRatios, splitKeys, seed
else
assist splitFrame
mergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows) ->
if destinationKey and leftFrameKey and rightFrameKey
_fork requestMergeFrames, destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows
else
assist mergeFrames
# define the function that is called when
# the Partial Dependence plot input form
# is submitted
buildPartialDependence = (opts) ->
if opts
_fork requestPartialDependence, opts
else
# specify function to call if user
# provides malformed input
assist buildPartialDependence
getPartialDependence = (destinationKey) ->
if destinationKey
_fork requestPartialDependenceData, destinationKey
else
assist getPartialDependence
getFrames = ->
_fork requestFrames
getFrame = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrame, frameKey
else
assist getFrame
bindFrames = (key, sourceKeys) ->
_fork requestBindFrames, key, sourceKeys
getFrameSummary = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameSummary, frameKey
else
assist getFrameSummary
getFrameData = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameData, frameKey, undefined, 0, 20
else
assist getFrameSummary
requestDeleteFrame = (frameKey, go) ->
_.requestDeleteFrame frameKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ frameKey ]
deleteFrame = (frameKey) ->
if frameKey
_fork requestDeleteFrame, frameKey
else
assist deleteFrame
extendExportFrame = (result) ->
render_ result, h2o.ExportFrameOutput, result
extendBindFrames = (key, result) ->
render_ result, h2o.BindFramesOutput, key, result
requestExportFrame = (frameKey, path, opts, go) ->
_.requestExportFrame frameKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error
go error
else
_.requestJob result.job.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
exportFrame = (frameKey, path, opts={}) ->
if frameKey and path
_fork requestExportFrame, frameKey, path, opts
else
assist exportFrame, frameKey, path, opts
requestDeleteFrames = (frameKeys, go) ->
futures = map frameKeys, (frameKey) ->
_fork _.requestDeleteFrame, frameKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys frameKeys
deleteFrames = (frameKeys) ->
switch frameKeys.length
when 0
assist deleteFrames
when 1
deleteFrame head frameKeys
else
_fork requestDeleteFrames, frameKeys
getColumnSummary = (frameKey, columnName) ->
_fork requestColumnSummary, frameKey, columnName
requestModels = (go) ->
_.requestModels (error, models) ->
if error then go error else go null, extendModels models
requestModelsByKeys = (modelKeys, go) ->
futures = map modelKeys, (key) ->
_fork _.requestModel, key
async.join futures, (error, models) ->
if error then go error else go null, extendModels models
getModels = (modelKeys) ->
if isArray modelKeys
if modelKeys.length
_fork requestModelsByKeys, modelKeys
else
_fork requestModels
else
_fork requestModels
requestGrids = (go) ->
_.requestGrids (error, grids) ->
if error then go error else go null, extendGrids grids
getGrids = ->
_fork requestGrids
requestLeaderboard = (key, go) ->
_.requestLeaderboard key, (error, leaderboard) ->
if error then go error else go null, extendLeaderboard leaderboard
getLeaderboard = (key) ->
_fork requestLeaderboard, key
requestModel = (modelKey, go) ->
_.requestModel modelKey, (error, model) ->
if error then go error else go null, extendModel model
getModel = (modelKey) ->
switch typeOf modelKey
when 'String'
_fork requestModel, modelKey
else
assist getModel
requestGrid = (gridKey, opts, go) ->
_.requestGrid gridKey, opts, (error, grid) ->
if error then go error else go null, extendGrid grid, opts
getGrid = (gridKey, opts) ->
switch typeOf gridKey
when 'String'
_fork requestGrid, gridKey, opts
else
assist getGrid
findColumnIndexByColumnLabel = (frame, columnLabel) ->
for column, i in frame.columns when column.label is columnLabel
return i
throw new FlowError "Column [#{columnLabel}] not found in frame"
findColumnIndicesByColumnLabels = (frame, columnLabels) ->
for columnLabel in columnLabels
findColumnIndexByColumnLabel frame, columnLabel
requestImputeColumn = (opts, go) ->
{ frame, column, method, combineMethod, groupByColumns } = opts
combineMethod = combineMethod ? 'interpolate'
_.requestFrameSummaryWithoutData frame, (error, result) ->
if error
go error
else
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
if groupByColumns and groupByColumns.length
try
groupByColumnIndices = findColumnIndicesByColumnLabels result, groupByColumns
catch columnIndicesError
return go columnIndicesError
else
groupByColumnIndices = null
groupByArg = if groupByColumnIndices
"[#{groupByColumnIndices.join ' '}]"
else
"[]"
_.requestExec "(h2o.impute #{frame} #{columnIndex} #{JSON.stringify method} #{JSON.stringify combineMethod} #{groupByArg} _ _)", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
requestChangeColumnType = (opts, go) ->
{ frame, column, type } = opts
method = if type is 'enum' then 'as.factor' else 'as.numeric'
_.requestFrameSummaryWithoutData frame, (error, result) ->
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
_.requestExec "(assign #{frame} (:= #{frame} (#{method} (cols #{frame} #{columnIndex})) #{columnIndex} [0:#{result.rows}]))", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
imputeColumn = (opts) ->
if opts and opts.frame and opts.column and opts.method
_fork requestImputeColumn, opts
else
assist imputeColumn, opts
changeColumnType = (opts) ->
if opts and opts.frame and opts.column and opts.type
_fork requestChangeColumnType, opts
else
assist changeColumnType, opts
requestDeleteModel = (modelKey, go) ->
_.requestDeleteModel modelKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ modelKey ]
deleteModel = (modelKey) ->
if modelKey
_fork requestDeleteModel, modelKey
else
assist deleteModel
extendImportModel = (result) ->
render_ result, h2o.ImportModelOutput, result
requestImportModel = (path, opts, go) ->
_.requestImportModel path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendImportModel result
importModel = (path, opts) ->
if path and path.length
_fork requestImportModel, path, opts
else
assist importModel, path, opts
extendExportModel = (result) ->
render_ result, h2o.ExportModelOutput, result
requestExportModel = (modelKey, path, opts, go) ->
_.requestExportModel opts.format, modelKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendExportModel result
exportModel = (modelKey, path, opts) ->
if modelKey and path
_fork requestExportModel, modelKey, path, opts
else
assist exportModel, modelKey, path, opts
requestDeleteModels = (modelKeys, go) ->
futures = map modelKeys, (modelKey) ->
_fork _.requestDeleteModel, modelKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys modelKeys
deleteModels = (modelKeys) ->
switch modelKeys.length
when 0
assist deleteModels
when 1
deleteModel head modelKeys
else
_fork requestDeleteModels, modelKeys
requestJob = (key, go) ->
_.requestJob key, (error, job) ->
if error
go error
else
go null, extendJob job
requestJobs = (go) ->
_.requestJobs (error, jobs) ->
if error
go error
else
go null, extendJobs jobs
getJobs = ->
_fork requestJobs
getJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestJob, arg
when 'Object'
if arg.key?
getJob arg.key
else
assist getJob
else
assist getJob
requestCancelJob = (key, go) ->
_.requestCancelJob key, (error) ->
if error
go error
else
go null, extendCancelJob {}
cancelJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestCancelJob, arg
else
assist cancelJob
extendImportResults = (importResults) ->
render_ importResults, h2o.ImportFilesOutput, importResults
requestImportFiles = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
go null, extendImportResults importResults
importFiles = (paths) ->
switch typeOf paths
when 'Array'
_fork requestImportFiles, paths
else
assist importFiles
extendImportSqlResults = (importResults) ->
render_ importResults, h2o.ImportSqlTableOutput, importResults
requestImportSqlTable = (arg, go) ->
_.requestImportSqlTable arg, (error, importResults) ->
if error
go error
else
go null, extendImportSqlResults importResults
importSqlTable = (arg) ->
switch typeOf arg
when 'Object'
_fork requestImportSqlTable, arg
else
assist importSqlTable
importBqTable = ->
assist importBqTable
extendParseSetupResults = (args, parseSetupResults) ->
render_ parseSetupResults, h2o.SetupParseOutput, args, parseSetupResults
requestImportAndParseSetup = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { paths: paths }, parseSetupResults
requestParseSetup = (sourceKeys, go) ->
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { source_frames: sourceKeys }, parseSetupResults
setupParse = (args) ->
if args.paths and isArray args.paths
_fork requestImportAndParseSetup, args.paths
else if args.source_frames and isArray args.source_frames
_fork requestParseSetup, args.source_frames
else
assist setupParse
extendParseResult = (parseResult) ->
render_ parseResult, h2o.JobOutput, parseResult.job
requestImportAndParseFiles = (paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
requestParseFiles = (sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
parseFiles = (opts) -> #XXX review args
#XXX validation
destinationKey = opts.destination_frame
parseType = opts.parse_type
separator = opts.separator
columnCount = opts.number_columns
useSingleQuotes = opts.single_quotes
columnNames = opts.column_names
columnTypes = opts.column_types
deleteOnDone = opts.delete_on_done
checkHeader = opts.check_header
chunkSize = opts.chunk_size
if opts.paths
_fork requestImportAndParseFiles, opts.paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
else
_fork requestParseFiles, opts.source_frames, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
requestModelBuild = (algo, opts, go) ->
_.requestModelBuild algo, opts, (error, result) ->
if error
go error
else
if result.error_count > 0
messages = (validation.message for validation in result.messages)
go new FlowError "Model build failure: #{messages.join '; '}"
else
go null, extendJob result.job
requestAutoMLBuild = (opts , go) ->
_.requestAutoMLBuild opts, (error, result) ->
if error
go error
else
go null, extendJob result.job
runAutoML = (opts, action) ->
if action is 'exec'
_fork requestAutoMLBuild, opts
else
assist runAutoML, opts
buildModel = (algo, opts) ->
if algo and opts and keys(opts).length > 1
_fork requestModelBuild, algo, opts
else
assist buildModel, algo, opts
unwrapPrediction = (go) ->
(error, result) ->
if error
go error
else
go null, extendPrediction result
requestPredict = (destinationKey, modelKey, frameKey, options, go) ->
_.requestPredict destinationKey, modelKey, frameKey, options, unwrapPrediction go
requestPredicts = (opts, go) ->
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey, options: options } = opt
_fork _.requestPredict, null, modelKey, frameKey, options or {}
async.join futures, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
predict = (opts={}) ->
{ predictions_frame, model, models, frame, frames, reconstruction_error, deep_features_hidden_layer, leaf_node_assignment, exemplar_index } = opts
if models or frames
unless models
if model
models = [ model ]
unless frames
if frame
frames = [ frame ]
if frames and models
combos = []
for model in models
for frame in frames
combos.push model: model, frame: frame
_fork requestPredicts, combos
else
assist predict, predictions_frame: predictions_frame, models: models, frames: frames
else
if model and frame
_fork requestPredict, predictions_frame, model, frame,
reconstruction_error: reconstruction_error
deep_features_hidden_layer: deep_features_hidden_layer
leaf_node_assignment: leaf_node_assignment
else if model and exemplar_index isnt undefined
_fork requestPredict, predictions_frame, model, null,
exemplar_index: exemplar_index
else
assist predict, predictions_frame: predictions_frame, model: model, frame: frame
requestPrediction = (modelKey, frameKey, go) ->
_.requestPrediction modelKey, frameKey, unwrapPrediction go
requestPredictions = (opts, go) ->
if isArray opts
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey } = opt
_fork _.requestPredictions, modelKey, frameKey
async.join futures, (error, predictions) ->
if error
go error
else
# De-dupe predictions
uniquePredictions = values keyBy (flatten predictions, yes), (prediction) -> prediction.model.name + prediction.frame.name
go null, extendPredictions opts, uniquePredictions
else
{ model: modelKey, frame: frameKey } = opts
_.requestPredictions modelKey, frameKey, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
getPrediction = (opts={}) ->
{ predictions_frame, model, frame } = opts
if model and frame
_fork requestPrediction, model, frame
else
assist getPrediction, predictions_frame: predictions_frame, model: model, frame: frame
getPredictions = (opts={}) ->
_fork requestPredictions, opts
requestCloud = (go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
go null, extendCloud cloud
getCloud = ->
_fork requestCloud
requestTimeline = (go) ->
_.requestTimeline (error, timeline) ->
if error
go error
else
go null, extendTimeline timeline
getTimeline = ->
_fork requestTimeline
requestStackTrace = (go) ->
_.requestStackTrace (error, stackTrace) ->
if error
go error
else
go null, extendStackTrace stackTrace
getStackTrace = ->
_fork requestStackTrace
requestLogFile = (nodeIpPort, fileType, go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
_.requestLogFile nodeIpPort, fileType, (error, logFile) ->
if error
go error
else
go null, extendLogFile cloud, nodeIpPort, fileType, logFile
getLogFile = (nodeIpPort="self", fileType='info') ->
_fork requestLogFile, nodeIpPort, fileType
requestNetworkTest = (go) ->
_.requestNetworkTest (error, result) ->
if error
go error
else
go null, extendNetworkTest result
testNetwork = ->
_fork requestNetworkTest
requestRemoveAll = (go) ->
_.requestRemoveAll (error, result) ->
if error
go error
else
go null, extendDeletedKeys []
deleteAll = ->
_fork requestRemoveAll
extendRDDs = (rdds) ->
render_ rdds, h2o.RDDsOutput, rdds
rdds
requestRDDs = (go) ->
_.requestRDDs (error, result) ->
if error
go error
else
go null, extendRDDs result.rdds
getRDDs = ->
_fork requestRDDs
extendDataFrames = (dataframes) ->
render_ dataframes, h2o.DataFramesOutput, dataframes
dataframes
requestDataFrames = (go) ->
_.requestDataFrames (error, result) ->
if error
go error
else
go null, extendDataFrames result.dataframes
getDataFrames = ->
_fork requestDataFrames
extendAsH2OFrame = (result) ->
render_ result, h2o.H2OFrameOutput, result
result
requestAsH2OFrameFromRDD = (rdd_id, name, go) ->
_.requestAsH2OFrameFromRDD rdd_id,name, (error, h2oframe_id) ->
if error
go error
else
go null, extendAsH2OFrame h2oframe_id
asH2OFrameFromRDD = (rdd_id, name=undefined) ->
_fork requestAsH2OFrameFromRDD, rdd_id, name
requestAsH2OFrameFromDF = (df_id, name, go) ->
_.requestAsH2OFrameFromDF df_id, name, (error, result) ->
if error
go error
else
go null, extendAsH2OFrame result
asH2OFrameFromDF = (df_id, name=undefined) ->
_fork requestAsH2OFrameFromDF, df_id, name
extendAsDataFrame = (result) ->
render_ result, h2o.DataFrameOutput, result
result
requestAsDataFrame = (hf_id, name, go) ->
_.requestAsDataFrame hf_id, name, (error, result) ->
if error
go error
else
go null, extendAsDataFrame result
asDataFrame = (hf_id, name=undefined) ->
_fork requestAsDataFrame, hf_id, name
getScalaCodeExecutionResult = (key) ->
switch typeOf key
when 'String'
_fork requestScalaCodeExecutionResult, key
else
assist getScalaCodeExecutionResult
requestScalaCodeExecutionResult = (key, go) ->
_.requestScalaCodeExecutionResult key, (error, result) ->
if error
go error
else
go null, extendScalaSyncCode result
requestScalaCode = (session_id, async, code, go) ->
_.requestScalaCode session_id, code, (error, result) ->
if error
go error
else
if async
go null, extendScalaAsyncCode result
else
go null, extendScalaSyncCode result
extendScalaSyncCode = (result) ->
render_ result, h2o.ScalaCodeOutput, result
result
extendScalaAsyncCode = (result) ->
render_ result, h2o.JobOutput, result.job
result
runScalaCode = (session_id, async, code) ->
_fork requestScalaCode, session_id, async, code
requestScalaIntp = (go) ->
_.requestScalaIntp (error, result) ->
if error
go error
else
go null, extendScalaIntp result
extendScalaIntp = (result) ->
render_ result, h2o.ScalaIntpOutput, result
result
getScalaIntp = ->
_fork requestScalaIntp
requestProfile = (depth, go) ->
_.requestProfile depth, (error, profile) ->
if error
go error
else
go null, extendProfile profile
getProfile = (opts) ->
opts = depth: 10 unless opts
_fork requestProfile, opts.depth
loadScript = (path, go) ->
onDone = (script, status) -> go null, script:script, status:status
onFail = (jqxhr, settings, error) -> go error #TODO use framework error
$.getScript path
.done onDone
.fail onFail
dumpFuture = (result, go) ->
result ?= {}
console.debug result
go null, render_ result, objectBrowser, 'dump', result
dump = (f) ->
if f?.isFuture
_fork dumpFuture, f
else
async.async -> f
assist = (func, args...) ->
if func is undefined
_fork proceed, h2o.Assist, [ _assistance ]
else
switch func
when importFiles
_fork proceed, h2o.ImportFilesInput, []
when importSqlTable
_fork proceed, h2o.ImportSqlTableInput, args
when importBqTable
_fork proceed, h2o.ImportBqTableInput, args
when buildModel
_fork proceed, h2o.ModelInput, args
when runAutoML
_fork proceed, h2o.AutoMLInput, args
when predict, getPrediction
_fork proceed, h2o.PredictInput, args
when createFrame
_fork proceed, h2o.CreateFrameInput, args
when splitFrame
_fork proceed, h2o.SplitFrameInput, args
when mergeFrames
_fork proceed, h2o.MergeFramesInput, args
when buildPartialDependence
_fork proceed, h2o.PartialDependenceInput, args
when exportFrame
_fork proceed, h2o.ExportFrameInput, args
when imputeColumn
_fork proceed, h2o.ImputeInput, args
when importModel
_fork proceed, h2o.ImportModelInput, args
when exportModel
_fork proceed, h2o.ExportModelInput, args
else
_fork proceed, h2o.NoAssist, []
link _.ready, ->
link _.ls, ls
link _.inspect, inspect
link _.plot, (p) -> p lightning
link _.plotlyPlot, (p) -> p Plotly
link _.grid, (frame) ->
lightning(
lightning.select()
lightning.from frame
)
link _.enumerate, (frame) ->
lightning(
lightning.select 0
lightning.from frame
)
link _.requestFrameDataE, requestFrameData
link _.requestFrameSummarySliceE, requestFrameSummarySlice
initAssistanceSparklingWater = ->
_assistance.getRDDs =
description: 'Get a list of Spark\'s RDDs'
icon: 'table'
_assistance.getDataFrames =
description: 'Get a list of Spark\'s data frames'
icon: 'table'
link _.initialized, ->
if _.onSparklingWater
initAssistanceSparklingWater()
routines =
# fork/join
fork: _fork
join: _join
call: _call
apply: _apply
isFuture: _isFuture
#
# Dataflow
signal: signal
signals: signals
isSignal: isSignal
act: act
react: react
lift: lift
merge: merge
#
# Generic
dump: dump
inspect: inspect
plot: plot
plotlyPlot: plotlyPlot
grid: grid
get: _get
#
# Meta
assist: assist
#
# GUI
gui: gui
#
# Util
loadScript: loadScript
#
# H2O
getJobs: getJobs
getJob: getJob
cancelJob: cancelJob
importFiles: importFiles
importSqlTable: importSqlTable
importBqTable: importBqTable
setupParse: setupParse
parseFiles: parseFiles
createFrame: createFrame
splitFrame: splitFrame
mergeFrames: mergeFrames
buildPartialDependence: buildPartialDependence
getPartialDependence: getPartialDependence
getFrames: getFrames
getFrame: getFrame
bindFrames: bindFrames
getFrameSummary: getFrameSummary
getFrameData: getFrameData
deleteFrames: deleteFrames
deleteFrame: deleteFrame
exportFrame: exportFrame
getColumnSummary: getColumnSummary
changeColumnType: changeColumnType
imputeColumn: imputeColumn
buildModel: buildModel
runAutoML: runAutoML
getGrids: getGrids
getLeaderboard: getLeaderboard
getModels: getModels
getModel: getModel
getGrid: getGrid
deleteModels: deleteModels
deleteModel: deleteModel
importModel: importModel
exportModel: exportModel
predict: predict
getPrediction: getPrediction
getPredictions: getPredictions
getCloud: getCloud
getTimeline: getTimeline
getProfile: getProfile
getStackTrace: getStackTrace
getLogFile: getLogFile
testNetwork: testNetwork
deleteAll: deleteAll
if _.onSparklingWater
routinesOnSw =
getDataFrames: getDataFrames
getRDDs: getRDDs
getScalaIntp: getScalaIntp
runScalaCode: runScalaCode
asH2OFrameFromRDD: asH2OFrameFromRDD
asH2OFrameFromDF: asH2OFrameFromDF
asDataFrame: asDataFrame
getScalaCodeExecutionResult: getScalaCodeExecutionResult
for attrname of routinesOnSw
routines[attrname] = routinesOnSw[attrname]
routines
| 117369 | Plotly = require('plotly.js')
{ flatten, compact, keyBy, findIndex, isFunction, isArray,
map, uniq, head, keys, range, escape, sortBy, some,
tail, concat, values } = require('lodash')
{ isObject, isNumber } = require('../../core/modules/prelude')
{ words, typeOf, stringify } = require('../../core/modules/prelude')
{ act, react, lift, link, merge, isSignal, signal, signals } = require("../../core/modules/dataflow")
{ TString, TNumber } = require('../../core/modules/types')
async = require('../../core/modules/async')
html = require('../../core/modules/html')
FlowError = require('../../core/modules/flow-error')
objectBrowser = require('../../core/components/object-browser')
util = require('../../core/modules/util')
gui = require('../../core/modules/gui')
form = require('../../core/components/form')
h2o = require('./h2o')
lightning = require('../../core/modules/lightning')
_assistance =
importFiles:
description: 'Import file(s) into H<sub>2</sub>O'
icon: 'files-o'
importSqlTable:
description: 'Import SQL table into H<sub>2</sub>O'
icon: 'table'
getFrames:
description: 'Get a list of frames in H<sub>2</sub>O'
icon: 'table'
splitFrame:
description: 'Split a frame into two or more frames'
icon: 'scissors'
mergeFrames:
description: 'Merge two frames into one'
icon: 'link'
getModels:
description: 'Get a list of models in H<sub>2</sub>O'
icon: 'cubes'
getGrids:
description: 'Get a list of grid search results in H<sub>2</sub>O'
icon: 'th'
getPredictions:
description: 'Get a list of predictions in H<sub>2</sub>O'
icon: 'bolt'
getJobs:
description: 'Get a list of jobs running in H<sub>2</sub>O'
icon: 'tasks'
runAutoML:
description: 'Automatically train and tune many models'
icon: 'sitemap'
buildModel:
description: 'Build a model'
icon: 'cube'
importModel:
description: 'Import a saved model'
icon: 'cube'
predict:
description: 'Make a prediction'
icon: 'bolt'
parseNumbers = (source) ->
target = new Array source.length
for value, i in source
target[i] = if value is 'NaN'
undefined
else if value is 'Infinity'
Number.POSITIVE_INFINITY #TODO handle formatting
else if value is '-Infinity'
Number.NEGATIVE_INFINITY #TODO handle formatting
else
value
target
convertColumnToVector = (column, data) ->
switch column.type
when 'byte', 'short', 'int', 'integer', 'long'
lightning.createVector column.name, TNumber, parseNumbers data
when 'float', 'double'
lightning.createVector column.name, TNumber, (parseNumbers data), format4f
when 'string'
lightning.createFactor column.name, TString, data
when 'matrix'
lightning.createList column.name, data, formatConfusionMatrix
else
lightning.createList column.name, data
convertTableToFrame = (table, tableName, metadata) ->
#TODO handle format strings and description
vectors = for column, i in table.columns
convertColumnToVector column, table.data[i]
lightning.createDataFrame tableName, vectors, (range table.rowcount), null, metadata
getTwoDimData = (table, columnName) ->
columnIndex = findIndex table.columns, (column) -> column.name is columnName
if columnIndex >= 0
table.data[columnIndex]
else
undefined
format4f = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(4).replace(/\.0+$/, '.0')
else
number
format6fi = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(6).replace(/\.0+$/, '')
else
number
combineTables = (tables) ->
leader = head tables
rowCount = 0
columnCount = leader.data.length
data = new Array columnCount
for table in tables
rowCount += table.rowcount
for i in [0 ... columnCount]
data[i] = columnData = new Array rowCount
index = 0
for table in tables
for element in table.data[i]
columnData[index++] = element
name: leader.name
columns: leader.columns
data: data
rowcount: rowCount
createArrays = (count, length) ->
for i in [0 ... count]
new Array length
parseNaNs = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element is 'NaN' then undefined else element
target
parseNulls = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element? then element else undefined
target
parseAndFormatArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if isNumber element
format6fi element
else
element
else
undefined
target
parseAndFormatObjectArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if element.__meta?.schema_type is 'Key<Model>'
"<a href='#' data-type='model' data-key=#{stringify element.name}>#{escape element.name}</a>"
else if element.__meta?.schema_type is 'Key<Frame>'
"<a href='#' data-type='frame' data-key=#{stringify element.name}>#{escape element.name}</a>"
else
element
else
undefined
target
repeatValues = (count, value) ->
target = new Array count
for i in [0 ... count]
target[i] = value
target
concatArrays = (arrays) ->
switch arrays.length
when 0
[]
when 1
head arrays
else
a = head arrays
a.concat.apply a, tail arrays
computeTruePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
tp / (tp + fn)
computeFalsePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
fp / (fp + tn)
formatConfusionMatrix = (cm) ->
[[tn, fp], [fn, tp]] = cm.matrix
fnr = fn / (tp + fn)
fpr = fp / (fp + tn)
domain = cm.domain
[ table, tbody, tr, strong, normal, yellow ] = html.template 'table.flow-matrix', 'tbody', 'tr', 'td.strong.flow-center', 'td', 'td.bg-yellow'
table [
tbody [
tr [
strong 'Actual/Predicted'
strong domain[0]
strong domain[1]
strong 'Error'
strong 'Rate'
]
tr [
strong domain[0]
yellow tn
normal fp
normal format4f fpr
normal fp + ' / ' + (fp + tn)
]
tr [
strong domain[1]
normal fn
yellow tp
normal format4f fnr
normal fn + ' / ' + (tp + fn)
]
tr [
strong 'Total'
strong tn + fn
strong tp + fp
strong format4f (fn + fp) / (fp + tn + tp + fn)
strong (fn + fp) + ' / ' + (fp + tn + tp + fn)
]
]
]
formulateGetPredictionsOrigin = (opts) ->
if isArray opts
sanitizedOpts = for opt in opts
sanitizedOpt = {}
sanitizedOpt.model = opt.model if opt.model
sanitizedOpt.frame = opt.frame if opt.frame
sanitizedOpt
"getPredictions #{stringify sanitizedOpts}"
else
{ model: modelKey, frame: frameKey } = opts
if modelKey and frameKey
"getPredictions model: #{stringify modelKey}, frame: #{stringify frameKey}"
else if modelKey
"getPredictions model: #{stringify modelKey}"
else if frameKey
"getPredictions frame: #{stringify frameKey}"
else
"getPredictions()"
exports.init = (_) ->
#TODO move these into async
_fork = (f, args...) -> async.fork f, args
_join = (args..., go) -> async.join args, async.applicate go
_call = (go, args...) -> async.join args, async.applicate go
_apply = (go, args) -> async.join args, go
_isFuture = async.isFuture
_async = async.async
_get = async.get
#XXX obsolete
proceed = (func, args, go) ->
go null, render_ {}, -> func.apply null, [_].concat args or []
proceed = (func, args, go) ->
go null, render_.apply null, [ {}, func, ].concat args or []
extendGuiForm = (f) ->
render_ f, form, f
createGui = (controls, go) ->
go null, extendGuiForm signals controls or []
gui = (controls) ->
_fork createGui, controls
gui[name] = f for name, f of gui
flow_ = (raw) ->
raw._flow_ or raw._flow_ = _cache_: {}
#XXX obsolete
render_ = (raw, render) ->
(flow_ raw).render = render
raw
render_ = (raw, render, args...) ->
(flow_ raw).render = (go) ->
# Prepend current context (_) and a continuation (go)
render.apply null, [_, go].concat args
raw
inspect_ = (raw, inspectors) ->
root = flow_ raw
root.inspect = {} unless root.inspect?
for attr, f of inspectors
root.inspect[attr] = f
raw
inspect = (a, b) ->
if arguments.length is 1
inspect$1 a
else
inspect$2 a, b
inspect$1 = (obj) ->
if _isFuture obj
_async inspect, obj
else
if inspectors = obj?._flow_?.inspect
inspections = []
for attr, f of inspectors
inspections.push inspect$2 attr, obj
render_ inspections, h2o.InspectsOutput, inspections
inspections
else
{}
ls = (obj) ->
if _isFuture obj
_async ls, obj
else
if inspectors = obj?._flow_?.inspect
keys inspectors
else
[]
inspect$2 = (attr, obj) ->
return unless attr
return _async inspect, attr, obj if _isFuture obj
return unless obj
return unless root = obj._flow_
return unless inspectors = root.inspect
return cached if cached = root._cache_[ key = "inspect_#{attr}" ]
return unless f = inspectors[attr]
return unless isFunction f
root._cache_[key] = inspection = f()
render_ inspection, h2o.InspectOutput, inspection
inspection
_plot = (render, go) ->
render (error, vis) ->
if error
go new FlowError 'Error rendering vis.', error
else
go null, vis
extendPlot = (vis) ->
render_ vis, h2o.PlotOutput, vis.element
createLightningPlot = (f, go) ->
_plot (f lightning), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plot = (f) ->
if _isFuture f
_fork proceed, h2o.PlotInput, f
else if isFunction f
_fork createLightningPlot, f
else
assist plot
createPlotlyPlot = (f, go) ->
_plot (f Plotly), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plotlyPlot = (f) ->
_fork createPlotlyPlot, f
grid = (f) ->
plot (g) -> g(
g.select()
g.from f
)
transformBinomialMetrics = (metrics) ->
if scores = metrics.thresholds_and_metric_scores
domain = metrics.domain
tps = getTwoDimData scores, 'tps'
tns = getTwoDimData scores, 'tns'
fps = getTwoDimData scores, 'fps'
fns = getTwoDimData scores, 'fns'
cms = for tp, i in tps
domain: domain
matrix: [[tns[i], fps[i]], [fns[i], tp]]
scores.columns.push
name: 'CM'
description: 'CM'
format: 'matrix' #TODO HACK
type: 'matrix'
scores.data.push cms
metrics
extendCloud = (cloud) ->
render_ cloud, h2o.CloudOutput, cloud
extendTimeline = (timeline) ->
render_ timeline, h2o.TimelineOutput, timeline
extendStackTrace = (stackTrace) ->
render_ stackTrace, h2o.StackTraceOutput, stackTrace
extendLogFile = (cloud, nodeIpPort, fileType, logFile) ->
render_ logFile, h2o.LogFileOutput, cloud, nodeIpPort, fileType, logFile
inspectNetworkTestResult = (testResult) -> ->
convertTableToFrame testResult.table, testResult.table.name,
description: testResult.table.name
origin: "testNetwork"
extendNetworkTest = (testResult) ->
inspect_ testResult,
result: inspectNetworkTestResult testResult
render_ testResult, h2o.NetworkTestOutput, testResult
extendProfile = (profile) ->
render_ profile, h2o.ProfileOutput, profile
extendFrames = (frames) ->
render_ frames, h2o.FramesOutput, frames
frames
extendSplitFrameResult = (result) ->
render_ result, h2o.SplitFrameOutput, result
result
extendMergeFramesResult = (result) ->
render_ result, h2o.MergeFramesOutput, result
result
extendPartialDependence= (result) ->
inspections = {}
for data, i in result.partial_dependence_data
origin = "getPartialDependence #{stringify result.destination_key}"
inspections["plot#{i+1}"] = inspectTwoDimTable_ origin, "plot#{i+1}", data
inspect_ result, inspections
render_ result, h2o.PartialDependenceOutput, result
result
# inspectOutputsAcrossModels = (modelCategory, models) -> ->
# switch modelCategory
# when 'Binomial'
# when 'Multinomial'
# when 'Regression'
getModelParameterValue = (type, value) ->
switch type
when 'Key<Frame>', 'Key<Model>'
if value? then value.name else undefined
when 'VecSpecifier'
if value? then value.column_name else undefined
else
if value? then value else undefined
inspectParametersAcrossModels = (models) -> ->
leader = head models
vectors = for parameter, i in leader.parameters
data = for model in models
getModelParameterValue parameter.type, model.parameters[i].actual_value
switch parameter.type
when 'enum', 'Frame', 'string'
lightning.createFactor parameter.label, TString, data
when 'byte', 'short', 'int', 'long', 'float', 'double'
lightning.createVector parameter.label, TNumber, data
when 'string[]', 'byte[]', 'short[]', 'int[]', 'long[]', 'float[]', 'double[]'
lightning.createList parameter.label, data, (a) -> if a then a else undefined
when 'boolean'
lightning.createList parameter.label, data, (a) -> if a then 'true' else 'false'
else
lightning.createList parameter.label, data
modelKeys = (model.model_id.name for model in models)
lightning.createDataFrame 'parameters', vectors, (range models.length), null,
description: "Parameters for models #{modelKeys.join ', '}"
origin: "getModels #{stringify modelKeys}"
inspectModelParameters = (model) -> ->
parameters = model.parameters
attrs = [
'label'
'type'
'level'
'actual_value'
'default_value'
]
vectors = for attr in attrs
data = new Array parameters.length
for parameter, i in parameters
data[i] = if attr is 'actual_value'
getModelParameterValue parameter.type, parameter[attr]
else
parameter[attr]
lightning.createList attr, data
lightning.createDataFrame 'parameters', vectors, (range parameters.length), null,
description: "Parameters for model '#{model.model_id.name}'" #TODO frame model_id
origin: "getModel #{stringify model.model_id.name}"
extendJob = (job) ->
render_ job, h2o.JobOutput, job
extendJobs = (jobs) ->
for job in jobs
extendJob job
render_ jobs, h2o.JobsOutput, jobs
extendCancelJob = (cancellation) ->
render_ cancellation, h2o.CancelJobOutput, cancellation
extendDeletedKeys = (keys) ->
render_ keys, h2o.DeleteObjectsOutput, keys
inspectTwoDimTable_ = (origin, tableName, table) -> ->
convertTableToFrame table, tableName,
description: table.description or ''
origin: origin
inspectRawArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatArray array], (range array.length), null,
description: ''
origin: origin
inspectObjectArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatObjectArray array], (range array.length), null,
description: ''
origin: origin
inspectRawObject_ = (name, origin, description, obj) -> ->
vectors = for k, v of obj
lightning.createList k, [ if v is null then undefined else if isNumber v then format6fi v else v ]
lightning.createDataFrame name, vectors, (range 1), null,
description: ''
origin: origin
_globalHacks =
fields: 'reproducibility_information_table'
_schemaHacks =
KMeansOutput:
fields: 'names domains help'
GBMOutput:
fields: 'names domains help'
GLMOutput:
fields: 'names domains help'
DRFOutput:
fields: 'names domains help'
DeepLearningModelOutput:
fields: 'names domains help'
NaiveBayesOutput:
fields: 'names domains help pcond'
PCAOutput:
fields: 'names domains help'
ModelMetricsBinomialGLM:
fields: null
transform: transformBinomialMetrics
ModelMetricsBinomial:
fields: null
transform: transformBinomialMetrics
ModelMetricsMultinomialGLM:
fields: null
ModelMetricsMultinomial:
fields: null
ModelMetricsRegressionGLM:
fields: null
ModelMetricsRegression:
fields: null
ModelMetricsClustering:
fields: null
ModelMetricsAutoEncoder:
fields: null
ConfusionMatrix:
fields: null
blacklistedAttributesBySchema = do ->
dicts = {}
for schema, attrs of _schemaHacks
dicts[schema] = dict = __meta: yes
if attrs.fields
for field in words attrs.fields
dict[field] = yes
dicts
blacklistedAttributesSchemaIndependent = do ->
dict = {}
for attrs of _globalHacks
if attrs = 'fields'
for field in words _globalHacks[attrs]
dict[field] = yes
dict
schemaTransforms = do ->
transforms = {}
for schema, attrs of _schemaHacks
if transform = attrs.transform
transforms[schema] = transform
transforms
inspectObject = (inspections, name, origin, obj) ->
blacklistedAttributes = blacklistedAttributesSchemaIndependent
schemaType = obj.__meta?.schema_type
if schemaType
if attrs = blacklistedAttributesBySchema[schemaType]
for key, value of attrs
blacklistedAttributes[key] = value
obj = transform obj if transform = schemaTransforms[schemaType]
record = {}
inspections[name] = inspectRawObject_ name, origin, name, record
for k, v of obj when not blacklistedAttributes[k]
if v is null
record[k] = null
else
if v.__meta?.schema_type is 'TwoDimTable'
inspections["#{name} - #{v.name}"] = inspectTwoDimTable_ origin, "#{name} - #{v.name}", v
else
if isArray v
if k is 'cross_validation_models' or k is 'cross_validation_predictions' or (name is 'output' and (k is 'weights' or k is 'biases')) # megahack
inspections[k] = inspectObjectArray_ k, origin, k, v
else
inspections[k] = inspectRawArray_ k, origin, k, v
else if isObject v
if meta = v.__meta
if meta.schema_type is 'Key<Frame>'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Key<Model>'
record[k] = "<a href='#' data-type='model' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Frame'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.frame_id.name}>#{escape v.frame_id.name}</a>"
else
inspectObject inspections, "#{name} - #{k}", origin, v
else
console.log "WARNING: dropping [#{k}] from inspection:", v
else
record[k] = if isNumber v then format6fi v else v
return
extendModel = (model) ->
extend = (model) ->
inspections = {}
inspections.parameters = inspectModelParameters model
origin = "getModel #{stringify model.model_id.name}"
inspectObject inspections, 'output', origin, model.output
# Obviously, an array of 2d tables calls for a megahack.
if model.__meta.schema_type is 'NaiveBayesModel'
if isArray model.output.pcond
for table in model.output.pcond
tableName = "output - pcond - #{table.name}"
inspections[tableName] = inspectTwoDimTable_ origin, tableName, table
inspect_ model, inspections
model
refresh = (go) ->
_.requestModel model.model_id.name, (error, model) ->
if error then go error else go null, extend model
extend model
render_ model, h2o.ModelOutput, model, refresh
extendGrid = (grid, opts) ->
origin = "getGrid #{stringify grid.grid_id.name}"
origin += ", #{stringify opts}" if opts
inspections =
summary: inspectTwoDimTable_ origin, "summary", grid.summary_table
scoring_history: inspectTwoDimTable_ origin, "scoring_history", grid.scoring_history
inspect_ grid, inspections
render_ grid, h2o.GridOutput, grid
extendGrids = (grids) ->
render_ grids, h2o.GridsOutput, grids
extendLeaderboard = (result) ->
render_ result, h2o.LeaderboardOutput, result
extendModels = (models) ->
inspections = {}
algos = uniq (model.algo for model in models)
if algos.length is 1
inspections.parameters = inspectParametersAcrossModels models
# modelCategories = uniq (model.output.model_category for model in models)
# TODO implement model comparision after 2d table cleanup for model metrics
#if modelCategories.length is 1
# inspections.outputs = inspectOutputsAcrossModels (head modelCategories), models
inspect_ models, inspections
render_ models, h2o.ModelsOutput, models
read = (value) -> if value is 'NaN' then null else value
extendPredictions = (opts, predictions) ->
render_ predictions, h2o.PredictsOutput, opts, predictions
predictions
extendPrediction = (result) ->
modelKey = result.model.name
frameKey = result.frame?.name
prediction = head result.model_metrics
predictionFrame = if result.predictions_frame is null then result.frame? else result.predictions_frame
inspections = {}
if prediction
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", prediction
else
prediction = {}
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", { prediction_frame: predictionFrame }
inspect_ prediction, inspections
render_ prediction, h2o.PredictOutput, modelKey, frameKey, predictionFrame, prediction
inspectFrameColumns = (tableLabel, frameKey, frame, frameColumns) -> ->
attrs = [
'label'
'type'
'missing_count|Missing'
'zero_count|Zeros'
'positive_infinity_count|+Inf'
'negative_infinity_count|-Inf'
'min'
'max'
'mean'
'sigma'
'cardinality'
]
toColumnSummaryLink = (label) ->
"<a href='#' data-type='summary-link' data-key=#{stringify label}>#{escape label}</a>"
toConversionLink = (value) ->
[ type, label ] = value.split '\0'
switch type
when 'enum'
"<a href='#' data-type='as-numeric-link' data-key=#{stringify label}>Convert to numeric</a>"
when 'int', 'string'
"<a href='#' data-type='as-factor-link' data-key=#{stringify label}>Convert to enum</a>"
else
undefined
vectors = for attr in attrs
[ name, title ] = attr.split '|'
title = title ? name
switch name
when 'min'
lightning.createVector title, TNumber, (head column.mins for column in frameColumns), format4f
when 'max'
lightning.createVector title, TNumber, (head column.maxs for column in frameColumns), format4f
when 'cardinality'
lightning.createVector title, TNumber, ((if column.type is 'enum' then column.domain_cardinality else undefined) for column in frameColumns)
when 'label'
lightning.createFactor title, TString, (column[name] for column in frameColumns), null, toColumnSummaryLink
when 'type'
lightning.createFactor title, TString, (column[name] for column in frameColumns)
when 'mean', 'sigma'
lightning.createVector title, TNumber, (column[name] for column in frameColumns), format4f
else
lightning.createVector title, TNumber, (column[name] for column in frameColumns)
[ labelVector, typeVector ] = vectors
actionsData = for i in [0 ... frameColumns.length]
"#{typeVector.valueAt i}\0#{labelVector.valueAt i}"
vectors.push lightning.createFactor 'Actions', TString, actionsData, null, toConversionLink
lightning.createDataFrame tableLabel, vectors, (range frameColumns.length), null,
description: "A list of #{tableLabel} in the H2O Frame."
origin: "getFrameSummary #{stringify frameKey}"
plot: "plot inspect '#{tableLabel}', getFrameSummary #{stringify frameKey}"
inspectFrameData = (frameKey, frame) -> ->
frameColumns = frame.columns
vectors = for column in frameColumns
#XXX format functions
switch column.type
when 'int', 'real'
lightning.createVector column.label, TNumber, (parseNaNs column.data), format4f
when 'enum'
domain = column.domain
lightning.createFactor column.label, TString, ((if index? then domain[index] else undefined) for index in column.data)
when 'time'
lightning.createVector column.label, TNumber, parseNaNs column.data
when 'string', 'uuid'
lightning.createList column.label, parseNulls column.string_data
else
lightning.createList column.label, parseNulls column.data
vectors.unshift lightning.createVector 'Row', TNumber, (rowIndex + 1 for rowIndex in [frame.row_offset ... frame.row_count])
lightning.createDataFrame 'data', vectors, (range frame.row_count - frame.row_offset), null,
description: 'A partial list of rows in the H2O Frame.'
origin: "getFrameData #{stringify frameKey}"
extendFrameData = (frameKey, frame) ->
inspections =
data: inspectFrameData frameKey, frame
origin = "getFrameData #{stringify frameKey}"
inspect_ frame, inspections
render_ frame, h2o.FrameDataOutput, frame
extendFrame = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
data: inspectFrameData frameKey, frame
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendFrameSummary = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendColumnSummary = (frameKey, frame, columnName) ->
column = head frame.columns
rowCount = frame.rows
inspectPercentiles = ->
vectors = [
lightning.createVector 'percentile', TNumber, frame.default_percentiles
lightning.createVector 'value', TNumber, column.percentiles
]
lightning.createDataFrame 'percentiles', vectors, (range frame.default_percentiles.length), null,
description: "Percentiles for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDistribution = ->
minBinCount = 32
{ histogram_base:base, histogram_stride:stride, histogram_bins:bins } = column
width = Math.ceil bins.length / minBinCount
interval = stride * width
rows = []
if width > 0
binCount = minBinCount + if bins.length % width > 0 then 1 else 0
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for i in [0 ... binCount]
m = i * width
n = m + width
count = 0
for binIndex in [m ... n] when binIndex < bins.length
count += bins[binIndex]
intervalData[i] = base + i * interval
widthData[i] = interval
countData[i] = count
else
binCount = bins.length
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for count, i in bins
intervalData[i] = base + i * stride
widthData[i] = stride
countData[i] = count
# Trim off empty bins from the end
for i in [binCount - 1 .. 0]
if countData[i] isnt 0
binCount = i + 1
intervalData = intervalData.slice 0, binCount
widthData = widthData.slice 0, binCount
countData = countData.slice 0, binCount
break
vectors = [
lightning.createFactor 'interval', TString, intervalData
lightning.createVector 'width', TNumber, widthData
lightning.createVector 'count', TNumber, countData
]
lightning.createDataFrame 'distribution', vectors, (range binCount), null,
description: "Distribution for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'distribution', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectCharacteristics = ->
{ missing_count, zero_count, positive_infinity_count, negative_infinity_count } = column
other = rowCount - missing_count - zero_count - positive_infinity_count - negative_infinity_count
characteristicData = [ 'Missing', '-Inf', 'Zero', '+Inf', 'Other' ]
countData = [ missing_count, negative_infinity_count, zero_count, positive_infinity_count, other ]
percentData = for count in countData
100 * count / rowCount
vectors = [
lightning.createFactor 'characteristic', TString, characteristicData
lightning.createVector 'count', TNumber, countData
lightning.createVector 'percent', TNumber, percentData
]
lightning.createDataFrame 'characteristics', vectors, (range characteristicData.length), null,
description: "Characteristics for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'characteristics', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectSummary = ->
defaultPercentiles = frame.default_percentiles
percentiles = column.percentiles
mean = column.mean
q1 = percentiles[defaultPercentiles.indexOf 0.25]
q2 = percentiles[defaultPercentiles.indexOf 0.5]
q3 = percentiles[defaultPercentiles.indexOf 0.75]
outliers = uniq concat column.mins, column.maxs
minimum = head column.mins
maximum = head column.maxs
vectors = [
lightning.createFactor 'column', TString, [ columnName ]
lightning.createVector 'mean', TNumber, [ mean ]
lightning.createVector 'q1', TNumber, [ q1 ]
lightning.createVector 'q2', TNumber, [ q2 ]
lightning.createVector 'q3', TNumber, [ q3 ]
lightning.createVector 'min', TNumber, [ minimum ]
lightning.createVector 'max', TNumber, [ maximum ]
]
lightning.createDataFrame 'summary', vectors, (range 1), null,
description: "Summary for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'summary', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDomain = ->
levels = map column.histogram_bins, (count, index) -> count: count, index: index
#TODO sort table in-place when sorting is implemented
sortedLevels = sortBy levels, (level) -> -level.count
[ labels, counts, percents ] = createArrays 3, sortedLevels.length
for level, i in sortedLevels
labels[i] = column.domain[level.index]
counts[i] = level.count
percents[i] = 100 * level.count / rowCount
vectors = [
lightning.createFactor 'label', TString, labels
lightning.createVector 'count', TNumber, counts
lightning.createVector 'percent', TNumber, percents
]
lightning.createDataFrame 'domain', vectors, (range sortedLevels.length), null,
description: "Domain for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'domain', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspections =
characteristics: inspectCharacteristics
switch column.type
when 'int', 'real'
# Skip for columns with all NAs
if column.histogram_bins.length
inspections.distribution = inspectDistribution
# Skip for columns with all NAs
unless (some column.percentiles, (a) -> a is 'NaN')
inspections.summary = inspectSummary
inspections.percentiles = inspectPercentiles
when 'enum'
inspections.domain = inspectDomain
inspect_ frame, inspections
render_ frame, h2o.ColumnSummaryOutput, frameKey, frame, columnName
requestFrame = (frameKey, go) ->
_.requestFrameSlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrame frameKey, frame
requestFrameData = (frameKey, searchTerm, offset, count, go) ->
_.requestFrameSlice frameKey, searchTerm, offset, count, (error, frame) ->
if error
go error
else
go null, extendFrameData frameKey, frame
requestFrameSummarySlice = (frameKey, searchTerm, offset, length, go) ->
_.requestFrameSummarySlice frameKey, searchTerm, offset, length, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestFrameSummary = (frameKey, go) ->
_.requestFrameSummarySlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestColumnSummary = (frameKey, columnName, go) ->
_.requestColumnSummary frameKey, columnName, (error, frame) ->
if error
go error
else
go null, extendColumnSummary frameKey, frame, columnName
requestFrames = (go) ->
_.requestFrames (error, frames) ->
if error
go error
else
go null, extendFrames frames
requestCreateFrame = (opts, go) ->
_.requestCreateFrame opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependence = (opts, go) ->
_.requestPartialDependence opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependenceData = (key, go) ->
_.requestPartialDependenceData key, (error, result) ->
if error
go error
else
go null, extendPartialDependence result
computeSplits = (ratios, keys) ->
parts = []
sum = 0
for key, i in keys.slice(0, ratios.length)
sum += ratio = ratios[i]
parts.push
key: key
ratio: ratio
parts.push
key: keys[keys.length - 1]
ratio: 1 - sum
splits = []
sum = 0
for part in parts
splits.push
min: sum
max: sum + part.ratio
key: part.key
sum += part.ratio
splits
requestBindFrames = (key, sourceKeys, go) ->
_.requestExec "(assign #{key} (cbind #{sourceKeys.join ' '}))", (error, result) ->
if error
go error
else
go null, extendBindFrames key, result
requestSplitFrame = (frameKey, splitRatios, splitKeys, seed, go) ->
if splitRatios.length is splitKeys.length - 1
splits = computeSplits splitRatios, splitKeys
randomVecKey = <KEY>()
statements = []
statements.push "(tmp= #{randomVecKey} (h2o.runif #{frameKey} #{seed}))"
for part, i in splits
g = if i isnt 0 then "(> #{randomVecKey} #{part.min})" else null
l = if i isnt splits.length - 1 then "(<= #{randomVecKey} #{part.max})" else null
sliceExpr = if g and l
"(& #{g} #{l})"
else if l
l
else
g
statements.push "(assign #{part.key} (rows #{frameKey} #{sliceExpr}))"
statements.push "(rm #{randomVecKey})"
_.requestExec "(, #{statements.join ' '})", (error, result) ->
if error
go error
else
go null, extendSplitFrameResult
keys: splitKeys
ratios: splitRatios
else
go new FlowError 'The number of split ratios should be one less than the number of split keys'
requestMergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows, go) ->
lr = if includeAllLeftRows then 'TRUE' else 'FALSE'
rr = if includeAllRightRows then 'TRUE' else 'FALSE'
statement = "(assign #{destinationKey} (merge #{leftFrameKey} #{rightFrameKey} #{lr} #{rr} #{leftColumnIndex} #{rightColumnIndex} \"radix\"))"
_.requestExec statement, (error, result) ->
if error
go error
else
go null, extendMergeFramesResult
key: destinationKey
createFrame = (opts) ->
if opts
_fork requestCreateFrame, opts
else
assist createFrame
splitFrame = (frameKey, splitRatios, splitKeys, seed=-1) ->
if frameKey and splitRatios and splitKeys
_fork requestSplitFrame, frameKey, splitRatios, splitKeys, seed
else
assist splitFrame
mergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows) ->
if destinationKey and leftFrameKey and rightFrameKey
_fork requestMergeFrames, destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows
else
assist mergeFrames
# define the function that is called when
# the Partial Dependence plot input form
# is submitted
buildPartialDependence = (opts) ->
if opts
_fork requestPartialDependence, opts
else
# specify function to call if user
# provides malformed input
assist buildPartialDependence
getPartialDependence = (destinationKey) ->
if destinationKey
_fork requestPartialDependenceData, destinationKey
else
assist getPartialDependence
getFrames = ->
_fork requestFrames
getFrame = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrame, frameKey
else
assist getFrame
bindFrames = (key, sourceKeys) ->
_fork requestBindFrames, key, sourceKeys
getFrameSummary = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameSummary, frameKey
else
assist getFrameSummary
getFrameData = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameData, frameKey, undefined, 0, 20
else
assist getFrameSummary
requestDeleteFrame = (frameKey, go) ->
_.requestDeleteFrame frameKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ frameKey ]
deleteFrame = (frameKey) ->
if frameKey
_fork requestDeleteFrame, frameKey
else
assist deleteFrame
extendExportFrame = (result) ->
render_ result, h2o.ExportFrameOutput, result
extendBindFrames = (key, result) ->
render_ result, h2o.BindFramesOutput, key, result
requestExportFrame = (frameKey, path, opts, go) ->
_.requestExportFrame frameKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error
go error
else
_.requestJob result.job.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
exportFrame = (frameKey, path, opts={}) ->
if frameKey and path
_fork requestExportFrame, frameKey, path, opts
else
assist exportFrame, frameKey, path, opts
requestDeleteFrames = (frameKeys, go) ->
futures = map frameKeys, (frameKey) ->
_fork _.requestDeleteFrame, frameKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys frameKeys
deleteFrames = (frameKeys) ->
switch frameKeys.length
when 0
assist deleteFrames
when 1
deleteFrame head frameKeys
else
_fork requestDeleteFrames, frameKeys
getColumnSummary = (frameKey, columnName) ->
_fork requestColumnSummary, frameKey, columnName
requestModels = (go) ->
_.requestModels (error, models) ->
if error then go error else go null, extendModels models
requestModelsByKeys = (modelKeys, go) ->
futures = map modelKeys, (key) ->
_fork _.requestModel, key
async.join futures, (error, models) ->
if error then go error else go null, extendModels models
getModels = (modelKeys) ->
if isArray modelKeys
if modelKeys.length
_fork requestModelsByKeys, modelKeys
else
_fork requestModels
else
_fork requestModels
requestGrids = (go) ->
_.requestGrids (error, grids) ->
if error then go error else go null, extendGrids grids
getGrids = ->
_fork requestGrids
requestLeaderboard = (key, go) ->
_.requestLeaderboard key, (error, leaderboard) ->
if error then go error else go null, extendLeaderboard leaderboard
getLeaderboard = (key) ->
_fork requestLeaderboard, key
requestModel = (modelKey, go) ->
_.requestModel modelKey, (error, model) ->
if error then go error else go null, extendModel model
getModel = (modelKey) ->
switch typeOf modelKey
when 'String'
_fork requestModel, modelKey
else
assist getModel
requestGrid = (gridKey, opts, go) ->
_.requestGrid gridKey, opts, (error, grid) ->
if error then go error else go null, extendGrid grid, opts
getGrid = (gridKey, opts) ->
switch typeOf gridKey
when 'String'
_fork requestGrid, gridKey, opts
else
assist getGrid
findColumnIndexByColumnLabel = (frame, columnLabel) ->
for column, i in frame.columns when column.label is columnLabel
return i
throw new FlowError "Column [#{columnLabel}] not found in frame"
findColumnIndicesByColumnLabels = (frame, columnLabels) ->
for columnLabel in columnLabels
findColumnIndexByColumnLabel frame, columnLabel
requestImputeColumn = (opts, go) ->
{ frame, column, method, combineMethod, groupByColumns } = opts
combineMethod = combineMethod ? 'interpolate'
_.requestFrameSummaryWithoutData frame, (error, result) ->
if error
go error
else
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
if groupByColumns and groupByColumns.length
try
groupByColumnIndices = findColumnIndicesByColumnLabels result, groupByColumns
catch columnIndicesError
return go columnIndicesError
else
groupByColumnIndices = null
groupByArg = if groupByColumnIndices
"[#{groupByColumnIndices.join ' '}]"
else
"[]"
_.requestExec "(h2o.impute #{frame} #{columnIndex} #{JSON.stringify method} #{JSON.stringify combineMethod} #{groupByArg} _ _)", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
requestChangeColumnType = (opts, go) ->
{ frame, column, type } = opts
method = if type is 'enum' then 'as.factor' else 'as.numeric'
_.requestFrameSummaryWithoutData frame, (error, result) ->
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
_.requestExec "(assign #{frame} (:= #{frame} (#{method} (cols #{frame} #{columnIndex})) #{columnIndex} [0:#{result.rows}]))", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
imputeColumn = (opts) ->
if opts and opts.frame and opts.column and opts.method
_fork requestImputeColumn, opts
else
assist imputeColumn, opts
changeColumnType = (opts) ->
if opts and opts.frame and opts.column and opts.type
_fork requestChangeColumnType, opts
else
assist changeColumnType, opts
requestDeleteModel = (modelKey, go) ->
_.requestDeleteModel modelKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ modelKey ]
deleteModel = (modelKey) ->
if modelKey
_fork requestDeleteModel, modelKey
else
assist deleteModel
extendImportModel = (result) ->
render_ result, h2o.ImportModelOutput, result
requestImportModel = (path, opts, go) ->
_.requestImportModel path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendImportModel result
importModel = (path, opts) ->
if path and path.length
_fork requestImportModel, path, opts
else
assist importModel, path, opts
extendExportModel = (result) ->
render_ result, h2o.ExportModelOutput, result
requestExportModel = (modelKey, path, opts, go) ->
_.requestExportModel opts.format, modelKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendExportModel result
exportModel = (modelKey, path, opts) ->
if modelKey and path
_fork requestExportModel, modelKey, path, opts
else
assist exportModel, modelKey, path, opts
requestDeleteModels = (modelKeys, go) ->
futures = map modelKeys, (modelKey) ->
_fork _.requestDeleteModel, modelKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys modelKeys
deleteModels = (modelKeys) ->
switch modelKeys.length
when 0
assist deleteModels
when 1
deleteModel head modelKeys
else
_fork requestDeleteModels, modelKeys
requestJob = (key, go) ->
_.requestJob key, (error, job) ->
if error
go error
else
go null, extendJob job
requestJobs = (go) ->
_.requestJobs (error, jobs) ->
if error
go error
else
go null, extendJobs jobs
getJobs = ->
_fork requestJobs
getJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestJob, arg
when 'Object'
if arg.key?
getJob arg.key
else
assist getJob
else
assist getJob
requestCancelJob = (key, go) ->
_.requestCancelJob key, (error) ->
if error
go error
else
go null, extendCancelJob {}
cancelJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestCancelJob, arg
else
assist cancelJob
extendImportResults = (importResults) ->
render_ importResults, h2o.ImportFilesOutput, importResults
requestImportFiles = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
go null, extendImportResults importResults
importFiles = (paths) ->
switch typeOf paths
when 'Array'
_fork requestImportFiles, paths
else
assist importFiles
extendImportSqlResults = (importResults) ->
render_ importResults, h2o.ImportSqlTableOutput, importResults
requestImportSqlTable = (arg, go) ->
_.requestImportSqlTable arg, (error, importResults) ->
if error
go error
else
go null, extendImportSqlResults importResults
importSqlTable = (arg) ->
switch typeOf arg
when 'Object'
_fork requestImportSqlTable, arg
else
assist importSqlTable
importBqTable = ->
assist importBqTable
extendParseSetupResults = (args, parseSetupResults) ->
render_ parseSetupResults, h2o.SetupParseOutput, args, parseSetupResults
requestImportAndParseSetup = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { paths: paths }, parseSetupResults
requestParseSetup = (sourceKeys, go) ->
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { source_frames: sourceKeys }, parseSetupResults
setupParse = (args) ->
if args.paths and isArray args.paths
_fork requestImportAndParseSetup, args.paths
else if args.source_frames and isArray args.source_frames
_fork requestParseSetup, args.source_frames
else
assist setupParse
extendParseResult = (parseResult) ->
render_ parseResult, h2o.JobOutput, parseResult.job
requestImportAndParseFiles = (paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
requestParseFiles = (sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
parseFiles = (opts) -> #XXX review args
#XXX validation
destinationKey = opts.destination_frame
parseType = opts.parse_type
separator = opts.separator
columnCount = opts.number_columns
useSingleQuotes = opts.single_quotes
columnNames = opts.column_names
columnTypes = opts.column_types
deleteOnDone = opts.delete_on_done
checkHeader = opts.check_header
chunkSize = opts.chunk_size
if opts.paths
_fork requestImportAndParseFiles, opts.paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
else
_fork requestParseFiles, opts.source_frames, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
requestModelBuild = (algo, opts, go) ->
_.requestModelBuild algo, opts, (error, result) ->
if error
go error
else
if result.error_count > 0
messages = (validation.message for validation in result.messages)
go new FlowError "Model build failure: #{messages.join '; '}"
else
go null, extendJob result.job
requestAutoMLBuild = (opts , go) ->
_.requestAutoMLBuild opts, (error, result) ->
if error
go error
else
go null, extendJob result.job
runAutoML = (opts, action) ->
if action is 'exec'
_fork requestAutoMLBuild, opts
else
assist runAutoML, opts
buildModel = (algo, opts) ->
if algo and opts and keys(opts).length > 1
_fork requestModelBuild, algo, opts
else
assist buildModel, algo, opts
unwrapPrediction = (go) ->
(error, result) ->
if error
go error
else
go null, extendPrediction result
requestPredict = (destinationKey, modelKey, frameKey, options, go) ->
_.requestPredict destinationKey, modelKey, frameKey, options, unwrapPrediction go
requestPredicts = (opts, go) ->
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey, options: options } = opt
_fork _.requestPredict, null, modelKey, frameKey, options or {}
async.join futures, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
predict = (opts={}) ->
{ predictions_frame, model, models, frame, frames, reconstruction_error, deep_features_hidden_layer, leaf_node_assignment, exemplar_index } = opts
if models or frames
unless models
if model
models = [ model ]
unless frames
if frame
frames = [ frame ]
if frames and models
combos = []
for model in models
for frame in frames
combos.push model: model, frame: frame
_fork requestPredicts, combos
else
assist predict, predictions_frame: predictions_frame, models: models, frames: frames
else
if model and frame
_fork requestPredict, predictions_frame, model, frame,
reconstruction_error: reconstruction_error
deep_features_hidden_layer: deep_features_hidden_layer
leaf_node_assignment: leaf_node_assignment
else if model and exemplar_index isnt undefined
_fork requestPredict, predictions_frame, model, null,
exemplar_index: exemplar_index
else
assist predict, predictions_frame: predictions_frame, model: model, frame: frame
requestPrediction = (modelKey, frameKey, go) ->
_.requestPrediction modelKey, frameKey, unwrapPrediction go
requestPredictions = (opts, go) ->
if isArray opts
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey } = opt
_fork _.requestPredictions, modelKey, frameKey
async.join futures, (error, predictions) ->
if error
go error
else
# De-dupe predictions
uniquePredictions = values keyBy (flatten predictions, yes), (prediction) -> prediction.model.name + prediction.frame.name
go null, extendPredictions opts, uniquePredictions
else
{ model: modelKey, frame: frameKey } = opts
_.requestPredictions modelKey, frameKey, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
getPrediction = (opts={}) ->
{ predictions_frame, model, frame } = opts
if model and frame
_fork requestPrediction, model, frame
else
assist getPrediction, predictions_frame: predictions_frame, model: model, frame: frame
getPredictions = (opts={}) ->
_fork requestPredictions, opts
requestCloud = (go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
go null, extendCloud cloud
getCloud = ->
_fork requestCloud
requestTimeline = (go) ->
_.requestTimeline (error, timeline) ->
if error
go error
else
go null, extendTimeline timeline
getTimeline = ->
_fork requestTimeline
requestStackTrace = (go) ->
_.requestStackTrace (error, stackTrace) ->
if error
go error
else
go null, extendStackTrace stackTrace
getStackTrace = ->
_fork requestStackTrace
requestLogFile = (nodeIpPort, fileType, go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
_.requestLogFile nodeIpPort, fileType, (error, logFile) ->
if error
go error
else
go null, extendLogFile cloud, nodeIpPort, fileType, logFile
getLogFile = (nodeIpPort="self", fileType='info') ->
_fork requestLogFile, nodeIpPort, fileType
requestNetworkTest = (go) ->
_.requestNetworkTest (error, result) ->
if error
go error
else
go null, extendNetworkTest result
testNetwork = ->
_fork requestNetworkTest
requestRemoveAll = (go) ->
_.requestRemoveAll (error, result) ->
if error
go error
else
go null, extendDeletedKeys []
deleteAll = ->
_fork requestRemoveAll
extendRDDs = (rdds) ->
render_ rdds, h2o.RDDsOutput, rdds
rdds
requestRDDs = (go) ->
_.requestRDDs (error, result) ->
if error
go error
else
go null, extendRDDs result.rdds
getRDDs = ->
_fork requestRDDs
extendDataFrames = (dataframes) ->
render_ dataframes, h2o.DataFramesOutput, dataframes
dataframes
requestDataFrames = (go) ->
_.requestDataFrames (error, result) ->
if error
go error
else
go null, extendDataFrames result.dataframes
getDataFrames = ->
_fork requestDataFrames
extendAsH2OFrame = (result) ->
render_ result, h2o.H2OFrameOutput, result
result
requestAsH2OFrameFromRDD = (rdd_id, name, go) ->
_.requestAsH2OFrameFromRDD rdd_id,name, (error, h2oframe_id) ->
if error
go error
else
go null, extendAsH2OFrame h2oframe_id
asH2OFrameFromRDD = (rdd_id, name=undefined) ->
_fork requestAsH2OFrameFromRDD, rdd_id, name
requestAsH2OFrameFromDF = (df_id, name, go) ->
_.requestAsH2OFrameFromDF df_id, name, (error, result) ->
if error
go error
else
go null, extendAsH2OFrame result
asH2OFrameFromDF = (df_id, name=undefined) ->
_fork requestAsH2OFrameFromDF, df_id, name
extendAsDataFrame = (result) ->
render_ result, h2o.DataFrameOutput, result
result
requestAsDataFrame = (hf_id, name, go) ->
_.requestAsDataFrame hf_id, name, (error, result) ->
if error
go error
else
go null, extendAsDataFrame result
asDataFrame = (hf_id, name=undefined) ->
_fork requestAsDataFrame, hf_id, name
getScalaCodeExecutionResult = (key) ->
switch typeOf key
when 'String'
_fork requestScalaCodeExecutionResult, key
else
assist getScalaCodeExecutionResult
requestScalaCodeExecutionResult = (key, go) ->
_.requestScalaCodeExecutionResult key, (error, result) ->
if error
go error
else
go null, extendScalaSyncCode result
requestScalaCode = (session_id, async, code, go) ->
_.requestScalaCode session_id, code, (error, result) ->
if error
go error
else
if async
go null, extendScalaAsyncCode result
else
go null, extendScalaSyncCode result
extendScalaSyncCode = (result) ->
render_ result, h2o.ScalaCodeOutput, result
result
extendScalaAsyncCode = (result) ->
render_ result, h2o.JobOutput, result.job
result
runScalaCode = (session_id, async, code) ->
_fork requestScalaCode, session_id, async, code
requestScalaIntp = (go) ->
_.requestScalaIntp (error, result) ->
if error
go error
else
go null, extendScalaIntp result
extendScalaIntp = (result) ->
render_ result, h2o.ScalaIntpOutput, result
result
getScalaIntp = ->
_fork requestScalaIntp
requestProfile = (depth, go) ->
_.requestProfile depth, (error, profile) ->
if error
go error
else
go null, extendProfile profile
getProfile = (opts) ->
opts = depth: 10 unless opts
_fork requestProfile, opts.depth
loadScript = (path, go) ->
onDone = (script, status) -> go null, script:script, status:status
onFail = (jqxhr, settings, error) -> go error #TODO use framework error
$.getScript path
.done onDone
.fail onFail
dumpFuture = (result, go) ->
result ?= {}
console.debug result
go null, render_ result, objectBrowser, 'dump', result
dump = (f) ->
if f?.isFuture
_fork dumpFuture, f
else
async.async -> f
assist = (func, args...) ->
if func is undefined
_fork proceed, h2o.Assist, [ _assistance ]
else
switch func
when importFiles
_fork proceed, h2o.ImportFilesInput, []
when importSqlTable
_fork proceed, h2o.ImportSqlTableInput, args
when importBqTable
_fork proceed, h2o.ImportBqTableInput, args
when buildModel
_fork proceed, h2o.ModelInput, args
when runAutoML
_fork proceed, h2o.AutoMLInput, args
when predict, getPrediction
_fork proceed, h2o.PredictInput, args
when createFrame
_fork proceed, h2o.CreateFrameInput, args
when splitFrame
_fork proceed, h2o.SplitFrameInput, args
when mergeFrames
_fork proceed, h2o.MergeFramesInput, args
when buildPartialDependence
_fork proceed, h2o.PartialDependenceInput, args
when exportFrame
_fork proceed, h2o.ExportFrameInput, args
when imputeColumn
_fork proceed, h2o.ImputeInput, args
when importModel
_fork proceed, h2o.ImportModelInput, args
when exportModel
_fork proceed, h2o.ExportModelInput, args
else
_fork proceed, h2o.NoAssist, []
link _.ready, ->
link _.ls, ls
link _.inspect, inspect
link _.plot, (p) -> p lightning
link _.plotlyPlot, (p) -> p Plotly
link _.grid, (frame) ->
lightning(
lightning.select()
lightning.from frame
)
link _.enumerate, (frame) ->
lightning(
lightning.select 0
lightning.from frame
)
link _.requestFrameDataE, requestFrameData
link _.requestFrameSummarySliceE, requestFrameSummarySlice
initAssistanceSparklingWater = ->
_assistance.getRDDs =
description: 'Get a list of Spark\'s RDDs'
icon: 'table'
_assistance.getDataFrames =
description: 'Get a list of Spark\'s data frames'
icon: 'table'
link _.initialized, ->
if _.onSparklingWater
initAssistanceSparklingWater()
routines =
# fork/join
fork: _fork
join: _join
call: _call
apply: _apply
isFuture: _isFuture
#
# Dataflow
signal: signal
signals: signals
isSignal: isSignal
act: act
react: react
lift: lift
merge: merge
#
# Generic
dump: dump
inspect: inspect
plot: plot
plotlyPlot: plotlyPlot
grid: grid
get: _get
#
# Meta
assist: assist
#
# GUI
gui: gui
#
# Util
loadScript: loadScript
#
# H2O
getJobs: getJobs
getJob: getJob
cancelJob: cancelJob
importFiles: importFiles
importSqlTable: importSqlTable
importBqTable: importBqTable
setupParse: setupParse
parseFiles: parseFiles
createFrame: createFrame
splitFrame: splitFrame
mergeFrames: mergeFrames
buildPartialDependence: buildPartialDependence
getPartialDependence: getPartialDependence
getFrames: getFrames
getFrame: getFrame
bindFrames: bindFrames
getFrameSummary: getFrameSummary
getFrameData: getFrameData
deleteFrames: deleteFrames
deleteFrame: deleteFrame
exportFrame: exportFrame
getColumnSummary: getColumnSummary
changeColumnType: changeColumnType
imputeColumn: imputeColumn
buildModel: buildModel
runAutoML: runAutoML
getGrids: getGrids
getLeaderboard: getLeaderboard
getModels: getModels
getModel: getModel
getGrid: getGrid
deleteModels: deleteModels
deleteModel: deleteModel
importModel: importModel
exportModel: exportModel
predict: predict
getPrediction: getPrediction
getPredictions: getPredictions
getCloud: getCloud
getTimeline: getTimeline
getProfile: getProfile
getStackTrace: getStackTrace
getLogFile: getLogFile
testNetwork: testNetwork
deleteAll: deleteAll
if _.onSparklingWater
routinesOnSw =
getDataFrames: getDataFrames
getRDDs: getRDDs
getScalaIntp: getScalaIntp
runScalaCode: runScalaCode
asH2OFrameFromRDD: asH2OFrameFromRDD
asH2OFrameFromDF: asH2OFrameFromDF
asDataFrame: asDataFrame
getScalaCodeExecutionResult: getScalaCodeExecutionResult
for attrname of routinesOnSw
routines[attrname] = routinesOnSw[attrname]
routines
| true | Plotly = require('plotly.js')
{ flatten, compact, keyBy, findIndex, isFunction, isArray,
map, uniq, head, keys, range, escape, sortBy, some,
tail, concat, values } = require('lodash')
{ isObject, isNumber } = require('../../core/modules/prelude')
{ words, typeOf, stringify } = require('../../core/modules/prelude')
{ act, react, lift, link, merge, isSignal, signal, signals } = require("../../core/modules/dataflow")
{ TString, TNumber } = require('../../core/modules/types')
async = require('../../core/modules/async')
html = require('../../core/modules/html')
FlowError = require('../../core/modules/flow-error')
objectBrowser = require('../../core/components/object-browser')
util = require('../../core/modules/util')
gui = require('../../core/modules/gui')
form = require('../../core/components/form')
h2o = require('./h2o')
lightning = require('../../core/modules/lightning')
_assistance =
importFiles:
description: 'Import file(s) into H<sub>2</sub>O'
icon: 'files-o'
importSqlTable:
description: 'Import SQL table into H<sub>2</sub>O'
icon: 'table'
getFrames:
description: 'Get a list of frames in H<sub>2</sub>O'
icon: 'table'
splitFrame:
description: 'Split a frame into two or more frames'
icon: 'scissors'
mergeFrames:
description: 'Merge two frames into one'
icon: 'link'
getModels:
description: 'Get a list of models in H<sub>2</sub>O'
icon: 'cubes'
getGrids:
description: 'Get a list of grid search results in H<sub>2</sub>O'
icon: 'th'
getPredictions:
description: 'Get a list of predictions in H<sub>2</sub>O'
icon: 'bolt'
getJobs:
description: 'Get a list of jobs running in H<sub>2</sub>O'
icon: 'tasks'
runAutoML:
description: 'Automatically train and tune many models'
icon: 'sitemap'
buildModel:
description: 'Build a model'
icon: 'cube'
importModel:
description: 'Import a saved model'
icon: 'cube'
predict:
description: 'Make a prediction'
icon: 'bolt'
parseNumbers = (source) ->
target = new Array source.length
for value, i in source
target[i] = if value is 'NaN'
undefined
else if value is 'Infinity'
Number.POSITIVE_INFINITY #TODO handle formatting
else if value is '-Infinity'
Number.NEGATIVE_INFINITY #TODO handle formatting
else
value
target
convertColumnToVector = (column, data) ->
switch column.type
when 'byte', 'short', 'int', 'integer', 'long'
lightning.createVector column.name, TNumber, parseNumbers data
when 'float', 'double'
lightning.createVector column.name, TNumber, (parseNumbers data), format4f
when 'string'
lightning.createFactor column.name, TString, data
when 'matrix'
lightning.createList column.name, data, formatConfusionMatrix
else
lightning.createList column.name, data
convertTableToFrame = (table, tableName, metadata) ->
#TODO handle format strings and description
vectors = for column, i in table.columns
convertColumnToVector column, table.data[i]
lightning.createDataFrame tableName, vectors, (range table.rowcount), null, metadata
getTwoDimData = (table, columnName) ->
columnIndex = findIndex table.columns, (column) -> column.name is columnName
if columnIndex >= 0
table.data[columnIndex]
else
undefined
format4f = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(4).replace(/\.0+$/, '.0')
else
number
format6fi = (number) ->
if number
if number is 'NaN'
undefined
else
number.toFixed(6).replace(/\.0+$/, '')
else
number
combineTables = (tables) ->
leader = head tables
rowCount = 0
columnCount = leader.data.length
data = new Array columnCount
for table in tables
rowCount += table.rowcount
for i in [0 ... columnCount]
data[i] = columnData = new Array rowCount
index = 0
for table in tables
for element in table.data[i]
columnData[index++] = element
name: leader.name
columns: leader.columns
data: data
rowcount: rowCount
createArrays = (count, length) ->
for i in [0 ... count]
new Array length
parseNaNs = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element is 'NaN' then undefined else element
target
parseNulls = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element? then element else undefined
target
parseAndFormatArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if isNumber element
format6fi element
else
element
else
undefined
target
parseAndFormatObjectArray = (source) ->
target = new Array source.length
for element, i in source
target[i] = if element?
if element.__meta?.schema_type is 'Key<Model>'
"<a href='#' data-type='model' data-key=#{stringify element.name}>#{escape element.name}</a>"
else if element.__meta?.schema_type is 'Key<Frame>'
"<a href='#' data-type='frame' data-key=#{stringify element.name}>#{escape element.name}</a>"
else
element
else
undefined
target
repeatValues = (count, value) ->
target = new Array count
for i in [0 ... count]
target[i] = value
target
concatArrays = (arrays) ->
switch arrays.length
when 0
[]
when 1
head arrays
else
a = head arrays
a.concat.apply a, tail arrays
computeTruePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
tp / (tp + fn)
computeFalsePositiveRate = (cm) ->
[[tn, fp], [fn, tp]] = cm
fp / (fp + tn)
formatConfusionMatrix = (cm) ->
[[tn, fp], [fn, tp]] = cm.matrix
fnr = fn / (tp + fn)
fpr = fp / (fp + tn)
domain = cm.domain
[ table, tbody, tr, strong, normal, yellow ] = html.template 'table.flow-matrix', 'tbody', 'tr', 'td.strong.flow-center', 'td', 'td.bg-yellow'
table [
tbody [
tr [
strong 'Actual/Predicted'
strong domain[0]
strong domain[1]
strong 'Error'
strong 'Rate'
]
tr [
strong domain[0]
yellow tn
normal fp
normal format4f fpr
normal fp + ' / ' + (fp + tn)
]
tr [
strong domain[1]
normal fn
yellow tp
normal format4f fnr
normal fn + ' / ' + (tp + fn)
]
tr [
strong 'Total'
strong tn + fn
strong tp + fp
strong format4f (fn + fp) / (fp + tn + tp + fn)
strong (fn + fp) + ' / ' + (fp + tn + tp + fn)
]
]
]
formulateGetPredictionsOrigin = (opts) ->
if isArray opts
sanitizedOpts = for opt in opts
sanitizedOpt = {}
sanitizedOpt.model = opt.model if opt.model
sanitizedOpt.frame = opt.frame if opt.frame
sanitizedOpt
"getPredictions #{stringify sanitizedOpts}"
else
{ model: modelKey, frame: frameKey } = opts
if modelKey and frameKey
"getPredictions model: #{stringify modelKey}, frame: #{stringify frameKey}"
else if modelKey
"getPredictions model: #{stringify modelKey}"
else if frameKey
"getPredictions frame: #{stringify frameKey}"
else
"getPredictions()"
exports.init = (_) ->
#TODO move these into async
_fork = (f, args...) -> async.fork f, args
_join = (args..., go) -> async.join args, async.applicate go
_call = (go, args...) -> async.join args, async.applicate go
_apply = (go, args) -> async.join args, go
_isFuture = async.isFuture
_async = async.async
_get = async.get
#XXX obsolete
proceed = (func, args, go) ->
go null, render_ {}, -> func.apply null, [_].concat args or []
proceed = (func, args, go) ->
go null, render_.apply null, [ {}, func, ].concat args or []
extendGuiForm = (f) ->
render_ f, form, f
createGui = (controls, go) ->
go null, extendGuiForm signals controls or []
gui = (controls) ->
_fork createGui, controls
gui[name] = f for name, f of gui
flow_ = (raw) ->
raw._flow_ or raw._flow_ = _cache_: {}
#XXX obsolete
render_ = (raw, render) ->
(flow_ raw).render = render
raw
render_ = (raw, render, args...) ->
(flow_ raw).render = (go) ->
# Prepend current context (_) and a continuation (go)
render.apply null, [_, go].concat args
raw
inspect_ = (raw, inspectors) ->
root = flow_ raw
root.inspect = {} unless root.inspect?
for attr, f of inspectors
root.inspect[attr] = f
raw
inspect = (a, b) ->
if arguments.length is 1
inspect$1 a
else
inspect$2 a, b
inspect$1 = (obj) ->
if _isFuture obj
_async inspect, obj
else
if inspectors = obj?._flow_?.inspect
inspections = []
for attr, f of inspectors
inspections.push inspect$2 attr, obj
render_ inspections, h2o.InspectsOutput, inspections
inspections
else
{}
ls = (obj) ->
if _isFuture obj
_async ls, obj
else
if inspectors = obj?._flow_?.inspect
keys inspectors
else
[]
inspect$2 = (attr, obj) ->
return unless attr
return _async inspect, attr, obj if _isFuture obj
return unless obj
return unless root = obj._flow_
return unless inspectors = root.inspect
return cached if cached = root._cache_[ key = "inspect_#{attr}" ]
return unless f = inspectors[attr]
return unless isFunction f
root._cache_[key] = inspection = f()
render_ inspection, h2o.InspectOutput, inspection
inspection
_plot = (render, go) ->
render (error, vis) ->
if error
go new FlowError 'Error rendering vis.', error
else
go null, vis
extendPlot = (vis) ->
render_ vis, h2o.PlotOutput, vis.element
createLightningPlot = (f, go) ->
_plot (f lightning), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plot = (f) ->
if _isFuture f
_fork proceed, h2o.PlotInput, f
else if isFunction f
_fork createLightningPlot, f
else
assist plot
createPlotlyPlot = (f, go) ->
_plot (f Plotly), (error, vis) ->
if error
go error
else
go null, extendPlot vis
plotlyPlot = (f) ->
_fork createPlotlyPlot, f
grid = (f) ->
plot (g) -> g(
g.select()
g.from f
)
transformBinomialMetrics = (metrics) ->
if scores = metrics.thresholds_and_metric_scores
domain = metrics.domain
tps = getTwoDimData scores, 'tps'
tns = getTwoDimData scores, 'tns'
fps = getTwoDimData scores, 'fps'
fns = getTwoDimData scores, 'fns'
cms = for tp, i in tps
domain: domain
matrix: [[tns[i], fps[i]], [fns[i], tp]]
scores.columns.push
name: 'CM'
description: 'CM'
format: 'matrix' #TODO HACK
type: 'matrix'
scores.data.push cms
metrics
extendCloud = (cloud) ->
render_ cloud, h2o.CloudOutput, cloud
extendTimeline = (timeline) ->
render_ timeline, h2o.TimelineOutput, timeline
extendStackTrace = (stackTrace) ->
render_ stackTrace, h2o.StackTraceOutput, stackTrace
extendLogFile = (cloud, nodeIpPort, fileType, logFile) ->
render_ logFile, h2o.LogFileOutput, cloud, nodeIpPort, fileType, logFile
inspectNetworkTestResult = (testResult) -> ->
convertTableToFrame testResult.table, testResult.table.name,
description: testResult.table.name
origin: "testNetwork"
extendNetworkTest = (testResult) ->
inspect_ testResult,
result: inspectNetworkTestResult testResult
render_ testResult, h2o.NetworkTestOutput, testResult
extendProfile = (profile) ->
render_ profile, h2o.ProfileOutput, profile
extendFrames = (frames) ->
render_ frames, h2o.FramesOutput, frames
frames
extendSplitFrameResult = (result) ->
render_ result, h2o.SplitFrameOutput, result
result
extendMergeFramesResult = (result) ->
render_ result, h2o.MergeFramesOutput, result
result
extendPartialDependence= (result) ->
inspections = {}
for data, i in result.partial_dependence_data
origin = "getPartialDependence #{stringify result.destination_key}"
inspections["plot#{i+1}"] = inspectTwoDimTable_ origin, "plot#{i+1}", data
inspect_ result, inspections
render_ result, h2o.PartialDependenceOutput, result
result
# inspectOutputsAcrossModels = (modelCategory, models) -> ->
# switch modelCategory
# when 'Binomial'
# when 'Multinomial'
# when 'Regression'
getModelParameterValue = (type, value) ->
switch type
when 'Key<Frame>', 'Key<Model>'
if value? then value.name else undefined
when 'VecSpecifier'
if value? then value.column_name else undefined
else
if value? then value else undefined
inspectParametersAcrossModels = (models) -> ->
leader = head models
vectors = for parameter, i in leader.parameters
data = for model in models
getModelParameterValue parameter.type, model.parameters[i].actual_value
switch parameter.type
when 'enum', 'Frame', 'string'
lightning.createFactor parameter.label, TString, data
when 'byte', 'short', 'int', 'long', 'float', 'double'
lightning.createVector parameter.label, TNumber, data
when 'string[]', 'byte[]', 'short[]', 'int[]', 'long[]', 'float[]', 'double[]'
lightning.createList parameter.label, data, (a) -> if a then a else undefined
when 'boolean'
lightning.createList parameter.label, data, (a) -> if a then 'true' else 'false'
else
lightning.createList parameter.label, data
modelKeys = (model.model_id.name for model in models)
lightning.createDataFrame 'parameters', vectors, (range models.length), null,
description: "Parameters for models #{modelKeys.join ', '}"
origin: "getModels #{stringify modelKeys}"
inspectModelParameters = (model) -> ->
parameters = model.parameters
attrs = [
'label'
'type'
'level'
'actual_value'
'default_value'
]
vectors = for attr in attrs
data = new Array parameters.length
for parameter, i in parameters
data[i] = if attr is 'actual_value'
getModelParameterValue parameter.type, parameter[attr]
else
parameter[attr]
lightning.createList attr, data
lightning.createDataFrame 'parameters', vectors, (range parameters.length), null,
description: "Parameters for model '#{model.model_id.name}'" #TODO frame model_id
origin: "getModel #{stringify model.model_id.name}"
extendJob = (job) ->
render_ job, h2o.JobOutput, job
extendJobs = (jobs) ->
for job in jobs
extendJob job
render_ jobs, h2o.JobsOutput, jobs
extendCancelJob = (cancellation) ->
render_ cancellation, h2o.CancelJobOutput, cancellation
extendDeletedKeys = (keys) ->
render_ keys, h2o.DeleteObjectsOutput, keys
inspectTwoDimTable_ = (origin, tableName, table) -> ->
convertTableToFrame table, tableName,
description: table.description or ''
origin: origin
inspectRawArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatArray array], (range array.length), null,
description: ''
origin: origin
inspectObjectArray_ = (name, origin, description, array) -> ->
lightning.createDataFrame name, [lightning.createList name, parseAndFormatObjectArray array], (range array.length), null,
description: ''
origin: origin
inspectRawObject_ = (name, origin, description, obj) -> ->
vectors = for k, v of obj
lightning.createList k, [ if v is null then undefined else if isNumber v then format6fi v else v ]
lightning.createDataFrame name, vectors, (range 1), null,
description: ''
origin: origin
_globalHacks =
fields: 'reproducibility_information_table'
_schemaHacks =
KMeansOutput:
fields: 'names domains help'
GBMOutput:
fields: 'names domains help'
GLMOutput:
fields: 'names domains help'
DRFOutput:
fields: 'names domains help'
DeepLearningModelOutput:
fields: 'names domains help'
NaiveBayesOutput:
fields: 'names domains help pcond'
PCAOutput:
fields: 'names domains help'
ModelMetricsBinomialGLM:
fields: null
transform: transformBinomialMetrics
ModelMetricsBinomial:
fields: null
transform: transformBinomialMetrics
ModelMetricsMultinomialGLM:
fields: null
ModelMetricsMultinomial:
fields: null
ModelMetricsRegressionGLM:
fields: null
ModelMetricsRegression:
fields: null
ModelMetricsClustering:
fields: null
ModelMetricsAutoEncoder:
fields: null
ConfusionMatrix:
fields: null
blacklistedAttributesBySchema = do ->
dicts = {}
for schema, attrs of _schemaHacks
dicts[schema] = dict = __meta: yes
if attrs.fields
for field in words attrs.fields
dict[field] = yes
dicts
blacklistedAttributesSchemaIndependent = do ->
dict = {}
for attrs of _globalHacks
if attrs = 'fields'
for field in words _globalHacks[attrs]
dict[field] = yes
dict
schemaTransforms = do ->
transforms = {}
for schema, attrs of _schemaHacks
if transform = attrs.transform
transforms[schema] = transform
transforms
inspectObject = (inspections, name, origin, obj) ->
blacklistedAttributes = blacklistedAttributesSchemaIndependent
schemaType = obj.__meta?.schema_type
if schemaType
if attrs = blacklistedAttributesBySchema[schemaType]
for key, value of attrs
blacklistedAttributes[key] = value
obj = transform obj if transform = schemaTransforms[schemaType]
record = {}
inspections[name] = inspectRawObject_ name, origin, name, record
for k, v of obj when not blacklistedAttributes[k]
if v is null
record[k] = null
else
if v.__meta?.schema_type is 'TwoDimTable'
inspections["#{name} - #{v.name}"] = inspectTwoDimTable_ origin, "#{name} - #{v.name}", v
else
if isArray v
if k is 'cross_validation_models' or k is 'cross_validation_predictions' or (name is 'output' and (k is 'weights' or k is 'biases')) # megahack
inspections[k] = inspectObjectArray_ k, origin, k, v
else
inspections[k] = inspectRawArray_ k, origin, k, v
else if isObject v
if meta = v.__meta
if meta.schema_type is 'Key<Frame>'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Key<Model>'
record[k] = "<a href='#' data-type='model' data-key=#{stringify v.name}>#{escape v.name}</a>"
else if meta.schema_type is 'Frame'
record[k] = "<a href='#' data-type='frame' data-key=#{stringify v.frame_id.name}>#{escape v.frame_id.name}</a>"
else
inspectObject inspections, "#{name} - #{k}", origin, v
else
console.log "WARNING: dropping [#{k}] from inspection:", v
else
record[k] = if isNumber v then format6fi v else v
return
extendModel = (model) ->
extend = (model) ->
inspections = {}
inspections.parameters = inspectModelParameters model
origin = "getModel #{stringify model.model_id.name}"
inspectObject inspections, 'output', origin, model.output
# Obviously, an array of 2d tables calls for a megahack.
if model.__meta.schema_type is 'NaiveBayesModel'
if isArray model.output.pcond
for table in model.output.pcond
tableName = "output - pcond - #{table.name}"
inspections[tableName] = inspectTwoDimTable_ origin, tableName, table
inspect_ model, inspections
model
refresh = (go) ->
_.requestModel model.model_id.name, (error, model) ->
if error then go error else go null, extend model
extend model
render_ model, h2o.ModelOutput, model, refresh
extendGrid = (grid, opts) ->
origin = "getGrid #{stringify grid.grid_id.name}"
origin += ", #{stringify opts}" if opts
inspections =
summary: inspectTwoDimTable_ origin, "summary", grid.summary_table
scoring_history: inspectTwoDimTable_ origin, "scoring_history", grid.scoring_history
inspect_ grid, inspections
render_ grid, h2o.GridOutput, grid
extendGrids = (grids) ->
render_ grids, h2o.GridsOutput, grids
extendLeaderboard = (result) ->
render_ result, h2o.LeaderboardOutput, result
extendModels = (models) ->
inspections = {}
algos = uniq (model.algo for model in models)
if algos.length is 1
inspections.parameters = inspectParametersAcrossModels models
# modelCategories = uniq (model.output.model_category for model in models)
# TODO implement model comparision after 2d table cleanup for model metrics
#if modelCategories.length is 1
# inspections.outputs = inspectOutputsAcrossModels (head modelCategories), models
inspect_ models, inspections
render_ models, h2o.ModelsOutput, models
read = (value) -> if value is 'NaN' then null else value
extendPredictions = (opts, predictions) ->
render_ predictions, h2o.PredictsOutput, opts, predictions
predictions
extendPrediction = (result) ->
modelKey = result.model.name
frameKey = result.frame?.name
prediction = head result.model_metrics
predictionFrame = if result.predictions_frame is null then result.frame? else result.predictions_frame
inspections = {}
if prediction
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", prediction
else
prediction = {}
inspectObject inspections, 'Prediction', "getPrediction model: #{stringify modelKey}, frame: #{stringify frameKey}", { prediction_frame: predictionFrame }
inspect_ prediction, inspections
render_ prediction, h2o.PredictOutput, modelKey, frameKey, predictionFrame, prediction
inspectFrameColumns = (tableLabel, frameKey, frame, frameColumns) -> ->
attrs = [
'label'
'type'
'missing_count|Missing'
'zero_count|Zeros'
'positive_infinity_count|+Inf'
'negative_infinity_count|-Inf'
'min'
'max'
'mean'
'sigma'
'cardinality'
]
toColumnSummaryLink = (label) ->
"<a href='#' data-type='summary-link' data-key=#{stringify label}>#{escape label}</a>"
toConversionLink = (value) ->
[ type, label ] = value.split '\0'
switch type
when 'enum'
"<a href='#' data-type='as-numeric-link' data-key=#{stringify label}>Convert to numeric</a>"
when 'int', 'string'
"<a href='#' data-type='as-factor-link' data-key=#{stringify label}>Convert to enum</a>"
else
undefined
vectors = for attr in attrs
[ name, title ] = attr.split '|'
title = title ? name
switch name
when 'min'
lightning.createVector title, TNumber, (head column.mins for column in frameColumns), format4f
when 'max'
lightning.createVector title, TNumber, (head column.maxs for column in frameColumns), format4f
when 'cardinality'
lightning.createVector title, TNumber, ((if column.type is 'enum' then column.domain_cardinality else undefined) for column in frameColumns)
when 'label'
lightning.createFactor title, TString, (column[name] for column in frameColumns), null, toColumnSummaryLink
when 'type'
lightning.createFactor title, TString, (column[name] for column in frameColumns)
when 'mean', 'sigma'
lightning.createVector title, TNumber, (column[name] for column in frameColumns), format4f
else
lightning.createVector title, TNumber, (column[name] for column in frameColumns)
[ labelVector, typeVector ] = vectors
actionsData = for i in [0 ... frameColumns.length]
"#{typeVector.valueAt i}\0#{labelVector.valueAt i}"
vectors.push lightning.createFactor 'Actions', TString, actionsData, null, toConversionLink
lightning.createDataFrame tableLabel, vectors, (range frameColumns.length), null,
description: "A list of #{tableLabel} in the H2O Frame."
origin: "getFrameSummary #{stringify frameKey}"
plot: "plot inspect '#{tableLabel}', getFrameSummary #{stringify frameKey}"
inspectFrameData = (frameKey, frame) -> ->
frameColumns = frame.columns
vectors = for column in frameColumns
#XXX format functions
switch column.type
when 'int', 'real'
lightning.createVector column.label, TNumber, (parseNaNs column.data), format4f
when 'enum'
domain = column.domain
lightning.createFactor column.label, TString, ((if index? then domain[index] else undefined) for index in column.data)
when 'time'
lightning.createVector column.label, TNumber, parseNaNs column.data
when 'string', 'uuid'
lightning.createList column.label, parseNulls column.string_data
else
lightning.createList column.label, parseNulls column.data
vectors.unshift lightning.createVector 'Row', TNumber, (rowIndex + 1 for rowIndex in [frame.row_offset ... frame.row_count])
lightning.createDataFrame 'data', vectors, (range frame.row_count - frame.row_offset), null,
description: 'A partial list of rows in the H2O Frame.'
origin: "getFrameData #{stringify frameKey}"
extendFrameData = (frameKey, frame) ->
inspections =
data: inspectFrameData frameKey, frame
origin = "getFrameData #{stringify frameKey}"
inspect_ frame, inspections
render_ frame, h2o.FrameDataOutput, frame
extendFrame = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
data: inspectFrameData frameKey, frame
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendFrameSummary = (frameKey, frame) ->
inspections =
columns: inspectFrameColumns 'columns', frameKey, frame, frame.columns
enumColumns = (column for column in frame.columns when column.type is 'enum')
inspections.factors = inspectFrameColumns 'factors', frameKey, frame, enumColumns if enumColumns.length > 0
origin = "getFrameSummary #{stringify frameKey}"
inspections[frame.chunk_summary.name] = inspectTwoDimTable_ origin, frame.chunk_summary.name, frame.chunk_summary
inspections[frame.distribution_summary.name] = inspectTwoDimTable_ origin, frame.distribution_summary.name, frame.distribution_summary
inspect_ frame, inspections
render_ frame, h2o.FrameOutput, frame
extendColumnSummary = (frameKey, frame, columnName) ->
column = head frame.columns
rowCount = frame.rows
inspectPercentiles = ->
vectors = [
lightning.createVector 'percentile', TNumber, frame.default_percentiles
lightning.createVector 'value', TNumber, column.percentiles
]
lightning.createDataFrame 'percentiles', vectors, (range frame.default_percentiles.length), null,
description: "Percentiles for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDistribution = ->
minBinCount = 32
{ histogram_base:base, histogram_stride:stride, histogram_bins:bins } = column
width = Math.ceil bins.length / minBinCount
interval = stride * width
rows = []
if width > 0
binCount = minBinCount + if bins.length % width > 0 then 1 else 0
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for i in [0 ... binCount]
m = i * width
n = m + width
count = 0
for binIndex in [m ... n] when binIndex < bins.length
count += bins[binIndex]
intervalData[i] = base + i * interval
widthData[i] = interval
countData[i] = count
else
binCount = bins.length
intervalData = new Array binCount
widthData = new Array binCount
countData = new Array binCount
for count, i in bins
intervalData[i] = base + i * stride
widthData[i] = stride
countData[i] = count
# Trim off empty bins from the end
for i in [binCount - 1 .. 0]
if countData[i] isnt 0
binCount = i + 1
intervalData = intervalData.slice 0, binCount
widthData = widthData.slice 0, binCount
countData = countData.slice 0, binCount
break
vectors = [
lightning.createFactor 'interval', TString, intervalData
lightning.createVector 'width', TNumber, widthData
lightning.createVector 'count', TNumber, countData
]
lightning.createDataFrame 'distribution', vectors, (range binCount), null,
description: "Distribution for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'distribution', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectCharacteristics = ->
{ missing_count, zero_count, positive_infinity_count, negative_infinity_count } = column
other = rowCount - missing_count - zero_count - positive_infinity_count - negative_infinity_count
characteristicData = [ 'Missing', '-Inf', 'Zero', '+Inf', 'Other' ]
countData = [ missing_count, negative_infinity_count, zero_count, positive_infinity_count, other ]
percentData = for count in countData
100 * count / rowCount
vectors = [
lightning.createFactor 'characteristic', TString, characteristicData
lightning.createVector 'count', TNumber, countData
lightning.createVector 'percent', TNumber, percentData
]
lightning.createDataFrame 'characteristics', vectors, (range characteristicData.length), null,
description: "Characteristics for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'characteristics', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectSummary = ->
defaultPercentiles = frame.default_percentiles
percentiles = column.percentiles
mean = column.mean
q1 = percentiles[defaultPercentiles.indexOf 0.25]
q2 = percentiles[defaultPercentiles.indexOf 0.5]
q3 = percentiles[defaultPercentiles.indexOf 0.75]
outliers = uniq concat column.mins, column.maxs
minimum = head column.mins
maximum = head column.maxs
vectors = [
lightning.createFactor 'column', TString, [ columnName ]
lightning.createVector 'mean', TNumber, [ mean ]
lightning.createVector 'q1', TNumber, [ q1 ]
lightning.createVector 'q2', TNumber, [ q2 ]
lightning.createVector 'q3', TNumber, [ q3 ]
lightning.createVector 'min', TNumber, [ minimum ]
lightning.createVector 'max', TNumber, [ maximum ]
]
lightning.createDataFrame 'summary', vectors, (range 1), null,
description: "Summary for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'summary', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspectDomain = ->
levels = map column.histogram_bins, (count, index) -> count: count, index: index
#TODO sort table in-place when sorting is implemented
sortedLevels = sortBy levels, (level) -> -level.count
[ labels, counts, percents ] = createArrays 3, sortedLevels.length
for level, i in sortedLevels
labels[i] = column.domain[level.index]
counts[i] = level.count
percents[i] = 100 * level.count / rowCount
vectors = [
lightning.createFactor 'label', TString, labels
lightning.createVector 'count', TNumber, counts
lightning.createVector 'percent', TNumber, percents
]
lightning.createDataFrame 'domain', vectors, (range sortedLevels.length), null,
description: "Domain for column '#{column.label}' in frame '#{frameKey}'."
origin: "getColumnSummary #{stringify frameKey}, #{stringify columnName}"
plot: "plot inspect 'domain', getColumnSummary #{stringify frameKey}, #{stringify columnName}"
inspections =
characteristics: inspectCharacteristics
switch column.type
when 'int', 'real'
# Skip for columns with all NAs
if column.histogram_bins.length
inspections.distribution = inspectDistribution
# Skip for columns with all NAs
unless (some column.percentiles, (a) -> a is 'NaN')
inspections.summary = inspectSummary
inspections.percentiles = inspectPercentiles
when 'enum'
inspections.domain = inspectDomain
inspect_ frame, inspections
render_ frame, h2o.ColumnSummaryOutput, frameKey, frame, columnName
requestFrame = (frameKey, go) ->
_.requestFrameSlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrame frameKey, frame
requestFrameData = (frameKey, searchTerm, offset, count, go) ->
_.requestFrameSlice frameKey, searchTerm, offset, count, (error, frame) ->
if error
go error
else
go null, extendFrameData frameKey, frame
requestFrameSummarySlice = (frameKey, searchTerm, offset, length, go) ->
_.requestFrameSummarySlice frameKey, searchTerm, offset, length, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestFrameSummary = (frameKey, go) ->
_.requestFrameSummarySlice frameKey, undefined, 0, 20, (error, frame) ->
if error
go error
else
go null, extendFrameSummary frameKey, frame
requestColumnSummary = (frameKey, columnName, go) ->
_.requestColumnSummary frameKey, columnName, (error, frame) ->
if error
go error
else
go null, extendColumnSummary frameKey, frame, columnName
requestFrames = (go) ->
_.requestFrames (error, frames) ->
if error
go error
else
go null, extendFrames frames
requestCreateFrame = (opts, go) ->
_.requestCreateFrame opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependence = (opts, go) ->
_.requestPartialDependence opts, (error, result) ->
if error
go error
else
_.requestJob result.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
requestPartialDependenceData = (key, go) ->
_.requestPartialDependenceData key, (error, result) ->
if error
go error
else
go null, extendPartialDependence result
computeSplits = (ratios, keys) ->
parts = []
sum = 0
for key, i in keys.slice(0, ratios.length)
sum += ratio = ratios[i]
parts.push
key: key
ratio: ratio
parts.push
key: keys[keys.length - 1]
ratio: 1 - sum
splits = []
sum = 0
for part in parts
splits.push
min: sum
max: sum + part.ratio
key: part.key
sum += part.ratio
splits
requestBindFrames = (key, sourceKeys, go) ->
_.requestExec "(assign #{key} (cbind #{sourceKeys.join ' '}))", (error, result) ->
if error
go error
else
go null, extendBindFrames key, result
requestSplitFrame = (frameKey, splitRatios, splitKeys, seed, go) ->
if splitRatios.length is splitKeys.length - 1
splits = computeSplits splitRatios, splitKeys
randomVecKey = PI:KEY:<KEY>END_PI()
statements = []
statements.push "(tmp= #{randomVecKey} (h2o.runif #{frameKey} #{seed}))"
for part, i in splits
g = if i isnt 0 then "(> #{randomVecKey} #{part.min})" else null
l = if i isnt splits.length - 1 then "(<= #{randomVecKey} #{part.max})" else null
sliceExpr = if g and l
"(& #{g} #{l})"
else if l
l
else
g
statements.push "(assign #{part.key} (rows #{frameKey} #{sliceExpr}))"
statements.push "(rm #{randomVecKey})"
_.requestExec "(, #{statements.join ' '})", (error, result) ->
if error
go error
else
go null, extendSplitFrameResult
keys: splitKeys
ratios: splitRatios
else
go new FlowError 'The number of split ratios should be one less than the number of split keys'
requestMergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows, go) ->
lr = if includeAllLeftRows then 'TRUE' else 'FALSE'
rr = if includeAllRightRows then 'TRUE' else 'FALSE'
statement = "(assign #{destinationKey} (merge #{leftFrameKey} #{rightFrameKey} #{lr} #{rr} #{leftColumnIndex} #{rightColumnIndex} \"radix\"))"
_.requestExec statement, (error, result) ->
if error
go error
else
go null, extendMergeFramesResult
key: destinationKey
createFrame = (opts) ->
if opts
_fork requestCreateFrame, opts
else
assist createFrame
splitFrame = (frameKey, splitRatios, splitKeys, seed=-1) ->
if frameKey and splitRatios and splitKeys
_fork requestSplitFrame, frameKey, splitRatios, splitKeys, seed
else
assist splitFrame
mergeFrames = (destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows) ->
if destinationKey and leftFrameKey and rightFrameKey
_fork requestMergeFrames, destinationKey, leftFrameKey, leftColumnIndex, includeAllLeftRows, rightFrameKey, rightColumnIndex, includeAllRightRows
else
assist mergeFrames
# define the function that is called when
# the Partial Dependence plot input form
# is submitted
buildPartialDependence = (opts) ->
if opts
_fork requestPartialDependence, opts
else
# specify function to call if user
# provides malformed input
assist buildPartialDependence
getPartialDependence = (destinationKey) ->
if destinationKey
_fork requestPartialDependenceData, destinationKey
else
assist getPartialDependence
getFrames = ->
_fork requestFrames
getFrame = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrame, frameKey
else
assist getFrame
bindFrames = (key, sourceKeys) ->
_fork requestBindFrames, key, sourceKeys
getFrameSummary = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameSummary, frameKey
else
assist getFrameSummary
getFrameData = (frameKey) ->
switch typeOf frameKey
when 'String'
_fork requestFrameData, frameKey, undefined, 0, 20
else
assist getFrameSummary
requestDeleteFrame = (frameKey, go) ->
_.requestDeleteFrame frameKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ frameKey ]
deleteFrame = (frameKey) ->
if frameKey
_fork requestDeleteFrame, frameKey
else
assist deleteFrame
extendExportFrame = (result) ->
render_ result, h2o.ExportFrameOutput, result
extendBindFrames = (key, result) ->
render_ result, h2o.BindFramesOutput, key, result
requestExportFrame = (frameKey, path, opts, go) ->
_.requestExportFrame frameKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error
go error
else
_.requestJob result.job.key.name, (error, job) ->
if error
go error
else
go null, extendJob job
exportFrame = (frameKey, path, opts={}) ->
if frameKey and path
_fork requestExportFrame, frameKey, path, opts
else
assist exportFrame, frameKey, path, opts
requestDeleteFrames = (frameKeys, go) ->
futures = map frameKeys, (frameKey) ->
_fork _.requestDeleteFrame, frameKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys frameKeys
deleteFrames = (frameKeys) ->
switch frameKeys.length
when 0
assist deleteFrames
when 1
deleteFrame head frameKeys
else
_fork requestDeleteFrames, frameKeys
getColumnSummary = (frameKey, columnName) ->
_fork requestColumnSummary, frameKey, columnName
requestModels = (go) ->
_.requestModels (error, models) ->
if error then go error else go null, extendModels models
requestModelsByKeys = (modelKeys, go) ->
futures = map modelKeys, (key) ->
_fork _.requestModel, key
async.join futures, (error, models) ->
if error then go error else go null, extendModels models
getModels = (modelKeys) ->
if isArray modelKeys
if modelKeys.length
_fork requestModelsByKeys, modelKeys
else
_fork requestModels
else
_fork requestModels
requestGrids = (go) ->
_.requestGrids (error, grids) ->
if error then go error else go null, extendGrids grids
getGrids = ->
_fork requestGrids
requestLeaderboard = (key, go) ->
_.requestLeaderboard key, (error, leaderboard) ->
if error then go error else go null, extendLeaderboard leaderboard
getLeaderboard = (key) ->
_fork requestLeaderboard, key
requestModel = (modelKey, go) ->
_.requestModel modelKey, (error, model) ->
if error then go error else go null, extendModel model
getModel = (modelKey) ->
switch typeOf modelKey
when 'String'
_fork requestModel, modelKey
else
assist getModel
requestGrid = (gridKey, opts, go) ->
_.requestGrid gridKey, opts, (error, grid) ->
if error then go error else go null, extendGrid grid, opts
getGrid = (gridKey, opts) ->
switch typeOf gridKey
when 'String'
_fork requestGrid, gridKey, opts
else
assist getGrid
findColumnIndexByColumnLabel = (frame, columnLabel) ->
for column, i in frame.columns when column.label is columnLabel
return i
throw new FlowError "Column [#{columnLabel}] not found in frame"
findColumnIndicesByColumnLabels = (frame, columnLabels) ->
for columnLabel in columnLabels
findColumnIndexByColumnLabel frame, columnLabel
requestImputeColumn = (opts, go) ->
{ frame, column, method, combineMethod, groupByColumns } = opts
combineMethod = combineMethod ? 'interpolate'
_.requestFrameSummaryWithoutData frame, (error, result) ->
if error
go error
else
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
if groupByColumns and groupByColumns.length
try
groupByColumnIndices = findColumnIndicesByColumnLabels result, groupByColumns
catch columnIndicesError
return go columnIndicesError
else
groupByColumnIndices = null
groupByArg = if groupByColumnIndices
"[#{groupByColumnIndices.join ' '}]"
else
"[]"
_.requestExec "(h2o.impute #{frame} #{columnIndex} #{JSON.stringify method} #{JSON.stringify combineMethod} #{groupByArg} _ _)", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
requestChangeColumnType = (opts, go) ->
{ frame, column, type } = opts
method = if type is 'enum' then 'as.factor' else 'as.numeric'
_.requestFrameSummaryWithoutData frame, (error, result) ->
try
columnIndex = findColumnIndexByColumnLabel result, column
catch columnKeyError
return go columnKeyError
_.requestExec "(assign #{frame} (:= #{frame} (#{method} (cols #{frame} #{columnIndex})) #{columnIndex} [0:#{result.rows}]))", (error, result) ->
if error
go error
else
requestColumnSummary frame, column, go
imputeColumn = (opts) ->
if opts and opts.frame and opts.column and opts.method
_fork requestImputeColumn, opts
else
assist imputeColumn, opts
changeColumnType = (opts) ->
if opts and opts.frame and opts.column and opts.type
_fork requestChangeColumnType, opts
else
assist changeColumnType, opts
requestDeleteModel = (modelKey, go) ->
_.requestDeleteModel modelKey, (error, result) ->
if error then go error else go null, extendDeletedKeys [ modelKey ]
deleteModel = (modelKey) ->
if modelKey
_fork requestDeleteModel, modelKey
else
assist deleteModel
extendImportModel = (result) ->
render_ result, h2o.ImportModelOutput, result
requestImportModel = (path, opts, go) ->
_.requestImportModel path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendImportModel result
importModel = (path, opts) ->
if path and path.length
_fork requestImportModel, path, opts
else
assist importModel, path, opts
extendExportModel = (result) ->
render_ result, h2o.ExportModelOutput, result
requestExportModel = (modelKey, path, opts, go) ->
_.requestExportModel opts.format, modelKey, path, (if opts.overwrite then yes else no), (error, result) ->
if error then go error else go null, extendExportModel result
exportModel = (modelKey, path, opts) ->
if modelKey and path
_fork requestExportModel, modelKey, path, opts
else
assist exportModel, modelKey, path, opts
requestDeleteModels = (modelKeys, go) ->
futures = map modelKeys, (modelKey) ->
_fork _.requestDeleteModel, modelKey
async.join futures, (error, results) ->
if error
go error
else
go null, extendDeletedKeys modelKeys
deleteModels = (modelKeys) ->
switch modelKeys.length
when 0
assist deleteModels
when 1
deleteModel head modelKeys
else
_fork requestDeleteModels, modelKeys
requestJob = (key, go) ->
_.requestJob key, (error, job) ->
if error
go error
else
go null, extendJob job
requestJobs = (go) ->
_.requestJobs (error, jobs) ->
if error
go error
else
go null, extendJobs jobs
getJobs = ->
_fork requestJobs
getJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestJob, arg
when 'Object'
if arg.key?
getJob arg.key
else
assist getJob
else
assist getJob
requestCancelJob = (key, go) ->
_.requestCancelJob key, (error) ->
if error
go error
else
go null, extendCancelJob {}
cancelJob = (arg) ->
switch typeOf arg
when 'String'
_fork requestCancelJob, arg
else
assist cancelJob
extendImportResults = (importResults) ->
render_ importResults, h2o.ImportFilesOutput, importResults
requestImportFiles = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
go null, extendImportResults importResults
importFiles = (paths) ->
switch typeOf paths
when 'Array'
_fork requestImportFiles, paths
else
assist importFiles
extendImportSqlResults = (importResults) ->
render_ importResults, h2o.ImportSqlTableOutput, importResults
requestImportSqlTable = (arg, go) ->
_.requestImportSqlTable arg, (error, importResults) ->
if error
go error
else
go null, extendImportSqlResults importResults
importSqlTable = (arg) ->
switch typeOf arg
when 'Object'
_fork requestImportSqlTable, arg
else
assist importSqlTable
importBqTable = ->
assist importBqTable
extendParseSetupResults = (args, parseSetupResults) ->
render_ parseSetupResults, h2o.SetupParseOutput, args, parseSetupResults
requestImportAndParseSetup = (paths, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { paths: paths }, parseSetupResults
requestParseSetup = (sourceKeys, go) ->
_.requestParseSetup sourceKeys, (error, parseSetupResults) ->
if error
go error
else
go null, extendParseSetupResults { source_frames: sourceKeys }, parseSetupResults
setupParse = (args) ->
if args.paths and isArray args.paths
_fork requestImportAndParseSetup, args.paths
else if args.source_frames and isArray args.source_frames
_fork requestParseSetup, args.source_frames
else
assist setupParse
extendParseResult = (parseResult) ->
render_ parseResult, h2o.JobOutput, parseResult.job
requestImportAndParseFiles = (paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestImportFiles paths, (error, importResults) ->
if error
go error
else
sourceKeys = flatten compact map importResults, (result) -> result.destination_frames
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
requestParseFiles = (sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, go) ->
_.requestParseFiles sourceKeys, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize, (error, parseResult) ->
if error
go error
else
go null, extendParseResult parseResult
parseFiles = (opts) -> #XXX review args
#XXX validation
destinationKey = opts.destination_frame
parseType = opts.parse_type
separator = opts.separator
columnCount = opts.number_columns
useSingleQuotes = opts.single_quotes
columnNames = opts.column_names
columnTypes = opts.column_types
deleteOnDone = opts.delete_on_done
checkHeader = opts.check_header
chunkSize = opts.chunk_size
if opts.paths
_fork requestImportAndParseFiles, opts.paths, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
else
_fork requestParseFiles, opts.source_frames, destinationKey, parseType, separator, columnCount, useSingleQuotes, columnNames, columnTypes, deleteOnDone, checkHeader, chunkSize
requestModelBuild = (algo, opts, go) ->
_.requestModelBuild algo, opts, (error, result) ->
if error
go error
else
if result.error_count > 0
messages = (validation.message for validation in result.messages)
go new FlowError "Model build failure: #{messages.join '; '}"
else
go null, extendJob result.job
requestAutoMLBuild = (opts , go) ->
_.requestAutoMLBuild opts, (error, result) ->
if error
go error
else
go null, extendJob result.job
runAutoML = (opts, action) ->
if action is 'exec'
_fork requestAutoMLBuild, opts
else
assist runAutoML, opts
buildModel = (algo, opts) ->
if algo and opts and keys(opts).length > 1
_fork requestModelBuild, algo, opts
else
assist buildModel, algo, opts
unwrapPrediction = (go) ->
(error, result) ->
if error
go error
else
go null, extendPrediction result
requestPredict = (destinationKey, modelKey, frameKey, options, go) ->
_.requestPredict destinationKey, modelKey, frameKey, options, unwrapPrediction go
requestPredicts = (opts, go) ->
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey, options: options } = opt
_fork _.requestPredict, null, modelKey, frameKey, options or {}
async.join futures, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
predict = (opts={}) ->
{ predictions_frame, model, models, frame, frames, reconstruction_error, deep_features_hidden_layer, leaf_node_assignment, exemplar_index } = opts
if models or frames
unless models
if model
models = [ model ]
unless frames
if frame
frames = [ frame ]
if frames and models
combos = []
for model in models
for frame in frames
combos.push model: model, frame: frame
_fork requestPredicts, combos
else
assist predict, predictions_frame: predictions_frame, models: models, frames: frames
else
if model and frame
_fork requestPredict, predictions_frame, model, frame,
reconstruction_error: reconstruction_error
deep_features_hidden_layer: deep_features_hidden_layer
leaf_node_assignment: leaf_node_assignment
else if model and exemplar_index isnt undefined
_fork requestPredict, predictions_frame, model, null,
exemplar_index: exemplar_index
else
assist predict, predictions_frame: predictions_frame, model: model, frame: frame
requestPrediction = (modelKey, frameKey, go) ->
_.requestPrediction modelKey, frameKey, unwrapPrediction go
requestPredictions = (opts, go) ->
if isArray opts
futures = map opts, (opt) ->
{ model: modelKey, frame: frameKey } = opt
_fork _.requestPredictions, modelKey, frameKey
async.join futures, (error, predictions) ->
if error
go error
else
# De-dupe predictions
uniquePredictions = values keyBy (flatten predictions, yes), (prediction) -> prediction.model.name + prediction.frame.name
go null, extendPredictions opts, uniquePredictions
else
{ model: modelKey, frame: frameKey } = opts
_.requestPredictions modelKey, frameKey, (error, predictions) ->
if error
go error
else
go null, extendPredictions opts, predictions
getPrediction = (opts={}) ->
{ predictions_frame, model, frame } = opts
if model and frame
_fork requestPrediction, model, frame
else
assist getPrediction, predictions_frame: predictions_frame, model: model, frame: frame
getPredictions = (opts={}) ->
_fork requestPredictions, opts
requestCloud = (go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
go null, extendCloud cloud
getCloud = ->
_fork requestCloud
requestTimeline = (go) ->
_.requestTimeline (error, timeline) ->
if error
go error
else
go null, extendTimeline timeline
getTimeline = ->
_fork requestTimeline
requestStackTrace = (go) ->
_.requestStackTrace (error, stackTrace) ->
if error
go error
else
go null, extendStackTrace stackTrace
getStackTrace = ->
_fork requestStackTrace
requestLogFile = (nodeIpPort, fileType, go) ->
_.requestCloud (error, cloud) ->
if error
go error
else
_.requestLogFile nodeIpPort, fileType, (error, logFile) ->
if error
go error
else
go null, extendLogFile cloud, nodeIpPort, fileType, logFile
getLogFile = (nodeIpPort="self", fileType='info') ->
_fork requestLogFile, nodeIpPort, fileType
requestNetworkTest = (go) ->
_.requestNetworkTest (error, result) ->
if error
go error
else
go null, extendNetworkTest result
testNetwork = ->
_fork requestNetworkTest
requestRemoveAll = (go) ->
_.requestRemoveAll (error, result) ->
if error
go error
else
go null, extendDeletedKeys []
deleteAll = ->
_fork requestRemoveAll
extendRDDs = (rdds) ->
render_ rdds, h2o.RDDsOutput, rdds
rdds
requestRDDs = (go) ->
_.requestRDDs (error, result) ->
if error
go error
else
go null, extendRDDs result.rdds
getRDDs = ->
_fork requestRDDs
extendDataFrames = (dataframes) ->
render_ dataframes, h2o.DataFramesOutput, dataframes
dataframes
requestDataFrames = (go) ->
_.requestDataFrames (error, result) ->
if error
go error
else
go null, extendDataFrames result.dataframes
getDataFrames = ->
_fork requestDataFrames
extendAsH2OFrame = (result) ->
render_ result, h2o.H2OFrameOutput, result
result
requestAsH2OFrameFromRDD = (rdd_id, name, go) ->
_.requestAsH2OFrameFromRDD rdd_id,name, (error, h2oframe_id) ->
if error
go error
else
go null, extendAsH2OFrame h2oframe_id
asH2OFrameFromRDD = (rdd_id, name=undefined) ->
_fork requestAsH2OFrameFromRDD, rdd_id, name
requestAsH2OFrameFromDF = (df_id, name, go) ->
_.requestAsH2OFrameFromDF df_id, name, (error, result) ->
if error
go error
else
go null, extendAsH2OFrame result
asH2OFrameFromDF = (df_id, name=undefined) ->
_fork requestAsH2OFrameFromDF, df_id, name
extendAsDataFrame = (result) ->
render_ result, h2o.DataFrameOutput, result
result
requestAsDataFrame = (hf_id, name, go) ->
_.requestAsDataFrame hf_id, name, (error, result) ->
if error
go error
else
go null, extendAsDataFrame result
asDataFrame = (hf_id, name=undefined) ->
_fork requestAsDataFrame, hf_id, name
getScalaCodeExecutionResult = (key) ->
switch typeOf key
when 'String'
_fork requestScalaCodeExecutionResult, key
else
assist getScalaCodeExecutionResult
requestScalaCodeExecutionResult = (key, go) ->
_.requestScalaCodeExecutionResult key, (error, result) ->
if error
go error
else
go null, extendScalaSyncCode result
requestScalaCode = (session_id, async, code, go) ->
_.requestScalaCode session_id, code, (error, result) ->
if error
go error
else
if async
go null, extendScalaAsyncCode result
else
go null, extendScalaSyncCode result
extendScalaSyncCode = (result) ->
render_ result, h2o.ScalaCodeOutput, result
result
extendScalaAsyncCode = (result) ->
render_ result, h2o.JobOutput, result.job
result
runScalaCode = (session_id, async, code) ->
_fork requestScalaCode, session_id, async, code
requestScalaIntp = (go) ->
_.requestScalaIntp (error, result) ->
if error
go error
else
go null, extendScalaIntp result
extendScalaIntp = (result) ->
render_ result, h2o.ScalaIntpOutput, result
result
getScalaIntp = ->
_fork requestScalaIntp
requestProfile = (depth, go) ->
_.requestProfile depth, (error, profile) ->
if error
go error
else
go null, extendProfile profile
getProfile = (opts) ->
opts = depth: 10 unless opts
_fork requestProfile, opts.depth
loadScript = (path, go) ->
onDone = (script, status) -> go null, script:script, status:status
onFail = (jqxhr, settings, error) -> go error #TODO use framework error
$.getScript path
.done onDone
.fail onFail
dumpFuture = (result, go) ->
result ?= {}
console.debug result
go null, render_ result, objectBrowser, 'dump', result
dump = (f) ->
if f?.isFuture
_fork dumpFuture, f
else
async.async -> f
assist = (func, args...) ->
if func is undefined
_fork proceed, h2o.Assist, [ _assistance ]
else
switch func
when importFiles
_fork proceed, h2o.ImportFilesInput, []
when importSqlTable
_fork proceed, h2o.ImportSqlTableInput, args
when importBqTable
_fork proceed, h2o.ImportBqTableInput, args
when buildModel
_fork proceed, h2o.ModelInput, args
when runAutoML
_fork proceed, h2o.AutoMLInput, args
when predict, getPrediction
_fork proceed, h2o.PredictInput, args
when createFrame
_fork proceed, h2o.CreateFrameInput, args
when splitFrame
_fork proceed, h2o.SplitFrameInput, args
when mergeFrames
_fork proceed, h2o.MergeFramesInput, args
when buildPartialDependence
_fork proceed, h2o.PartialDependenceInput, args
when exportFrame
_fork proceed, h2o.ExportFrameInput, args
when imputeColumn
_fork proceed, h2o.ImputeInput, args
when importModel
_fork proceed, h2o.ImportModelInput, args
when exportModel
_fork proceed, h2o.ExportModelInput, args
else
_fork proceed, h2o.NoAssist, []
link _.ready, ->
link _.ls, ls
link _.inspect, inspect
link _.plot, (p) -> p lightning
link _.plotlyPlot, (p) -> p Plotly
link _.grid, (frame) ->
lightning(
lightning.select()
lightning.from frame
)
link _.enumerate, (frame) ->
lightning(
lightning.select 0
lightning.from frame
)
link _.requestFrameDataE, requestFrameData
link _.requestFrameSummarySliceE, requestFrameSummarySlice
initAssistanceSparklingWater = ->
_assistance.getRDDs =
description: 'Get a list of Spark\'s RDDs'
icon: 'table'
_assistance.getDataFrames =
description: 'Get a list of Spark\'s data frames'
icon: 'table'
link _.initialized, ->
if _.onSparklingWater
initAssistanceSparklingWater()
routines =
# fork/join
fork: _fork
join: _join
call: _call
apply: _apply
isFuture: _isFuture
#
# Dataflow
signal: signal
signals: signals
isSignal: isSignal
act: act
react: react
lift: lift
merge: merge
#
# Generic
dump: dump
inspect: inspect
plot: plot
plotlyPlot: plotlyPlot
grid: grid
get: _get
#
# Meta
assist: assist
#
# GUI
gui: gui
#
# Util
loadScript: loadScript
#
# H2O
getJobs: getJobs
getJob: getJob
cancelJob: cancelJob
importFiles: importFiles
importSqlTable: importSqlTable
importBqTable: importBqTable
setupParse: setupParse
parseFiles: parseFiles
createFrame: createFrame
splitFrame: splitFrame
mergeFrames: mergeFrames
buildPartialDependence: buildPartialDependence
getPartialDependence: getPartialDependence
getFrames: getFrames
getFrame: getFrame
bindFrames: bindFrames
getFrameSummary: getFrameSummary
getFrameData: getFrameData
deleteFrames: deleteFrames
deleteFrame: deleteFrame
exportFrame: exportFrame
getColumnSummary: getColumnSummary
changeColumnType: changeColumnType
imputeColumn: imputeColumn
buildModel: buildModel
runAutoML: runAutoML
getGrids: getGrids
getLeaderboard: getLeaderboard
getModels: getModels
getModel: getModel
getGrid: getGrid
deleteModels: deleteModels
deleteModel: deleteModel
importModel: importModel
exportModel: exportModel
predict: predict
getPrediction: getPrediction
getPredictions: getPredictions
getCloud: getCloud
getTimeline: getTimeline
getProfile: getProfile
getStackTrace: getStackTrace
getLogFile: getLogFile
testNetwork: testNetwork
deleteAll: deleteAll
if _.onSparklingWater
routinesOnSw =
getDataFrames: getDataFrames
getRDDs: getRDDs
getScalaIntp: getScalaIntp
runScalaCode: runScalaCode
asH2OFrameFromRDD: asH2OFrameFromRDD
asH2OFrameFromDF: asH2OFrameFromDF
asDataFrame: asDataFrame
getScalaCodeExecutionResult: getScalaCodeExecutionResult
for attrname of routinesOnSw
routines[attrname] = routinesOnSw[attrname]
routines
|
[
{
"context": "###\n @author Gilles Gerlinger\n Copyright 2016. All rights reserved.\n###\n\nfs = ",
"end": 30,
"score": 0.999864399433136,
"start": 14,
"tag": "NAME",
"value": "Gilles Gerlinger"
}
] | test/express.coffee | gigerlin/easyRPC | 1 | ###
@author Gilles Gerlinger
Copyright 2016. All rights reserved.
###
fs = require 'fs'
routes = []; all = '*'
module.exports = ->
app = (req, res) ->
if routes[req.url]
roads = if root = routes[all] then root.concat(routes[req.url]) else routes[req.url]
index = 0
(next = -> if index < roads.length then roads[index++] req, res, next)()
else # this is a file
fs.readFile "./#{req.url}", (err, data) ->
if err
res.statusCode = 404
res.end "error: no class #{req.url.substring(1)}"
else
res.statusCode = 200
res.end data
app.post = app.get = app.use = (path, route) ->
if typeof path is 'function' then route = path; path = all
if road = routes[path] then road.push route else routes[path] = [route]
return app
| 99721 | ###
@author <NAME>
Copyright 2016. All rights reserved.
###
fs = require 'fs'
routes = []; all = '*'
module.exports = ->
app = (req, res) ->
if routes[req.url]
roads = if root = routes[all] then root.concat(routes[req.url]) else routes[req.url]
index = 0
(next = -> if index < roads.length then roads[index++] req, res, next)()
else # this is a file
fs.readFile "./#{req.url}", (err, data) ->
if err
res.statusCode = 404
res.end "error: no class #{req.url.substring(1)}"
else
res.statusCode = 200
res.end data
app.post = app.get = app.use = (path, route) ->
if typeof path is 'function' then route = path; path = all
if road = routes[path] then road.push route else routes[path] = [route]
return app
| true | ###
@author PI:NAME:<NAME>END_PI
Copyright 2016. All rights reserved.
###
fs = require 'fs'
routes = []; all = '*'
module.exports = ->
app = (req, res) ->
if routes[req.url]
roads = if root = routes[all] then root.concat(routes[req.url]) else routes[req.url]
index = 0
(next = -> if index < roads.length then roads[index++] req, res, next)()
else # this is a file
fs.readFile "./#{req.url}", (err, data) ->
if err
res.statusCode = 404
res.end "error: no class #{req.url.substring(1)}"
else
res.statusCode = 200
res.end data
app.post = app.get = app.use = (path, route) ->
if typeof path is 'function' then route = path; path = all
if road = routes[path] then road.push route else routes[path] = [route]
return app
|
[
{
"context": " = require \"./lib/fixtures\"\n\nitems = [\n { name: \"Caprese\", price: \"5.25\"},\n { name: \"Artichoke\", price: \"",
"end": 91,
"score": 0.9998120665550232,
"start": 84,
"tag": "NAME",
"value": "Caprese"
},
{
"context": "[\n { name: \"Caprese\", price: \"5.25\"},\n { name: \"Artichoke\", price: \"6.25\" }\n]\n\nmodule.exports =\n \"eco() ca",
"end": 130,
"score": 0.9998310208320618,
"start": 121,
"tag": "NAME",
"value": "Artichoke"
},
{
"context": "st.ok typeof fn is \"function\"\n test.same \"Hello Sam\", fn name: \"Sam\"\n test.done()\n\n \"compiling he",
"end": 840,
"score": 0.9993060231208801,
"start": 837,
"tag": "NAME",
"value": "Sam"
},
{
"context": "s \"function\"\n test.same \"Hello Sam\", fn name: \"Sam\"\n test.done()\n\n \"compiling hello.eco\": (test)",
"end": 856,
"score": 0.9995747208595276,
"start": 853,
"tag": "NAME",
"value": "Sam"
},
{
"context": " test.same fixture(\"hello.out.1\"), render name: \"Sam\"\n test.done()\n\n \"compiled templates can be re",
"end": 1011,
"score": 0.9994955062866211,
"start": 1008,
"tag": "NAME",
"value": "Sam"
},
{
"context": ".compile \"Hello <%= @name %>\"\n test.same \"Hello Sam\", render name: \"Sam\"\n test.same \"Hello Josh\", ",
"end": 1148,
"score": 0.9992865920066833,
"start": 1145,
"tag": "NAME",
"value": "Sam"
},
{
"context": "name %>\"\n test.same \"Hello Sam\", render name: \"Sam\"\n test.same \"Hello Josh\", render name: \"Josh\"\n",
"end": 1168,
"score": 0.9994326233863831,
"start": 1165,
"tag": "NAME",
"value": "Sam"
},
{
"context": "ello Sam\", render name: \"Sam\"\n test.same \"Hello Josh\", render name: \"Josh\"\n test.done()\n\n \"eco.com",
"end": 1195,
"score": 0.9996142387390137,
"start": 1191,
"tag": "NAME",
"value": "Josh"
},
{
"context": ": \"Sam\"\n test.same \"Hello Josh\", render name: \"Josh\"\n test.done()\n\n \"eco.compile bypasses cache\":",
"end": 1216,
"score": 0.9994402527809143,
"start": 1212,
"tag": "NAME",
"value": "Josh"
},
{
"context": " output = eco.render fixture(\"hello.eco\"), name: \"Sam\"\n test.same fixture(\"hello.out.1\"), output\n ",
"end": 1510,
"score": 0.999585747718811,
"start": 1507,
"tag": "NAME",
"value": "Sam"
},
{
"context": "der \"<%= @emailAddress %>\",\n emailAddress: \"<sstephenson@gmail.com>\"\n\n test.same \"<sstephenson@gmail.com>\",",
"end": 3026,
"score": 0.9999279975891113,
"start": 3005,
"tag": "EMAIL",
"value": "sstephenson@gmail.com"
},
{
"context": "ss: \"<sstephenson@gmail.com>\"\n\n test.same \"<sstephenson@gmail.com>\", output\n test.done()\n\n \"unescaped HTML c",
"end": 3070,
"score": 0.999915599822998,
"start": 3049,
"tag": "EMAIL",
"value": "sstephenson@gmail.com"
},
{
"context": "der \"<%= @emailAddress %>\",\n emailAddress: \"<sstephenson@gmail.com>\"\n escape: (string) ->\n string.toUppe",
"end": 3422,
"score": 0.9999281167984009,
"start": 3401,
"tag": "EMAIL",
"value": "sstephenson@gmail.com"
},
{
"context": " ->\n string.toUpperCase()\n\n test.same \"<SSTEPHENSON@GMAIL.COM>\", output\n test.done()\n\n \"'undefined' is neve",
"end": 3518,
"score": 0.9999279379844666,
"start": 3497,
"tag": "EMAIL",
"value": "SSTEPHENSON@GMAIL.COM"
},
{
"context": " test.same fixture(\"hello.out.1\"), hello name: \"Sam\"\n\n test.done()\n",
"end": 4040,
"score": 0.9963412880897522,
"start": 4037,
"tag": "NAME",
"value": "Sam"
}
] | test/test_eco.coffee | braze-inc/eco | 256 | eco = require ".."
{fixture} = require "./lib/fixtures"
items = [
{ name: "Caprese", price: "5.25"},
{ name: "Artichoke", price: "6.25" }
]
module.exports =
"eco() caches compiled templates": (test) ->
render = eco fixture("hello.eco")
test.same render, eco fixture("hello.eco")
test.done()
"cache can be disabled": (test) ->
cache = eco.cache
eco.cache = false
render = eco fixture("hello.eco")
test.ok render isnt eco fixture("hello.eco")
eco.cache = cache
test.done()
"eco.preprocess": (test) ->
test.same fixture("hello.coffee"), eco.preprocess fixture("hello.eco")
test.done()
"eco.precompile": (test) ->
js = eco.precompile "Hello <%= @name %>"
test.ok typeof js is "string"
fn = eval "(#{js})"
test.ok typeof fn is "function"
test.same "Hello Sam", fn name: "Sam"
test.done()
"compiling hello.eco": (test) ->
render = eco.compile fixture("hello.eco")
test.same fixture("hello.out.1"), render name: "Sam"
test.done()
"compiled templates can be reused": (test) ->
render = eco.compile "Hello <%= @name %>"
test.same "Hello Sam", render name: "Sam"
test.same "Hello Josh", render name: "Josh"
test.done()
"eco.compile bypasses cache": (test) ->
test.ok eco.cache
render = eco.compile fixture("hello.eco")
test.ok render isnt eco.compile fixture("hello.eco")
test.done()
"rendering hello.eco": (test) ->
output = eco.render fixture("hello.eco"), name: "Sam"
test.same fixture("hello.out.1"), output
test.done()
"rendering hello.eco without a name throws an exception": (test) ->
test.expect 1
try
eco.render fixture("hello.eco")
catch err
test.ok err
test.done()
"rendering projects.eco with empty projects array": (test) ->
output = eco.render fixture("projects.eco"), projects: []
test.same fixture("projects.out.1"), output
test.done()
"rendering projects.eco with multiple projects": (test) ->
output = eco.render fixture("projects.eco"), projects: [
{ name: "PowerTMS Active Shipments Page Redesign", url: "/projects/1" },
{ name: "SCU Intranet", url: "/projects/2", description: "<p><em>On hold</em></p>" },
{ name: "Sales Template", url: "/projects/3" }
]
test.same fixture("projects.out.2"), output
test.done()
"rendering helpers.eco": (test) ->
output = eco.render fixture("helpers.eco"),
items: items
contentTag: (tagName, attributes, callback) ->
attrs = (" #{name}=\"#{value}\"" for name, value of attributes)
@safe "<#{tagName}#{attrs.join("")}>#{callback()}</#{tagName}>"
test.same fixture("helpers.out.1"), output
test.done()
"rendering capture.eco": (test) ->
output = eco.render fixture("capture.eco"), items: items
test.same fixture("capture.out.1"), output
test.done()
"HTML is escaped by default": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<sstephenson@gmail.com>"
test.same "<sstephenson@gmail.com>", output
test.done()
"unescaped HTML can be rendered from a helper": (test) ->
output = eco.render "<%= @helper() %>",
helper: -> @safe "<boo>"
test.same "<boo>", output
test.done()
"escape method can be overridden": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<sstephenson@gmail.com>"
escape: (string) ->
string.toUpperCase()
test.same "<SSTEPHENSON@GMAIL.COM>", output
test.done()
"'undefined' is never coerced into a string": (test) ->
test.same "", eco.render "<%= @x %>"
test.same "", eco.render "<%= @safe @x %>"
test.same "", eco.render "<%- @x %>"
test.done()
"rendering an escaped <%": (test) ->
test.same "<%", eco.render "<%%"
test.done()
"requiring eco templates as modules": (test) ->
hello = require __dirname + "/fixtures/hello.eco"
test.ok typeof hello is "function"
test.same fixture("hello.out.1"), hello name: "Sam"
test.done()
| 70043 | eco = require ".."
{fixture} = require "./lib/fixtures"
items = [
{ name: "<NAME>", price: "5.25"},
{ name: "<NAME>", price: "6.25" }
]
module.exports =
"eco() caches compiled templates": (test) ->
render = eco fixture("hello.eco")
test.same render, eco fixture("hello.eco")
test.done()
"cache can be disabled": (test) ->
cache = eco.cache
eco.cache = false
render = eco fixture("hello.eco")
test.ok render isnt eco fixture("hello.eco")
eco.cache = cache
test.done()
"eco.preprocess": (test) ->
test.same fixture("hello.coffee"), eco.preprocess fixture("hello.eco")
test.done()
"eco.precompile": (test) ->
js = eco.precompile "Hello <%= @name %>"
test.ok typeof js is "string"
fn = eval "(#{js})"
test.ok typeof fn is "function"
test.same "Hello <NAME>", fn name: "<NAME>"
test.done()
"compiling hello.eco": (test) ->
render = eco.compile fixture("hello.eco")
test.same fixture("hello.out.1"), render name: "<NAME>"
test.done()
"compiled templates can be reused": (test) ->
render = eco.compile "Hello <%= @name %>"
test.same "Hello <NAME>", render name: "<NAME>"
test.same "Hello <NAME>", render name: "<NAME>"
test.done()
"eco.compile bypasses cache": (test) ->
test.ok eco.cache
render = eco.compile fixture("hello.eco")
test.ok render isnt eco.compile fixture("hello.eco")
test.done()
"rendering hello.eco": (test) ->
output = eco.render fixture("hello.eco"), name: "<NAME>"
test.same fixture("hello.out.1"), output
test.done()
"rendering hello.eco without a name throws an exception": (test) ->
test.expect 1
try
eco.render fixture("hello.eco")
catch err
test.ok err
test.done()
"rendering projects.eco with empty projects array": (test) ->
output = eco.render fixture("projects.eco"), projects: []
test.same fixture("projects.out.1"), output
test.done()
"rendering projects.eco with multiple projects": (test) ->
output = eco.render fixture("projects.eco"), projects: [
{ name: "PowerTMS Active Shipments Page Redesign", url: "/projects/1" },
{ name: "SCU Intranet", url: "/projects/2", description: "<p><em>On hold</em></p>" },
{ name: "Sales Template", url: "/projects/3" }
]
test.same fixture("projects.out.2"), output
test.done()
"rendering helpers.eco": (test) ->
output = eco.render fixture("helpers.eco"),
items: items
contentTag: (tagName, attributes, callback) ->
attrs = (" #{name}=\"#{value}\"" for name, value of attributes)
@safe "<#{tagName}#{attrs.join("")}>#{callback()}</#{tagName}>"
test.same fixture("helpers.out.1"), output
test.done()
"rendering capture.eco": (test) ->
output = eco.render fixture("capture.eco"), items: items
test.same fixture("capture.out.1"), output
test.done()
"HTML is escaped by default": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<<EMAIL>>"
test.same "<<EMAIL>>", output
test.done()
"unescaped HTML can be rendered from a helper": (test) ->
output = eco.render "<%= @helper() %>",
helper: -> @safe "<boo>"
test.same "<boo>", output
test.done()
"escape method can be overridden": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<<EMAIL>>"
escape: (string) ->
string.toUpperCase()
test.same "<<EMAIL>>", output
test.done()
"'undefined' is never coerced into a string": (test) ->
test.same "", eco.render "<%= @x %>"
test.same "", eco.render "<%= @safe @x %>"
test.same "", eco.render "<%- @x %>"
test.done()
"rendering an escaped <%": (test) ->
test.same "<%", eco.render "<%%"
test.done()
"requiring eco templates as modules": (test) ->
hello = require __dirname + "/fixtures/hello.eco"
test.ok typeof hello is "function"
test.same fixture("hello.out.1"), hello name: "<NAME>"
test.done()
| true | eco = require ".."
{fixture} = require "./lib/fixtures"
items = [
{ name: "PI:NAME:<NAME>END_PI", price: "5.25"},
{ name: "PI:NAME:<NAME>END_PI", price: "6.25" }
]
module.exports =
"eco() caches compiled templates": (test) ->
render = eco fixture("hello.eco")
test.same render, eco fixture("hello.eco")
test.done()
"cache can be disabled": (test) ->
cache = eco.cache
eco.cache = false
render = eco fixture("hello.eco")
test.ok render isnt eco fixture("hello.eco")
eco.cache = cache
test.done()
"eco.preprocess": (test) ->
test.same fixture("hello.coffee"), eco.preprocess fixture("hello.eco")
test.done()
"eco.precompile": (test) ->
js = eco.precompile "Hello <%= @name %>"
test.ok typeof js is "string"
fn = eval "(#{js})"
test.ok typeof fn is "function"
test.same "Hello PI:NAME:<NAME>END_PI", fn name: "PI:NAME:<NAME>END_PI"
test.done()
"compiling hello.eco": (test) ->
render = eco.compile fixture("hello.eco")
test.same fixture("hello.out.1"), render name: "PI:NAME:<NAME>END_PI"
test.done()
"compiled templates can be reused": (test) ->
render = eco.compile "Hello <%= @name %>"
test.same "Hello PI:NAME:<NAME>END_PI", render name: "PI:NAME:<NAME>END_PI"
test.same "Hello PI:NAME:<NAME>END_PI", render name: "PI:NAME:<NAME>END_PI"
test.done()
"eco.compile bypasses cache": (test) ->
test.ok eco.cache
render = eco.compile fixture("hello.eco")
test.ok render isnt eco.compile fixture("hello.eco")
test.done()
"rendering hello.eco": (test) ->
output = eco.render fixture("hello.eco"), name: "PI:NAME:<NAME>END_PI"
test.same fixture("hello.out.1"), output
test.done()
"rendering hello.eco without a name throws an exception": (test) ->
test.expect 1
try
eco.render fixture("hello.eco")
catch err
test.ok err
test.done()
"rendering projects.eco with empty projects array": (test) ->
output = eco.render fixture("projects.eco"), projects: []
test.same fixture("projects.out.1"), output
test.done()
"rendering projects.eco with multiple projects": (test) ->
output = eco.render fixture("projects.eco"), projects: [
{ name: "PowerTMS Active Shipments Page Redesign", url: "/projects/1" },
{ name: "SCU Intranet", url: "/projects/2", description: "<p><em>On hold</em></p>" },
{ name: "Sales Template", url: "/projects/3" }
]
test.same fixture("projects.out.2"), output
test.done()
"rendering helpers.eco": (test) ->
output = eco.render fixture("helpers.eco"),
items: items
contentTag: (tagName, attributes, callback) ->
attrs = (" #{name}=\"#{value}\"" for name, value of attributes)
@safe "<#{tagName}#{attrs.join("")}>#{callback()}</#{tagName}>"
test.same fixture("helpers.out.1"), output
test.done()
"rendering capture.eco": (test) ->
output = eco.render fixture("capture.eco"), items: items
test.same fixture("capture.out.1"), output
test.done()
"HTML is escaped by default": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<PI:EMAIL:<EMAIL>END_PI>"
test.same "<PI:EMAIL:<EMAIL>END_PI>", output
test.done()
"unescaped HTML can be rendered from a helper": (test) ->
output = eco.render "<%= @helper() %>",
helper: -> @safe "<boo>"
test.same "<boo>", output
test.done()
"escape method can be overridden": (test) ->
output = eco.render "<%= @emailAddress %>",
emailAddress: "<PI:EMAIL:<EMAIL>END_PI>"
escape: (string) ->
string.toUpperCase()
test.same "<PI:EMAIL:<EMAIL>END_PI>", output
test.done()
"'undefined' is never coerced into a string": (test) ->
test.same "", eco.render "<%= @x %>"
test.same "", eco.render "<%= @safe @x %>"
test.same "", eco.render "<%- @x %>"
test.done()
"rendering an escaped <%": (test) ->
test.same "<%", eco.render "<%%"
test.done()
"requiring eco templates as modules": (test) ->
hello = require __dirname + "/fixtures/hello.eco"
test.ok typeof hello is "function"
test.same fixture("hello.out.1"), hello name: "PI:NAME:<NAME>END_PI"
test.done()
|
[
{
"context": " elements = [\n {type: 'email', value:'abä@de.com', 'minlength': 10}\n ]\n\n helper.appendAn",
"end": 1957,
"score": 0.9998487830162048,
"start": 1947,
"tag": "EMAIL",
"value": "abä@de.com"
},
{
"context": "ator.config.messages.email\n\n $element.val('abc@de.de')\n validator.validateOne($element)\n\n ",
"end": 2276,
"score": 0.9998053312301636,
"start": 2267,
"tag": "EMAIL",
"value": "abc@de.de"
}
] | spec/hint.spec.coffee | creative-workflow/jquery.input.validator | 0 |
describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
hintSelector = ".#{validator.config.classes.hint}"
# override -> no waiting for dom changes
validator.config.handler.onShowHint = validator.config.handler.onShowHintForTesting
describe "hint", ->
it 'gets added to invalid inputs', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$element = $('input', $elements).first()
expect($(hintSelector, $elements).length).toBe 0
helper.expectInValid(validator.validateOne($element))
expect($(hintSelector, $elements).length).toBe 1
)
describe "reset", ->
it 'gets removed if input gets valid', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
expect($(hintSelector, $elements).length).toBe 0
validator.validate($elements)
expect($(hintSelector, $elements).length).toBe 2
validator.reset($elements)
expect($(hintSelector, $elements).length).toBe 0
)
it 'shows the default message', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe validator.config.messages.email
)
it 'shows the data message', ->
elements = [
{type: 'email', value:'invalid', 'data-msg-email': 'hint text'}
]
helper.appendAndCallback(elements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe 'hint text'
)
it 'changes the message', ->
elements = [
{type: 'email', value:'abä@de.com', 'minlength': 10}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.email
$element.val('abc@de.de')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
)
it 'show valid message', ->
elements = [
{type: 'text', value:'ab', 'minlength': 3, 'data-msg-valid': 'OK!'}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
$element.val('not more minlength')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe 'OK!'
)
| 209001 |
describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
hintSelector = ".#{validator.config.classes.hint}"
# override -> no waiting for dom changes
validator.config.handler.onShowHint = validator.config.handler.onShowHintForTesting
describe "hint", ->
it 'gets added to invalid inputs', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$element = $('input', $elements).first()
expect($(hintSelector, $elements).length).toBe 0
helper.expectInValid(validator.validateOne($element))
expect($(hintSelector, $elements).length).toBe 1
)
describe "reset", ->
it 'gets removed if input gets valid', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
expect($(hintSelector, $elements).length).toBe 0
validator.validate($elements)
expect($(hintSelector, $elements).length).toBe 2
validator.reset($elements)
expect($(hintSelector, $elements).length).toBe 0
)
it 'shows the default message', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe validator.config.messages.email
)
it 'shows the data message', ->
elements = [
{type: 'email', value:'invalid', 'data-msg-email': 'hint text'}
]
helper.appendAndCallback(elements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe 'hint text'
)
it 'changes the message', ->
elements = [
{type: 'email', value:'<EMAIL>', 'minlength': 10}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.email
$element.val('<EMAIL>')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
)
it 'show valid message', ->
elements = [
{type: 'text', value:'ab', 'minlength': 3, 'data-msg-valid': 'OK!'}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
$element.val('not more minlength')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe 'OK!'
)
| true |
describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
hintSelector = ".#{validator.config.classes.hint}"
# override -> no waiting for dom changes
validator.config.handler.onShowHint = validator.config.handler.onShowHintForTesting
describe "hint", ->
it 'gets added to invalid inputs', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$element = $('input', $elements).first()
expect($(hintSelector, $elements).length).toBe 0
helper.expectInValid(validator.validateOne($element))
expect($(hintSelector, $elements).length).toBe 1
)
describe "reset", ->
it 'gets removed if input gets valid', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
expect($(hintSelector, $elements).length).toBe 0
validator.validate($elements)
expect($(hintSelector, $elements).length).toBe 2
validator.reset($elements)
expect($(hintSelector, $elements).length).toBe 0
)
it 'shows the default message', ->
helper.appendAndCallback(helper.invalidElements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe validator.config.messages.email
)
it 'shows the data message', ->
elements = [
{type: 'email', value:'invalid', 'data-msg-email': 'hint text'}
]
helper.appendAndCallback(elements, ($elements) ->
$input = $('input', $elements).first()
validator.validateOne($input)
$label = $(hintSelector, $elements)
expect($label.length).toBe 1
expect($label.text()).toBe 'hint text'
)
it 'changes the message', ->
elements = [
{type: 'email', value:'PI:EMAIL:<EMAIL>END_PI', 'minlength': 10}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.email
$element.val('PI:EMAIL:<EMAIL>END_PI')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
)
it 'show valid message', ->
elements = [
{type: 'text', value:'ab', 'minlength': 3, 'data-msg-valid': 'OK!'}
]
helper.appendAndCallback(elements, ($elements) =>
$element = $('input', $elements).first()
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe validator.config.messages.minlength
$element.val('not more minlength')
validator.validateOne($element)
$label = $(hintSelector, $elements)
expect($label.text()).toBe 'OK!'
)
|
[
{
"context": "###\r\n\r\ngas-manager\r\nhttps://github.com/soundTricker/gas-manager\r\n\r\nCopyright (c) 2013 Keisuke Oohashi",
"end": 51,
"score": 0.9975616335868835,
"start": 39,
"tag": "USERNAME",
"value": "soundTricker"
},
{
"context": "com/soundTricker/gas-manager\r\n\r\nCopyright (c) 2013 Keisuke Oohashi\r\nLicensed under the MIT license.\r\n\r\n###\r\n\r\n'use s",
"end": 101,
"score": 0.999882161617279,
"start": 86,
"tag": "NAME",
"value": "Keisuke Oohashi"
}
] | src/lib/commands/upload-command.coffee | unau/gas-minus-minus | 0 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 Keisuke Oohashi
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
exports.upload = (options)->
program = @
config = util.loadConfig(program)
manager = new Manager(config)
fileId = program.fileId || config[program.env].fileId
if !fileId
throw new Error(
"upload command is given fileId in config file or -f {fileId}"
)
if options.src
config[program.env] =
fileId : fileId
files : options.src
if !config[program.env]?.files
throw new Error(
"There is no [#{program.env}] enviroment setting at config file"
)
async.waterfall([
(cb)->
manager.getProject fileId, cb
(project, response, cb)->
readFiles = {}
for file in project.getFiles()
if !config[program.env].files[file.name]
project.deleteFile(file.name) if options.force
continue
readFiles[file.name] =
name : file.name
setting : config[program.env].files[file.name]
exist : yes
if options.force
for name,file of config[program.env].files
if !readFiles[name]
readFiles[name] =
name : name
setting : file
exist : no
async.parallel(
do (tasks = []) ->
for name,readFile of readFiles
tasks.push(
do (file = readFile) ->
(callback)->
fs.readFile(path.resolve(file.setting.path)
,encoding : options.encoding
,(err, source)->
return callback(err) if err
if file.exist
project.changeFile(name, {
type : file.setting.type
source : source
})
else
project.addFile(name, {
type : file.setting.type
source : source
})
callback(null)
)
)
tasks
,(err)->
throw err if err
cb(null, project)
)
(project,cb)->
project.deploy(cb)
],(err, project)->
throw err if err
console.log "Success uploading for #{project.filename}"
)
| 133338 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
exports.upload = (options)->
program = @
config = util.loadConfig(program)
manager = new Manager(config)
fileId = program.fileId || config[program.env].fileId
if !fileId
throw new Error(
"upload command is given fileId in config file or -f {fileId}"
)
if options.src
config[program.env] =
fileId : fileId
files : options.src
if !config[program.env]?.files
throw new Error(
"There is no [#{program.env}] enviroment setting at config file"
)
async.waterfall([
(cb)->
manager.getProject fileId, cb
(project, response, cb)->
readFiles = {}
for file in project.getFiles()
if !config[program.env].files[file.name]
project.deleteFile(file.name) if options.force
continue
readFiles[file.name] =
name : file.name
setting : config[program.env].files[file.name]
exist : yes
if options.force
for name,file of config[program.env].files
if !readFiles[name]
readFiles[name] =
name : name
setting : file
exist : no
async.parallel(
do (tasks = []) ->
for name,readFile of readFiles
tasks.push(
do (file = readFile) ->
(callback)->
fs.readFile(path.resolve(file.setting.path)
,encoding : options.encoding
,(err, source)->
return callback(err) if err
if file.exist
project.changeFile(name, {
type : file.setting.type
source : source
})
else
project.addFile(name, {
type : file.setting.type
source : source
})
callback(null)
)
)
tasks
,(err)->
throw err if err
cb(null, project)
)
(project,cb)->
project.deploy(cb)
],(err, project)->
throw err if err
console.log "Success uploading for #{project.filename}"
)
| true | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
exports.upload = (options)->
program = @
config = util.loadConfig(program)
manager = new Manager(config)
fileId = program.fileId || config[program.env].fileId
if !fileId
throw new Error(
"upload command is given fileId in config file or -f {fileId}"
)
if options.src
config[program.env] =
fileId : fileId
files : options.src
if !config[program.env]?.files
throw new Error(
"There is no [#{program.env}] enviroment setting at config file"
)
async.waterfall([
(cb)->
manager.getProject fileId, cb
(project, response, cb)->
readFiles = {}
for file in project.getFiles()
if !config[program.env].files[file.name]
project.deleteFile(file.name) if options.force
continue
readFiles[file.name] =
name : file.name
setting : config[program.env].files[file.name]
exist : yes
if options.force
for name,file of config[program.env].files
if !readFiles[name]
readFiles[name] =
name : name
setting : file
exist : no
async.parallel(
do (tasks = []) ->
for name,readFile of readFiles
tasks.push(
do (file = readFile) ->
(callback)->
fs.readFile(path.resolve(file.setting.path)
,encoding : options.encoding
,(err, source)->
return callback(err) if err
if file.exist
project.changeFile(name, {
type : file.setting.type
source : source
})
else
project.addFile(name, {
type : file.setting.type
source : source
})
callback(null)
)
)
tasks
,(err)->
throw err if err
cb(null, project)
)
(project,cb)->
project.deploy(cb)
],(err, project)->
throw err if err
console.log "Success uploading for #{project.filename}"
)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991371035575867,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-stream-writev.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.
run = ->
t = queue.pop()
if t
test t[0], t[1], t[2], run
else
console.log "ok"
return
test = (decode, uncork, multi, next) ->
cnt = (msg) ->
expectCount++
expect = expectCount
called = false
(er) ->
throw er if er
called = true
counter++
assert.equal counter, expect
return
console.log "# decode=%j uncork=%j multi=%j", decode, uncork, multi
counter = 0
expectCount = 0
w = new stream.Writable(decodeStrings: decode)
w._write = (chunk, e, cb) ->
assert false, "Should not call _write"
return
expectChunks = (if decode then [
{
encoding: "buffer"
chunk: [
104
101
108
108
111
44
32
]
}
{
encoding: "buffer"
chunk: [
119
111
114
108
100
]
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "buffer"
chunk: [
10
97
110
100
32
116
104
101
110
46
46
46
]
}
{
encoding: "buffer"
chunk: [
250
206
190
167
222
173
190
239
222
202
251
173
]
}
] else [
{
encoding: "ascii"
chunk: "hello, "
}
{
encoding: "utf8"
chunk: "world"
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "binary"
chunk: "\nand then..."
}
{
encoding: "hex"
chunk: "facebea7deadbeefdecafbad"
}
])
actualChunks = undefined
w._writev = (chunks, cb) ->
actualChunks = chunks.map((chunk) ->
encoding: chunk.encoding
chunk: (if Buffer.isBuffer(chunk.chunk) then Array::slice.call(chunk.chunk) else chunk.chunk)
)
cb()
return
w.cork()
w.write "hello, ", "ascii", cnt("hello")
w.write "world", "utf8", cnt("world")
w.cork() if multi
w.write new Buffer("!"), "buffer", cnt("!")
w.write "\nand then...", "binary", cnt("and then")
w.uncork() if multi
w.write "facebea7deadbeefdecafbad", "hex", cnt("hex")
w.uncork() if uncork
w.end cnt("end")
w.on "finish", ->
# make sure finish comes after all the write cb
cnt("finish")()
assert.deepEqual expectChunks, actualChunks
next()
return
return
common = require("../common")
assert = require("assert")
stream = require("stream")
queue = []
decode = 0
while decode < 2
uncork = 0
while uncork < 2
multi = 0
while multi < 2
queue.push [
!!decode
!!uncork
!!multi
]
multi++
uncork++
decode++
run()
| 171256 | # 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.
run = ->
t = queue.pop()
if t
test t[0], t[1], t[2], run
else
console.log "ok"
return
test = (decode, uncork, multi, next) ->
cnt = (msg) ->
expectCount++
expect = expectCount
called = false
(er) ->
throw er if er
called = true
counter++
assert.equal counter, expect
return
console.log "# decode=%j uncork=%j multi=%j", decode, uncork, multi
counter = 0
expectCount = 0
w = new stream.Writable(decodeStrings: decode)
w._write = (chunk, e, cb) ->
assert false, "Should not call _write"
return
expectChunks = (if decode then [
{
encoding: "buffer"
chunk: [
104
101
108
108
111
44
32
]
}
{
encoding: "buffer"
chunk: [
119
111
114
108
100
]
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "buffer"
chunk: [
10
97
110
100
32
116
104
101
110
46
46
46
]
}
{
encoding: "buffer"
chunk: [
250
206
190
167
222
173
190
239
222
202
251
173
]
}
] else [
{
encoding: "ascii"
chunk: "hello, "
}
{
encoding: "utf8"
chunk: "world"
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "binary"
chunk: "\nand then..."
}
{
encoding: "hex"
chunk: "facebea7deadbeefdecafbad"
}
])
actualChunks = undefined
w._writev = (chunks, cb) ->
actualChunks = chunks.map((chunk) ->
encoding: chunk.encoding
chunk: (if Buffer.isBuffer(chunk.chunk) then Array::slice.call(chunk.chunk) else chunk.chunk)
)
cb()
return
w.cork()
w.write "hello, ", "ascii", cnt("hello")
w.write "world", "utf8", cnt("world")
w.cork() if multi
w.write new Buffer("!"), "buffer", cnt("!")
w.write "\nand then...", "binary", cnt("and then")
w.uncork() if multi
w.write "facebea7deadbeefdecafbad", "hex", cnt("hex")
w.uncork() if uncork
w.end cnt("end")
w.on "finish", ->
# make sure finish comes after all the write cb
cnt("finish")()
assert.deepEqual expectChunks, actualChunks
next()
return
return
common = require("../common")
assert = require("assert")
stream = require("stream")
queue = []
decode = 0
while decode < 2
uncork = 0
while uncork < 2
multi = 0
while multi < 2
queue.push [
!!decode
!!uncork
!!multi
]
multi++
uncork++
decode++
run()
| 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.
run = ->
t = queue.pop()
if t
test t[0], t[1], t[2], run
else
console.log "ok"
return
test = (decode, uncork, multi, next) ->
cnt = (msg) ->
expectCount++
expect = expectCount
called = false
(er) ->
throw er if er
called = true
counter++
assert.equal counter, expect
return
console.log "# decode=%j uncork=%j multi=%j", decode, uncork, multi
counter = 0
expectCount = 0
w = new stream.Writable(decodeStrings: decode)
w._write = (chunk, e, cb) ->
assert false, "Should not call _write"
return
expectChunks = (if decode then [
{
encoding: "buffer"
chunk: [
104
101
108
108
111
44
32
]
}
{
encoding: "buffer"
chunk: [
119
111
114
108
100
]
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "buffer"
chunk: [
10
97
110
100
32
116
104
101
110
46
46
46
]
}
{
encoding: "buffer"
chunk: [
250
206
190
167
222
173
190
239
222
202
251
173
]
}
] else [
{
encoding: "ascii"
chunk: "hello, "
}
{
encoding: "utf8"
chunk: "world"
}
{
encoding: "buffer"
chunk: [33]
}
{
encoding: "binary"
chunk: "\nand then..."
}
{
encoding: "hex"
chunk: "facebea7deadbeefdecafbad"
}
])
actualChunks = undefined
w._writev = (chunks, cb) ->
actualChunks = chunks.map((chunk) ->
encoding: chunk.encoding
chunk: (if Buffer.isBuffer(chunk.chunk) then Array::slice.call(chunk.chunk) else chunk.chunk)
)
cb()
return
w.cork()
w.write "hello, ", "ascii", cnt("hello")
w.write "world", "utf8", cnt("world")
w.cork() if multi
w.write new Buffer("!"), "buffer", cnt("!")
w.write "\nand then...", "binary", cnt("and then")
w.uncork() if multi
w.write "facebea7deadbeefdecafbad", "hex", cnt("hex")
w.uncork() if uncork
w.end cnt("end")
w.on "finish", ->
# make sure finish comes after all the write cb
cnt("finish")()
assert.deepEqual expectChunks, actualChunks
next()
return
return
common = require("../common")
assert = require("assert")
stream = require("stream")
queue = []
decode = 0
while decode < 2
uncork = 0
while uncork < 2
multi = 0
while multi < 2
queue.push [
!!decode
!!uncork
!!multi
]
multi++
uncork++
decode++
run()
|
[
{
"context": " @element.appendChild(message)\n\n #@resultsBox.style.display = 'block'\n #@errorElement.style.d",
"end": 882,
"score": 0.7112994194030762,
"start": 882,
"tag": "EMAIL",
"value": ""
},
{
"context": "ocument.createElement('div')\n\n #@errorElement.style.display = 'block'\n #@resultsElement.sty",
"end": 1335,
"score": 0.5995154976844788,
"start": 1335,
"tag": "EMAIL",
"value": ""
}
] | lib/postgres-autocomplete-view.coffee | rikard2/Postgres-Autocomplete | 0 | module.exports =
class PostgresAutocompleteView
constructor: (serializedState) ->
# Create root element
@element = document.createElement('div')
@element.classList.add('postgres-autocomplete')
# Create message element
message = document.createElement('div')
message.textContent = "The PostgresAutocomplete package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getResultsElement: (results, error) ->
message = document.createElement('div')
message.textContent = "The PostgresHelperCoffee package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
#@resultsBox.style.display = 'block'
#@errorElement.style.display = 'none'
if @resultsBox
@resultsBox.childNodes.length = 0
else
@resultsBox = document.createElement('div')
@resultsBox.classList.add('postgres-helper-coffee-results')
@resultsBox.textContent = ""
if error
if @errorElement
@errorElement.childNodes.length = 0
else
@errorElement = document.createElement('div')
#@errorElement.style.display = 'block'
#@resultsElement.style.display = 'none'
@errorElement.classList.add('postgres-helper-coffee-error')
@errorElement.textContent = error
return @errorElement
table = document.createElement('table')
table.classList.add('table')
tr = document.createElement('tr')
for f in results.fields
th = document.createElement('th')
th.textContent = f
tr.appendChild(th)
table.appendChild(tr)
for row in results.rows
tr = document.createElement('tr')
for c in row
td = document.createElement('td')
td.textContent = c
tr.appendChild(td)
table.appendChild(tr)
@resultsBox.appendChild(table)
return @resultsBox
| 199998 | module.exports =
class PostgresAutocompleteView
constructor: (serializedState) ->
# Create root element
@element = document.createElement('div')
@element.classList.add('postgres-autocomplete')
# Create message element
message = document.createElement('div')
message.textContent = "The PostgresAutocomplete package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getResultsElement: (results, error) ->
message = document.createElement('div')
message.textContent = "The PostgresHelperCoffee package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
#@resultsBox<EMAIL>.style.display = 'block'
#@errorElement.style.display = 'none'
if @resultsBox
@resultsBox.childNodes.length = 0
else
@resultsBox = document.createElement('div')
@resultsBox.classList.add('postgres-helper-coffee-results')
@resultsBox.textContent = ""
if error
if @errorElement
@errorElement.childNodes.length = 0
else
@errorElement = document.createElement('div')
#@errorElement<EMAIL>.style.display = 'block'
#@resultsElement.style.display = 'none'
@errorElement.classList.add('postgres-helper-coffee-error')
@errorElement.textContent = error
return @errorElement
table = document.createElement('table')
table.classList.add('table')
tr = document.createElement('tr')
for f in results.fields
th = document.createElement('th')
th.textContent = f
tr.appendChild(th)
table.appendChild(tr)
for row in results.rows
tr = document.createElement('tr')
for c in row
td = document.createElement('td')
td.textContent = c
tr.appendChild(td)
table.appendChild(tr)
@resultsBox.appendChild(table)
return @resultsBox
| true | module.exports =
class PostgresAutocompleteView
constructor: (serializedState) ->
# Create root element
@element = document.createElement('div')
@element.classList.add('postgres-autocomplete')
# Create message element
message = document.createElement('div')
message.textContent = "The PostgresAutocomplete package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getResultsElement: (results, error) ->
message = document.createElement('div')
message.textContent = "The PostgresHelperCoffee package is Alive! It's ALIVE!"
message.classList.add('message')
@element.appendChild(message)
#@resultsBoxPI:EMAIL:<EMAIL>END_PI.style.display = 'block'
#@errorElement.style.display = 'none'
if @resultsBox
@resultsBox.childNodes.length = 0
else
@resultsBox = document.createElement('div')
@resultsBox.classList.add('postgres-helper-coffee-results')
@resultsBox.textContent = ""
if error
if @errorElement
@errorElement.childNodes.length = 0
else
@errorElement = document.createElement('div')
#@errorElementPI:EMAIL:<EMAIL>END_PI.style.display = 'block'
#@resultsElement.style.display = 'none'
@errorElement.classList.add('postgres-helper-coffee-error')
@errorElement.textContent = error
return @errorElement
table = document.createElement('table')
table.classList.add('table')
tr = document.createElement('tr')
for f in results.fields
th = document.createElement('th')
th.textContent = f
tr.appendChild(th)
table.appendChild(tr)
for row in results.rows
tr = document.createElement('tr')
for c in row
td = document.createElement('td')
td.textContent = c
tr.appendChild(td)
table.appendChild(tr)
@resultsBox.appendChild(table)
return @resultsBox
|
[
{
"context": "'use strict'\n\n\n# Key\n#\n# @copyright Andrew Lawson 2012\n# @see http://github.com/adlawson/key\n# @see",
"end": 49,
"score": 0.9998748898506165,
"start": 36,
"tag": "NAME",
"value": "Andrew Lawson"
},
{
"context": "right Andrew Lawson 2012\n# @see http://github.com/adlawson/key\n# @see http://npmjs.org/package/key\n# @see ht",
"end": 88,
"score": 0.9996761679649353,
"start": 80,
"tag": "USERNAME",
"value": "adlawson"
}
] | src/code/keypad.coffee | adlawson/coffee-key | 1 | 'use strict'
# Key
#
# @copyright Andrew Lawson 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
enter = require './special'
# Definitions
keypad = {
'0': ref '0', 96
'1': ref '1', 97
'2': ref '2', 98
'3': ref '3', 99
'4': ref '4', 100
'5': ref '5', 101
'6': ref '6', 102
'7': ref '7', 103
'8': ref '8', 104
'9': ref '9', 105
multiply: ref 'Multiply', 106
plus: ref 'Plus', 107
minus: ref 'Minus', 109
decimal: ref 'Decimal point', 110
divide: ref 'Divide', 111
enter: special.enter
}
# Exports
module.exports = keypad
| 149598 | 'use strict'
# Key
#
# @copyright <NAME> 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
enter = require './special'
# Definitions
keypad = {
'0': ref '0', 96
'1': ref '1', 97
'2': ref '2', 98
'3': ref '3', 99
'4': ref '4', 100
'5': ref '5', 101
'6': ref '6', 102
'7': ref '7', 103
'8': ref '8', 104
'9': ref '9', 105
multiply: ref 'Multiply', 106
plus: ref 'Plus', 107
minus: ref 'Minus', 109
decimal: ref 'Decimal point', 110
divide: ref 'Divide', 111
enter: special.enter
}
# Exports
module.exports = keypad
| true | 'use strict'
# Key
#
# @copyright PI:NAME:<NAME>END_PI 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
enter = require './special'
# Definitions
keypad = {
'0': ref '0', 96
'1': ref '1', 97
'2': ref '2', 98
'3': ref '3', 99
'4': ref '4', 100
'5': ref '5', 101
'6': ref '6', 102
'7': ref '7', 103
'8': ref '8', 104
'9': ref '9', 105
multiply: ref 'Multiply', 106
plus: ref 'Plus', 107
minus: ref 'Minus', 109
decimal: ref 'Decimal point', 110
divide: ref 'Divide', 111
enter: special.enter
}
# Exports
module.exports = keypad
|
[
{
"context": " {\n 'requiredData': {\n 'user': [\n 'username'\n ],\n 'group': [\n 'slug'\n ]",
"end": 671,
"score": 0.9995728731155396,
"start": 663,
"tag": "USERNAME",
"value": "username"
},
{
"context": "6da2'\n },\n 'credentials': {\n 'aws': [\n 'ec7b8692888f0043e265d558d61818be'\n ]\n },\n '_id': '56f9294526efa37e25019dfc',\n",
"end": 2253,
"score": 0.9677252173423767,
"start": 2221,
"tag": "KEY",
"value": "ec7b8692888f0043e265d558d61818be"
}
] | client/mocks/mock.jstack.coffee | ezgikaysi/koding | 1 | module.exports = {
'watchers': {},
'bongo_': {
'constructorName': 'JStackTemplate',
'instanceId': '2a68ab44e407c1cca60aada3ea98cebb'
},
'machines': [
{
'label': 'example',
'provider': 'aws',
'region': 'us-east-1',
'source_ami': 'ami-cf35f3a4',
'instanceType': 't2.nano',
'provisioners': []
}
],
'title': 'STACK 1',
'description': '##### Readme text for this stack template\n\nYou can write down a readme text for new users.\nThis text will be shown when they want to use this stack.\nYou can use markdown with the readme content.\n\n',
'config': {
'requiredData': {
'user': [
'username'
],
'group': [
'slug'
]
},
'requiredProviders': [
'aws',
'koding'
],
'groupStack': false,
'verified': true
},
'accessLevel': 'group',
'originId': '56e147d1aedf91e0087d67aa',
'meta': {
'data': {
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'group': 'turunc-team-hehe16',
'template': {
'content': '{"provider":{"aws":{"access_key":"${var.aws_access_key}","secret_key":"${var.aws_secret_key}"}},"resource":{"aws_instance":{"example":{"tags":{"Name":"${var.koding_user_username}-${var.koding_group_slug}"},"instance_type":"t2.nano","ami":""}}}}',
'details': {},
'rawContent': '# Here is your stack preview\n# You can make advanced changes like modifying your VM,\n# installing packages, and running shell commands.\n\nprovider:\n aws:\n access_key: '${var.aws_access_key}'\n secret_key: '${var.aws_secret_key}'\nresource:\n aws_instance:\n example:\n tags:\n Name: '${var.koding_user_username}-${var.koding_group_slug}'\n instance_type: t2.nano\n ami: ''\n',
'sum': '0857bea2903b56d1b530f120b8445a6074cb6da2'
},
'credentials': {
'aws': [
'ec7b8692888f0043e265d558d61818be'
]
},
'_id': '56f9294526efa37e25019dfc',
'isDefault': false,
'inUse': true
}
| 60573 | module.exports = {
'watchers': {},
'bongo_': {
'constructorName': 'JStackTemplate',
'instanceId': '2a68ab44e407c1cca60aada3ea98cebb'
},
'machines': [
{
'label': 'example',
'provider': 'aws',
'region': 'us-east-1',
'source_ami': 'ami-cf35f3a4',
'instanceType': 't2.nano',
'provisioners': []
}
],
'title': 'STACK 1',
'description': '##### Readme text for this stack template\n\nYou can write down a readme text for new users.\nThis text will be shown when they want to use this stack.\nYou can use markdown with the readme content.\n\n',
'config': {
'requiredData': {
'user': [
'username'
],
'group': [
'slug'
]
},
'requiredProviders': [
'aws',
'koding'
],
'groupStack': false,
'verified': true
},
'accessLevel': 'group',
'originId': '56e147d1aedf91e0087d67aa',
'meta': {
'data': {
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'group': 'turunc-team-hehe16',
'template': {
'content': '{"provider":{"aws":{"access_key":"${var.aws_access_key}","secret_key":"${var.aws_secret_key}"}},"resource":{"aws_instance":{"example":{"tags":{"Name":"${var.koding_user_username}-${var.koding_group_slug}"},"instance_type":"t2.nano","ami":""}}}}',
'details': {},
'rawContent': '# Here is your stack preview\n# You can make advanced changes like modifying your VM,\n# installing packages, and running shell commands.\n\nprovider:\n aws:\n access_key: '${var.aws_access_key}'\n secret_key: '${var.aws_secret_key}'\nresource:\n aws_instance:\n example:\n tags:\n Name: '${var.koding_user_username}-${var.koding_group_slug}'\n instance_type: t2.nano\n ami: ''\n',
'sum': '0857bea2903b56d1b530f120b8445a6074cb6da2'
},
'credentials': {
'aws': [
'<KEY>'
]
},
'_id': '56f9294526efa37e25019dfc',
'isDefault': false,
'inUse': true
}
| true | module.exports = {
'watchers': {},
'bongo_': {
'constructorName': 'JStackTemplate',
'instanceId': '2a68ab44e407c1cca60aada3ea98cebb'
},
'machines': [
{
'label': 'example',
'provider': 'aws',
'region': 'us-east-1',
'source_ami': 'ami-cf35f3a4',
'instanceType': 't2.nano',
'provisioners': []
}
],
'title': 'STACK 1',
'description': '##### Readme text for this stack template\n\nYou can write down a readme text for new users.\nThis text will be shown when they want to use this stack.\nYou can use markdown with the readme content.\n\n',
'config': {
'requiredData': {
'user': [
'username'
],
'group': [
'slug'
]
},
'requiredProviders': [
'aws',
'koding'
],
'groupStack': false,
'verified': true
},
'accessLevel': 'group',
'originId': '56e147d1aedf91e0087d67aa',
'meta': {
'data': {
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'createdAt': '2016-03-28T12:53:25.509Z',
'modifiedAt': '2016-03-28T12:53:25.509Z',
'likes': 0
},
'group': 'turunc-team-hehe16',
'template': {
'content': '{"provider":{"aws":{"access_key":"${var.aws_access_key}","secret_key":"${var.aws_secret_key}"}},"resource":{"aws_instance":{"example":{"tags":{"Name":"${var.koding_user_username}-${var.koding_group_slug}"},"instance_type":"t2.nano","ami":""}}}}',
'details': {},
'rawContent': '# Here is your stack preview\n# You can make advanced changes like modifying your VM,\n# installing packages, and running shell commands.\n\nprovider:\n aws:\n access_key: '${var.aws_access_key}'\n secret_key: '${var.aws_secret_key}'\nresource:\n aws_instance:\n example:\n tags:\n Name: '${var.koding_user_username}-${var.koding_group_slug}'\n instance_type: t2.nano\n ami: ''\n',
'sum': '0857bea2903b56d1b530f120b8445a6074cb6da2'
},
'credentials': {
'aws': [
'PI:KEY:<KEY>END_PI'
]
},
'_id': '56f9294526efa37e25019dfc',
'isDefault': false,
'inUse': true
}
|
[
{
"context": ".refs.textInput.refs.element\n input.value = 'test data'\n TestUtils.Simulate.change input\n expe",
"end": 862,
"score": 0.9356240630149841,
"start": 853,
"tag": "NAME",
"value": "test data"
},
{
"context": "xpect(data.user).toInclude { bing: 'bong', name: 'test data', id: 99 }\n done()\n\n component = Test",
"end": 1546,
"score": 0.9791619181632996,
"start": 1537,
"tag": "NAME",
"value": "test data"
},
{
"context": ".refs.textInput.refs.element\n input.value = 'test data'\n TestUtils.Simulate.change input\n expe",
"end": 1801,
"score": 0.849648654460907,
"start": 1792,
"tag": "NAME",
"value": "test data"
},
{
"context": " should pass\n component.state.patch = name: 'test data'\n TestUtils.Simulate.submit component.refs.f",
"end": 2716,
"score": 0.841926634311676,
"start": 2707,
"tag": "NAME",
"value": "test data"
}
] | test/rest_form.spec.cjsx | PayloadDev/react-at-rest | 48 | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, RestForm, Forms} = require '../modules'
class UserForm extends RestForm
validations:
name:
required: true
render: ->
<form onSubmit={@handleSubmit} ref='form'>
<Forms.TextInput {...@getFieldProps('name')} ref='textInput' />
<button ref='submitButton'>Submit</button>
</form>
describe 'RestForm', ->
store = new Store 'users'
describe '#handleFieldChange', ->
before ->
@component = TestUtils.renderIntoDocument <UserForm model={{bing: 'bong'}} store={store} />
it 'should update the patch on user action', ->
input = @component.refs.textInput.refs.element
input.value = 'test data'
TestUtils.Simulate.change input
expect(@component.state.patch).toEqual name: 'test data'
expect(@component.getUpdatedModel()).toEqual
name: 'test data'
bing: 'bong'
describe '#saveModel', ->
before ->
mocker.post '/users', (req) ->
req.body = user: req.body
req.body.user.id = 99
req.ok = true
req
it 'should capture the submit event and save via Store', (done) ->
# check onSuccess callback returned with data from Store
successSpy = expect.createSpy().andCall (data) ->
expect(successSpy).toHaveBeenCalled()
expect(data.user).toInclude { bing: 'bong', name: 'test data', id: 99 }
done()
component = TestUtils.renderIntoDocument <UserForm
onSuccess={successSpy}
model={{bing: 'bong'}}
store={store} />
input = component.refs.textInput.refs.element
input.value = 'test data'
TestUtils.Simulate.change input
expect(component.state.patch).toEqual name: 'test data'
spy = expect.spyOn(component, 'saveModel').andCallThrough()
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
expect(spy).toHaveBeenCalled()
expect(validateSpy).toHaveBeenCalled()
it 'should validate the patch', ->
component = TestUtils.renderIntoDocument <UserForm
model={{bing: 'bong'}}
store={store} />
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
# validations should not pass
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toEqual { name: [ "Can't be blank" ] }
# now validations should pass
component.state.patch = name: 'test data'
TestUtils.Simulate.submit component.refs.form
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toNotExist()
| 50034 | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, RestForm, Forms} = require '../modules'
class UserForm extends RestForm
validations:
name:
required: true
render: ->
<form onSubmit={@handleSubmit} ref='form'>
<Forms.TextInput {...@getFieldProps('name')} ref='textInput' />
<button ref='submitButton'>Submit</button>
</form>
describe 'RestForm', ->
store = new Store 'users'
describe '#handleFieldChange', ->
before ->
@component = TestUtils.renderIntoDocument <UserForm model={{bing: 'bong'}} store={store} />
it 'should update the patch on user action', ->
input = @component.refs.textInput.refs.element
input.value = '<NAME>'
TestUtils.Simulate.change input
expect(@component.state.patch).toEqual name: 'test data'
expect(@component.getUpdatedModel()).toEqual
name: 'test data'
bing: 'bong'
describe '#saveModel', ->
before ->
mocker.post '/users', (req) ->
req.body = user: req.body
req.body.user.id = 99
req.ok = true
req
it 'should capture the submit event and save via Store', (done) ->
# check onSuccess callback returned with data from Store
successSpy = expect.createSpy().andCall (data) ->
expect(successSpy).toHaveBeenCalled()
expect(data.user).toInclude { bing: 'bong', name: '<NAME>', id: 99 }
done()
component = TestUtils.renderIntoDocument <UserForm
onSuccess={successSpy}
model={{bing: 'bong'}}
store={store} />
input = component.refs.textInput.refs.element
input.value = '<NAME>'
TestUtils.Simulate.change input
expect(component.state.patch).toEqual name: 'test data'
spy = expect.spyOn(component, 'saveModel').andCallThrough()
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
expect(spy).toHaveBeenCalled()
expect(validateSpy).toHaveBeenCalled()
it 'should validate the patch', ->
component = TestUtils.renderIntoDocument <UserForm
model={{bing: 'bong'}}
store={store} />
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
# validations should not pass
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toEqual { name: [ "Can't be blank" ] }
# now validations should pass
component.state.patch = name: '<NAME>'
TestUtils.Simulate.submit component.refs.form
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toNotExist()
| true | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, RestForm, Forms} = require '../modules'
class UserForm extends RestForm
validations:
name:
required: true
render: ->
<form onSubmit={@handleSubmit} ref='form'>
<Forms.TextInput {...@getFieldProps('name')} ref='textInput' />
<button ref='submitButton'>Submit</button>
</form>
describe 'RestForm', ->
store = new Store 'users'
describe '#handleFieldChange', ->
before ->
@component = TestUtils.renderIntoDocument <UserForm model={{bing: 'bong'}} store={store} />
it 'should update the patch on user action', ->
input = @component.refs.textInput.refs.element
input.value = 'PI:NAME:<NAME>END_PI'
TestUtils.Simulate.change input
expect(@component.state.patch).toEqual name: 'test data'
expect(@component.getUpdatedModel()).toEqual
name: 'test data'
bing: 'bong'
describe '#saveModel', ->
before ->
mocker.post '/users', (req) ->
req.body = user: req.body
req.body.user.id = 99
req.ok = true
req
it 'should capture the submit event and save via Store', (done) ->
# check onSuccess callback returned with data from Store
successSpy = expect.createSpy().andCall (data) ->
expect(successSpy).toHaveBeenCalled()
expect(data.user).toInclude { bing: 'bong', name: 'PI:NAME:<NAME>END_PI', id: 99 }
done()
component = TestUtils.renderIntoDocument <UserForm
onSuccess={successSpy}
model={{bing: 'bong'}}
store={store} />
input = component.refs.textInput.refs.element
input.value = 'PI:NAME:<NAME>END_PI'
TestUtils.Simulate.change input
expect(component.state.patch).toEqual name: 'test data'
spy = expect.spyOn(component, 'saveModel').andCallThrough()
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
expect(spy).toHaveBeenCalled()
expect(validateSpy).toHaveBeenCalled()
it 'should validate the patch', ->
component = TestUtils.renderIntoDocument <UserForm
model={{bing: 'bong'}}
store={store} />
validateSpy = expect.spyOn(component, 'validateModel').andCallThrough()
TestUtils.Simulate.submit component.refs.form
# validations should not pass
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toEqual { name: [ "Can't be blank" ] }
# now validations should pass
component.state.patch = name: 'PI:NAME:<NAME>END_PI'
TestUtils.Simulate.submit component.refs.form
expect(validateSpy).toHaveBeenCalled()
expect(component.state.errors).toNotExist()
|
[
{
"context": ": 'TableA'\n id:\n name: 'id'\n column: 'colIdA'\n ",
"end": 2285,
"score": 0.6132261157035828,
"start": 2283,
"tag": "NAME",
"value": "id"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: 'idA'\n pk",
"end": 2822,
"score": 0.582990825176239,
"start": 2819,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: 'idA'\n pk",
"end": 3327,
"score": 0.6232160329818726,
"start": 3324,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: 'idA'\n p",
"end": 3784,
"score": 0.5065782070159912,
"start": 3782,
"tag": "NAME",
"value": "id"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: undefined\n , 'ID_",
"end": 4400,
"score": 0.641151487827301,
"start": 4397,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: null\n , 'ID_COLUM",
"end": 4618,
"score": 0.9859279990196228,
"start": 4615,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: {}\n , 'ID_COLUMN'",
"end": 4837,
"score": 0.9893553256988525,
"start": 4834,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'idA'\n column: ''\n , 'ID_COLUMN'",
"end": 5056,
"score": 0.9862428903579712,
"start": 5053,
"tag": "NAME",
"value": "idA"
},
{
"context": ": 'TableA'\n id:\n name: 'id'\n column: 'colIdA'\n pro",
"end": 6113,
"score": 0.5377429127693176,
"start": 6111,
"tag": "NAME",
"value": "id"
},
{
"context": ": 'TableA'\n id:\n name: 'id'\n column: 'colIdA'\n pro",
"end": 6416,
"score": 0.8110228776931763,
"start": 6414,
"tag": "NAME",
"value": "id"
},
{
"context": ": 'TableA'\n id:\n name: 'id'\n column: 'colIdA'\n pro",
"end": 6781,
"score": 0.8201616406440735,
"start": 6779,
"tag": "NAME",
"value": "id"
}
] | test/suite/02_test_mapping.coffee | smbape/node-dblayer | 0 | logger = log4js.getLogger __filename.replace /^(?:.+[\\\/])?([^.\\\/]+)(?:.[^.]+)?$/, '$1'
async = require 'async'
_ = require 'lodash'
{PersistenceManager} = require '../../'
describe 'mapping', ->
it 'should map', ->
mapping = {}
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
,
className: 'ClassA'
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
# String id is for name and column
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# Empty id column is replaced by id name
assertPartial mapping, 'ClassA',
table: 'TableA'
id: name: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# default table name is className
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'ClassA'
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1:
column: 'colPropA1'
,
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# Property as string => column name
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1: 'colPropA1'
,
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: 'propA1'}
]
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unique', properties: ['propA2']}
]
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1', 'propA2']}
]
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# must keep given pk name
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
return
it 'should throws', ->
mapping = {}
# Column cannot be setted as undefined
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'idA'
column: undefined
, 'ID_COLUMN'
# Column cannot be setted as null
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'idA'
column: null
, 'ID_COLUMN'
# Column cannot be setted as not string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'idA'
column: {}
, 'ID_COLUMN'
# Column cannot be setted as empty string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'idA'
column: ''
, 'ID_COLUMN'
# Column key is mandatory for setted properties
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1:
toto: 'colPropA'
propA2:
column: 'colPropA'
, 'COLUMN'
# Property cannot be null
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: null
propA2:
column: 'colPropA'
, 'PROP'
# Property cannot be undefined
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: undefined
propA2:
column: 'colPropA'
, 'PROP'
# Duplicate columns in id and properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1:
column: 'colIdA'
, 'DUP_COLUMN'
# Duplicate columns, in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1:
column: 'colPropA'
propA2:
column: 'colPropA'
, 'DUP_COLUMN'
# Undefined class in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA2:
className: 'colPropA2'
propA3:
className: 'colPropA3'
propA1: 'colPropA1'
, 'UNDEF_CLASS'
mapping['ClassA'] =
id: 'idA'
# Mixin column cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: undefined
]
, 'MIXIN_COLUMN'
# Mixin column cannot be null
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: null
]
, 'MIXIN_COLUMN'
# Mixin column cannot be not a string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: {}
]
, 'MIXIN_COLUMN'
# Mixin column cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: ''
]
, 'MIXIN_COLUMN'
# Table cannot be undefined
assertPartialThrows mapping, 'ClassB',
table: undefined
id:
name: 'id'
, 'TABLE'
# Table cannot be null
assertPartialThrows mapping, 'ClassB',
table: null
id:
name: 'id'
, 'TABLE'
# Table cannot be not a string
assertPartialThrows mapping, 'ClassB',
table: {}
id:
name: 'id'
, 'TABLE'
# Table cannot be an empty string
assertPartialThrows mapping, 'ClassB',
table: ''
id:
name: 'id'
, 'TABLE'
# Id Cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: undefined
, 'ID'
# Id Cannot be null
assertPartialThrows mapping, 'ClassB',
id: null
, 'ID'
# Id Cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: ''
, 'ID'
# Mixins cannot be undefined
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: undefined
, 'MIXINS'
# Mixins cannot be null
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: null
, 'MIXINS'
# Mixins cannot be not a string and not an Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: {}
, 'MIXINS'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
id: 'toto'
]
, 'MIXIN'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
undefined
]
, 'MIXIN'
# name and className cannot be both setted
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
className: 'toto'
, 'INCOMP_ID'
# constraint
delete mapping.ClassB
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: {}
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propA2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: undefined}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propB2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
ctor: 'toto'
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
, 'CTOR'
# primary key can only be a string
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: true
, 'INDEX'
return
return
| 26388 | logger = log4js.getLogger __filename.replace /^(?:.+[\\\/])?([^.\\\/]+)(?:.[^.]+)?$/, '$1'
async = require 'async'
_ = require 'lodash'
{PersistenceManager} = require '../../'
describe 'mapping', ->
it 'should map', ->
mapping = {}
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
,
className: 'ClassA'
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
# String id is for name and column
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# Empty id column is replaced by id name
assertPartial mapping, 'ClassA',
table: 'TableA'
id: name: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# default table name is className
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'ClassA'
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1:
column: 'colPropA1'
,
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# Property as string => column name
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1: 'colPropA1'
,
table: 'TableA'
id:
name: '<NAME>'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: 'propA1'}
]
,
table: 'TableA'
id:
name: '<NAME>'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unique', properties: ['propA2']}
]
,
table: 'TableA'
id:
name: '<NAME>'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1', 'propA2']}
]
,
table: 'TableA'
id:
name: '<NAME>A'
column: 'idA'
pk: 'TableA'
# must keep given pk name
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
return
it 'should throws', ->
mapping = {}
# Column cannot be setted as undefined
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: undefined
, 'ID_COLUMN'
# Column cannot be setted as null
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: null
, 'ID_COLUMN'
# Column cannot be setted as not string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: {}
, 'ID_COLUMN'
# Column cannot be setted as empty string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: ''
, 'ID_COLUMN'
# Column key is mandatory for setted properties
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1:
toto: 'colPropA'
propA2:
column: 'colPropA'
, 'COLUMN'
# Property cannot be null
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: null
propA2:
column: 'colPropA'
, 'PROP'
# Property cannot be undefined
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: undefined
propA2:
column: 'colPropA'
, 'PROP'
# Duplicate columns in id and properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: 'colIdA'
properties:
propA1:
column: 'colIdA'
, 'DUP_COLUMN'
# Duplicate columns, in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: 'colIdA'
properties:
propA1:
column: 'colPropA'
propA2:
column: 'colPropA'
, 'DUP_COLUMN'
# Undefined class in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: '<NAME>'
column: 'colIdA'
properties:
propA2:
className: 'colPropA2'
propA3:
className: 'colPropA3'
propA1: 'colPropA1'
, 'UNDEF_CLASS'
mapping['ClassA'] =
id: 'idA'
# Mixin column cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: undefined
]
, 'MIXIN_COLUMN'
# Mixin column cannot be null
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: null
]
, 'MIXIN_COLUMN'
# Mixin column cannot be not a string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: {}
]
, 'MIXIN_COLUMN'
# Mixin column cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: ''
]
, 'MIXIN_COLUMN'
# Table cannot be undefined
assertPartialThrows mapping, 'ClassB',
table: undefined
id:
name: 'id'
, 'TABLE'
# Table cannot be null
assertPartialThrows mapping, 'ClassB',
table: null
id:
name: 'id'
, 'TABLE'
# Table cannot be not a string
assertPartialThrows mapping, 'ClassB',
table: {}
id:
name: 'id'
, 'TABLE'
# Table cannot be an empty string
assertPartialThrows mapping, 'ClassB',
table: ''
id:
name: 'id'
, 'TABLE'
# Id Cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: undefined
, 'ID'
# Id Cannot be null
assertPartialThrows mapping, 'ClassB',
id: null
, 'ID'
# Id Cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: ''
, 'ID'
# Mixins cannot be undefined
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: undefined
, 'MIXINS'
# Mixins cannot be null
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: null
, 'MIXINS'
# Mixins cannot be not a string and not an Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: {}
, 'MIXINS'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
id: 'toto'
]
, 'MIXIN'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
undefined
]
, 'MIXIN'
# name and className cannot be both setted
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
className: 'toto'
, 'INCOMP_ID'
# constraint
delete mapping.ClassB
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: {}
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propA2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: undefined}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propB2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
ctor: 'toto'
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
, 'CTOR'
# primary key can only be a string
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: true
, 'INDEX'
return
return
| true | logger = log4js.getLogger __filename.replace /^(?:.+[\\\/])?([^.\\\/]+)(?:.[^.]+)?$/, '$1'
async = require 'async'
_ = require 'lodash'
{PersistenceManager} = require '../../'
describe 'mapping', ->
it 'should map', ->
mapping = {}
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
,
className: 'ClassA'
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
# String id is for name and column
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# Empty id column is replaced by id name
assertPartial mapping, 'ClassA',
table: 'TableA'
id: name: 'idA'
,
table: 'TableA'
id:
name: 'idA'
column: 'idA'
pk: 'TableA'
# default table name is className
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'ClassA'
# Check consistency
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1:
column: 'colPropA1'
,
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# Property as string => column name
assertPartial mapping, 'ClassA',
table: 'TableA'
id:
name: 'id'
column: 'colIdA'
properties:
propA1: 'colPropA1'
,
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'colIdA'
pk: 'TableA'
properties:
propA1:
column: 'colPropA1'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: 'propA1'}
]
,
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unique', properties: ['propA2']}
]
,
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'idA'
pk: 'TableA'
# constraint
assertPartial mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1', 'propA2']}
]
,
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PIA'
column: 'idA'
pk: 'TableA'
# must keep given pk name
assertPartial mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
,
table: 'ClassA'
id:
name: 'id'
column: 'colIdA'
pk: 'custom'
return
it 'should throws', ->
mapping = {}
# Column cannot be setted as undefined
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: undefined
, 'ID_COLUMN'
# Column cannot be setted as null
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: null
, 'ID_COLUMN'
# Column cannot be setted as not string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: {}
, 'ID_COLUMN'
# Column cannot be setted as empty string
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: ''
, 'ID_COLUMN'
# Column key is mandatory for setted properties
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1:
toto: 'colPropA'
propA2:
column: 'colPropA'
, 'COLUMN'
# Property cannot be null
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: null
propA2:
column: 'colPropA'
, 'PROP'
# Property cannot be undefined
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
properties:
propA1: undefined
propA2:
column: 'colPropA'
, 'PROP'
# Duplicate columns in id and properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'colIdA'
properties:
propA1:
column: 'colIdA'
, 'DUP_COLUMN'
# Duplicate columns, in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'colIdA'
properties:
propA1:
column: 'colPropA'
propA2:
column: 'colPropA'
, 'DUP_COLUMN'
# Undefined class in properties
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id:
name: 'PI:NAME:<NAME>END_PI'
column: 'colIdA'
properties:
propA2:
className: 'colPropA2'
propA3:
className: 'colPropA3'
propA1: 'colPropA1'
, 'UNDEF_CLASS'
mapping['ClassA'] =
id: 'idA'
# Mixin column cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: undefined
]
, 'MIXIN_COLUMN'
# Mixin column cannot be null
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: null
]
, 'MIXIN_COLUMN'
# Mixin column cannot be not a string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: {}
]
, 'MIXIN_COLUMN'
# Mixin column cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: 'idB'
mixins: [
className: 'ClassA'
column: ''
]
, 'MIXIN_COLUMN'
# Table cannot be undefined
assertPartialThrows mapping, 'ClassB',
table: undefined
id:
name: 'id'
, 'TABLE'
# Table cannot be null
assertPartialThrows mapping, 'ClassB',
table: null
id:
name: 'id'
, 'TABLE'
# Table cannot be not a string
assertPartialThrows mapping, 'ClassB',
table: {}
id:
name: 'id'
, 'TABLE'
# Table cannot be an empty string
assertPartialThrows mapping, 'ClassB',
table: ''
id:
name: 'id'
, 'TABLE'
# Id Cannot be undefined
assertPartialThrows mapping, 'ClassB',
id: undefined
, 'ID'
# Id Cannot be null
assertPartialThrows mapping, 'ClassB',
id: null
, 'ID'
# Id Cannot be an empty string
assertPartialThrows mapping, 'ClassB',
id: ''
, 'ID'
# Mixins cannot be undefined
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: undefined
, 'MIXINS'
# Mixins cannot be null
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: null
, 'MIXINS'
# Mixins cannot be not a string and not an Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: {}
, 'MIXINS'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
id: 'toto'
]
, 'MIXIN'
# Mixin must have a className prop if as Array
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
mixins: [
undefined
]
, 'MIXIN'
# name and className cannot be both setted
assertPartialThrows mapping, 'ClassB',
id:
name: 'id'
className: 'toto'
, 'INCOMP_ID'
# constraint
delete mapping.ClassB
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
id: 'idA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: {}
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propA2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: undefined}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
constraints: [
{type: 'unique', properties: ['propA1']}
{type: 'unknown', properties: ['propB2']}
]
, 'CONSTRAINT'
# constraint
assertPartialThrows mapping, 'ClassA',
ctor: 'toto'
table: 'TableA'
properties:
propA1: 'colPropA1'
propA2: 'colPropA2'
, 'CTOR'
# primary key can only be a string
assertPartialThrows mapping, 'ClassA',
id:
name: 'id'
column: 'colIdA'
pk: true
, 'INDEX'
return
return
|
[
{
"context": "y(), '1')\n\n $('.droplet-hidden-input').sendkeys('2 + 3')\n\n setTimeout((->\n ok(editor.cursorAtSocket(",
"end": 6290,
"score": 0.7096831798553467,
"start": 6285,
"tag": "KEY",
"value": "2 + 3"
},
{
"context": "y(), 'a')\n\n $('.droplet-hidden-input').sendkeys('18n')\n\n setTimeout((->\n ok(editor.getCursor(), 'E",
"end": 9134,
"score": 0.9655798077583313,
"start": 9131,
"tag": "KEY",
"value": "18n"
}
] | test/src/uitest.coffee | PencilCode/droplet | 117 | helper = require '../../src/helper.coffee'
model = require '../../src/model.coffee'
view = require '../../src/view.coffee'
draw = require '../../src/draw.coffee'
droplet = require '../../dist/droplet-full.js'
seedrandom = require 'seedrandom'
`
// Mouse event simluation function
function simulate(type, target, options) {
if ('string' == typeof(target)) {
target = $(target).get(0)
}
options = options || {}
var pageX = pageY = clientX = clientY = dx = dy = 0
var location = options.location || target
if (location) {
if ('string' == typeof(location)) {
location = $(location).get(0)
}
var gbcr = location.getBoundingClientRect()
clientX = gbcr.left,
clientY = gbcr.top,
pageX = clientX + window.pageXOffset
pageY = clientY + window.pageYOffset
dx = Math.floor((gbcr.right - gbcr.left) / 2)
dy = Math.floor((gbcr.bottom - gbcr.top) / 2)
}
if ('dx' in options) dx = options.dx
if ('dy' in options) dy = options.dy
pageX = (options.pageX == null ? pageX : options.pageX) + dx
pageY = (options.pageY == null ? pageY : options.pageY) + dy
clientX = pageX - window.pageXOffset
clientY = pageY - window.pageYOffset
var opts = {
bubbles: options.bubbles || true,
cancelable: options.cancelable || true,
view: options.view || target.ownerDocument.defaultView,
detail: options.detail || 1,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
screenX: clientX + window.screenLeft,
screenY: clientY + window.screenTop,
ctrlKey: options.ctrlKey || false,
altKey: options.altKey || false,
shiftKey: options.shiftKey || false,
metaKey: options.metaKey || false,
button: options.button || 0,
which: options.which || 1,
relatedTarget: options.relatedTarget || null,
}
//console.log(location.className);
//console.log(JSON.stringify(location.getBoundingClientRect()));
//console.log(JSON.stringify(opts, function(key, val) { if (key == '' || key == 'pageX' || key == 'pageY' || key == 'clientX' || key == 'clientY' || key == 'screenX' || key == 'screenY') return val; }));
var evt
try {
// Modern API supported by IE9+
evt = new MouseEvent(type, opts)
} catch (e) {
// Old API still required by PhantomJS.
evt = target.ownerDocument.createEvent('MouseEvents')
evt.initMouseEvent(type, opts.bubbles, opts.cancelable, opts.view,
opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY,
opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button,
opts.relatedTarget)
}
target.dispatchEvent(evt)
}
function sequence(delay) {
var seq = [],
chain = { then: function(fn) { seq.push(fn); return chain; } }
function advance() {
setTimeout(function() {
if (seq.length) {
(seq.shift())()
advance()
}
}, delay)
}
advance()
return chain
}
`
pickUpLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
bound = editor.session.view.getViewNodeFor(block).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: bound.x + 5 + editor.gutter.clientWidth,
dy: bound.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: bound.x + 10 + editor.gutter.clientWidth,
dy: bound.y + 10
})
dropLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
blockView = editor.session.view.getViewNodeFor block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
asyncTest 'Controller: palette block expansion', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
palette: [{
name: 'Draw',
color: 'blue',
blocks: [{
block: 'pen()',
expansion: 'pen red',
id: 'ptest'
}, {
block: 'a = b',
expansion: -> return 'a' + (++varcount) + ' = b'
id: 'ftest'
},
],
}]
})
simulate('mousedown', '[data-id=ptest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ptest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
equal(editor.getValue().trim(), 'pen red')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
equal(editor.getValue().trim(), 'pen red\na3 = b')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
equal(editor.getValue().trim(), 'pen red\na3 = b\na6 = b')
start()
asyncTest 'Controller: reparse and undo reparse', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = 1;')
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '1')
$('.droplet-hidden-input').sendkeys('2 + 3')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), '2 + 3')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '2', 'Successfully reparsed')
editor.undo()
setTimeout (->
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
equal(editor.getCursor().stringify(), '1', 'Successfully undid reparse')
), 0
start()
), 0)
asyncTest 'Controller: reparse fallback', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = mFunction(a);')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('a, b')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), 'a, b')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Did not insert parentheses
equal(editor.getValue().trim(), 'var hello = mFunction(a, b);')
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
start()
), 10)
asyncTest 'Controller: does not throw on reparse error', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
before = $('[stroke=#F00]').length
editor.setEditorState(true)
editor.setValue('var hello = function (a) {};')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.getCursor(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('18n')
setTimeout((->
ok(editor.getCursor(), 'Editor still has getCursor()')
equal(editor.getCursor().stringify(), '18n')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
ok(true, 'Does not throw on reparse')
after = $('[stroke=#F00]').length
ok(after > before, 'Marks block with a red line')
start()
), 10)
asyncTest 'Controller: Can replace a block where we found it', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
equal(editor.getValue() , 'for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
equal(editor.getValue() , 'for (var i = 0; i < i++; __) {\n' +
' fd(10);\n' +
'}\n')
start()
getRandomDragOp = (editor, rng) ->
# Find the locations of all the blocks
head = editor.session.tree.start
# Skip the first block if it is the entire document
if head.next.container?.end is editor.session.tree.end.prev
head = head.next.next
dragPossibilities = []
until head is editor.session.tree.end
if head.type is 'blockStart'
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
dragPossibilities.push {
block: head.container
handle: handle
}
head = head.next
drag = dragPossibilities[Math.floor rng() * dragPossibilities.length]
# Find all the drop areas
head = editor.session.tree.start
# Disclude the main tree if we're dragging the first block
if drag is dragPossibilities[0]
head = head.next
dropPossibilities = []
until head is editor.session.tree.end
if head is drag.block.start
head = drag.block.end
if head.type.match(/Start$/)?
dropPoint = editor.session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
if head.container.type is 'block'
parent = head.container.parent
else
parent = head.container
canDrop = editor.getAcceptLevel(drag.block, head.container)
if canDrop is 1
dropPossibilities.push {
block: head.container
point: {x: dropPoint.x, y: dropPoint.y}
}
head = head.next
# If this block is not droppable, try again.
if dropPossibilities.length is 0
return getRandomDragOp(editor, rng)
drop = dropPossibilities[Math.floor rng() * dropPossibilities.length]
return {drag, drop}
generateRandomAlphabetic = (rng) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
str = ''
str += alphabet[Math.floor rng() * alphabet.length]
until rng() < 0.1
str += alphabet[Math.floor rng() * alphabet.length]
return str
getRandomTextOp = (editor, rng) ->
head = editor.session.tree.start
socketPossibilities = []
until head is editor.session.tree.end
if head.type is 'socketStart' and head.container.editable()
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
socketPossibilities.push {
block: head.container
handle: handle
}
head = head.next
socket = socketPossibilities[Math.floor rng() * socketPossibilities.length]
text = generateRandomAlphabetic rng
return {socket, text}
performTextOperation = (editor, text, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
setTimeout (->
$(editor.hiddeninput).sendkeys(text.text)
# Unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
), 0
performDragOperation = (editor, drag, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drag.handle.x + editor.gutter.clientWidth,
dy: drag.drag.handle.y
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drag.handle.x + 5 + editor.gutter.clientWidth,
dy: drag.drag.handle.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
# Unfocus
if editor.cursorAtSocket()
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
executeAsyncSequence = (sequence, i = 0) ->
if i < sequence.length
sequence[i]()
setTimeout (->
executeAsyncSequence sequence, i + 1
), 0
asyncTest 'Controller: remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 9
type: 'block'
}
dropLocation editor, 0, {
row: 2
col: 7
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
fd [0..10]
else
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 2
col: 4
type: 'block'
}
dropLocation editor, 0, {
row: 3
col: 6
type: 'indent'
}
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
), (->
editor.undo()
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
``
else
fd [0..10]
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
start()
)
]
asyncTest 'Controller: floating blocks with remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: true}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
fd 10
fd 20
fd 30
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Create a floating block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.getValue(), '''
fd 20
fd 30\n
''')
equal(editor.session.floatingBlocks.length, 1)
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.session.floatingBlocks.length, 2)
equal(editor.getValue(), '''
fd 30\n
''')
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 3
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
# Move a block from floating block 1 to 2 so as to destroy floating block 1,
# potentially messing up the undo stack and rememberedSocket records
pickUpLocation editor, 1, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 6
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
# Remove the block we just placed to invoke rememberedSocket lookup
pickUpLocation editor, 1, {
row: 0
col: 6
type: 'block'
}
# Drop in main document
dropLocation editor, 0, {
row: 0
col: 0
type: 'document'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd 30
''')
equal(editor.getValue(), '''
fd 10\n
''')
), (->
editor.undo()
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd 20
''')
equal(editor.getValue(), '''
fd 30\n
''')
start()
)
]
asyncTest 'Controller: Quoted string selection', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('fd "hello"')
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
setTimeout (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
start()
), 0
asyncTest 'Controller: Quoted string CoffeeScript autoescape', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue("fd 'hello'")
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
executeAsyncSequence [
(->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
), (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
$('.droplet-hidden-input').sendkeys("h\\tel\\\\\"'lo")
), (->
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
), (->
equal editor.getValue(), """fd 'h\\tel\\\\"\\'lo'\n"""
start()
)
]
asyncTest 'Controller: Session switch test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks 1'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 2'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 3'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 4'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 5'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 6'
blocks: [
{block: 'a is b'}
]
}
]
})
originalSession = editor.aceEditor.getSession()
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
equal editor.paletteHeader.childElementCount, 3, 'Palette header originally has three rows'
newSession = ace.createEditSession('''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}
''', 'ace/mode/javascript')
executeAsyncSequence [
(->
editor.aceEditor.setSession newSession
),
(->
editor.bindNewSession({
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks'
editor.setEditorState(false)
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
),
(->
editor.aceEditor.setSession originalSession
),
(->
equal editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10\n
''', 'Original text restored'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks again'
equal editor.paletteHeader.childElementCount, 3, 'Original palette header size restored'
),
(->
editor.aceEditor.setSession newSession
),
(->
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
start()
)
]
asyncTest 'Controller: Random drag undo test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
stateStack.push editor.getSerializedEditorState().toString()
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
while stateStack.length > 0
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
editor.undo()
equal editor.getSerializedEditorState().toString(), text, 'Undo was correct'
start()
else
ok (not editor.cursorAtSocket()), 'Properly unfocused'
setTimeout (-> tick count - 1), 0
stateStack.push editor.getSerializedEditorState().toString()
if rng() > 0.5
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 100
###
asyncTest 'Controller: ANTLR random drag reparse test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'c_cpp',
modeOptions:
knownFunctions:
printf: {color: 'blue', shape: 'block-only'}
puts: {color: 'blue', shape: 'block-only'}
scanf: {color: 'blue', shape: 'block-only'}
malloc: {color: 'red', shape: 'value-only'}
palette: []
})
editor.setEditorState(true)
editor.setValue('''
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
// Linked list
struct List {
long long data;
struct List *next;
struct List *prev;
};
typedef struct List List;
// Memoryless swap
void swap(long long *a, long long *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
// Test if sorted
int sorted(List *head, int (*fn)(long long, long long)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data)) {
return 0;
}
}
return 1;
}
// Bubble sort
void sort(List *head, int (*fn)(long long, long long)) {
while (!sorted(head, fn)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data))
swap(&cursor->data, &cursor->next->data);
}
}
}
// Comparator
int comparator(long long a, long long b) {
return (a > b);
}
// Main
int main(int n, char *args[]) {
// Arbitrary array initializer just o test that syntax
int arbitraryArray[] = {1, 2, 3, 4, 5};
int length;
scanf("%d", &length);
if (length > MAXLEN) {
puts("Error: list is too large");
return 1;
}
List *head = (List*)malloc(sizeof(List));
scanf("%d", &head->data);
head->prev = NULL;
List *cursor = head;
int temp;
for (int i = 0; i < length - 1; i++) {
cursor->next = (List*)malloc(sizeof(List));
cursor = cursor->next;
scanf("%d", &temp);
cursor->data = (long long)temp;
}
sort(head, comparator);
for (cursor = head; cursor; cursor = cursor->next) {
printf("%d ", cursor->data);
}
puts("\\n");
return 0;
}
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
start()
else
ok editor.session.mode.parse(editor.getValue()), 'Still in a parseable state'
setTimeout (-> tick count - 1), 0
if rng() > 0.1
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 50
###
| 8452 | helper = require '../../src/helper.coffee'
model = require '../../src/model.coffee'
view = require '../../src/view.coffee'
draw = require '../../src/draw.coffee'
droplet = require '../../dist/droplet-full.js'
seedrandom = require 'seedrandom'
`
// Mouse event simluation function
function simulate(type, target, options) {
if ('string' == typeof(target)) {
target = $(target).get(0)
}
options = options || {}
var pageX = pageY = clientX = clientY = dx = dy = 0
var location = options.location || target
if (location) {
if ('string' == typeof(location)) {
location = $(location).get(0)
}
var gbcr = location.getBoundingClientRect()
clientX = gbcr.left,
clientY = gbcr.top,
pageX = clientX + window.pageXOffset
pageY = clientY + window.pageYOffset
dx = Math.floor((gbcr.right - gbcr.left) / 2)
dy = Math.floor((gbcr.bottom - gbcr.top) / 2)
}
if ('dx' in options) dx = options.dx
if ('dy' in options) dy = options.dy
pageX = (options.pageX == null ? pageX : options.pageX) + dx
pageY = (options.pageY == null ? pageY : options.pageY) + dy
clientX = pageX - window.pageXOffset
clientY = pageY - window.pageYOffset
var opts = {
bubbles: options.bubbles || true,
cancelable: options.cancelable || true,
view: options.view || target.ownerDocument.defaultView,
detail: options.detail || 1,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
screenX: clientX + window.screenLeft,
screenY: clientY + window.screenTop,
ctrlKey: options.ctrlKey || false,
altKey: options.altKey || false,
shiftKey: options.shiftKey || false,
metaKey: options.metaKey || false,
button: options.button || 0,
which: options.which || 1,
relatedTarget: options.relatedTarget || null,
}
//console.log(location.className);
//console.log(JSON.stringify(location.getBoundingClientRect()));
//console.log(JSON.stringify(opts, function(key, val) { if (key == '' || key == 'pageX' || key == 'pageY' || key == 'clientX' || key == 'clientY' || key == 'screenX' || key == 'screenY') return val; }));
var evt
try {
// Modern API supported by IE9+
evt = new MouseEvent(type, opts)
} catch (e) {
// Old API still required by PhantomJS.
evt = target.ownerDocument.createEvent('MouseEvents')
evt.initMouseEvent(type, opts.bubbles, opts.cancelable, opts.view,
opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY,
opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button,
opts.relatedTarget)
}
target.dispatchEvent(evt)
}
function sequence(delay) {
var seq = [],
chain = { then: function(fn) { seq.push(fn); return chain; } }
function advance() {
setTimeout(function() {
if (seq.length) {
(seq.shift())()
advance()
}
}, delay)
}
advance()
return chain
}
`
pickUpLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
bound = editor.session.view.getViewNodeFor(block).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: bound.x + 5 + editor.gutter.clientWidth,
dy: bound.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: bound.x + 10 + editor.gutter.clientWidth,
dy: bound.y + 10
})
dropLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
blockView = editor.session.view.getViewNodeFor block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
asyncTest 'Controller: palette block expansion', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
palette: [{
name: 'Draw',
color: 'blue',
blocks: [{
block: 'pen()',
expansion: 'pen red',
id: 'ptest'
}, {
block: 'a = b',
expansion: -> return 'a' + (++varcount) + ' = b'
id: 'ftest'
},
],
}]
})
simulate('mousedown', '[data-id=ptest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ptest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
equal(editor.getValue().trim(), 'pen red')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
equal(editor.getValue().trim(), 'pen red\na3 = b')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
equal(editor.getValue().trim(), 'pen red\na3 = b\na6 = b')
start()
asyncTest 'Controller: reparse and undo reparse', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = 1;')
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '1')
$('.droplet-hidden-input').sendkeys('<KEY>')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), '2 + 3')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '2', 'Successfully reparsed')
editor.undo()
setTimeout (->
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
equal(editor.getCursor().stringify(), '1', 'Successfully undid reparse')
), 0
start()
), 0)
asyncTest 'Controller: reparse fallback', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = mFunction(a);')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('a, b')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), 'a, b')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Did not insert parentheses
equal(editor.getValue().trim(), 'var hello = mFunction(a, b);')
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
start()
), 10)
asyncTest 'Controller: does not throw on reparse error', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
before = $('[stroke=#F00]').length
editor.setEditorState(true)
editor.setValue('var hello = function (a) {};')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.getCursor(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('<KEY>')
setTimeout((->
ok(editor.getCursor(), 'Editor still has getCursor()')
equal(editor.getCursor().stringify(), '18n')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
ok(true, 'Does not throw on reparse')
after = $('[stroke=#F00]').length
ok(after > before, 'Marks block with a red line')
start()
), 10)
asyncTest 'Controller: Can replace a block where we found it', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
equal(editor.getValue() , 'for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
equal(editor.getValue() , 'for (var i = 0; i < i++; __) {\n' +
' fd(10);\n' +
'}\n')
start()
getRandomDragOp = (editor, rng) ->
# Find the locations of all the blocks
head = editor.session.tree.start
# Skip the first block if it is the entire document
if head.next.container?.end is editor.session.tree.end.prev
head = head.next.next
dragPossibilities = []
until head is editor.session.tree.end
if head.type is 'blockStart'
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
dragPossibilities.push {
block: head.container
handle: handle
}
head = head.next
drag = dragPossibilities[Math.floor rng() * dragPossibilities.length]
# Find all the drop areas
head = editor.session.tree.start
# Disclude the main tree if we're dragging the first block
if drag is dragPossibilities[0]
head = head.next
dropPossibilities = []
until head is editor.session.tree.end
if head is drag.block.start
head = drag.block.end
if head.type.match(/Start$/)?
dropPoint = editor.session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
if head.container.type is 'block'
parent = head.container.parent
else
parent = head.container
canDrop = editor.getAcceptLevel(drag.block, head.container)
if canDrop is 1
dropPossibilities.push {
block: head.container
point: {x: dropPoint.x, y: dropPoint.y}
}
head = head.next
# If this block is not droppable, try again.
if dropPossibilities.length is 0
return getRandomDragOp(editor, rng)
drop = dropPossibilities[Math.floor rng() * dropPossibilities.length]
return {drag, drop}
generateRandomAlphabetic = (rng) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
str = ''
str += alphabet[Math.floor rng() * alphabet.length]
until rng() < 0.1
str += alphabet[Math.floor rng() * alphabet.length]
return str
getRandomTextOp = (editor, rng) ->
head = editor.session.tree.start
socketPossibilities = []
until head is editor.session.tree.end
if head.type is 'socketStart' and head.container.editable()
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
socketPossibilities.push {
block: head.container
handle: handle
}
head = head.next
socket = socketPossibilities[Math.floor rng() * socketPossibilities.length]
text = generateRandomAlphabetic rng
return {socket, text}
performTextOperation = (editor, text, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
setTimeout (->
$(editor.hiddeninput).sendkeys(text.text)
# Unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
), 0
performDragOperation = (editor, drag, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drag.handle.x + editor.gutter.clientWidth,
dy: drag.drag.handle.y
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drag.handle.x + 5 + editor.gutter.clientWidth,
dy: drag.drag.handle.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
# Unfocus
if editor.cursorAtSocket()
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
executeAsyncSequence = (sequence, i = 0) ->
if i < sequence.length
sequence[i]()
setTimeout (->
executeAsyncSequence sequence, i + 1
), 0
asyncTest 'Controller: remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 9
type: 'block'
}
dropLocation editor, 0, {
row: 2
col: 7
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
fd [0..10]
else
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 2
col: 4
type: 'block'
}
dropLocation editor, 0, {
row: 3
col: 6
type: 'indent'
}
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
), (->
editor.undo()
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
``
else
fd [0..10]
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
start()
)
]
asyncTest 'Controller: floating blocks with remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: true}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
fd 10
fd 20
fd 30
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Create a floating block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.getValue(), '''
fd 20
fd 30\n
''')
equal(editor.session.floatingBlocks.length, 1)
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.session.floatingBlocks.length, 2)
equal(editor.getValue(), '''
fd 30\n
''')
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 3
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
# Move a block from floating block 1 to 2 so as to destroy floating block 1,
# potentially messing up the undo stack and rememberedSocket records
pickUpLocation editor, 1, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 6
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
# Remove the block we just placed to invoke rememberedSocket lookup
pickUpLocation editor, 1, {
row: 0
col: 6
type: 'block'
}
# Drop in main document
dropLocation editor, 0, {
row: 0
col: 0
type: 'document'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd 30
''')
equal(editor.getValue(), '''
fd 10\n
''')
), (->
editor.undo()
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd 20
''')
equal(editor.getValue(), '''
fd 30\n
''')
start()
)
]
asyncTest 'Controller: Quoted string selection', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('fd "hello"')
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
setTimeout (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
start()
), 0
asyncTest 'Controller: Quoted string CoffeeScript autoescape', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue("fd 'hello'")
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
executeAsyncSequence [
(->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
), (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
$('.droplet-hidden-input').sendkeys("h\\tel\\\\\"'lo")
), (->
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
), (->
equal editor.getValue(), """fd 'h\\tel\\\\"\\'lo'\n"""
start()
)
]
asyncTest 'Controller: Session switch test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks 1'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 2'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 3'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 4'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 5'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 6'
blocks: [
{block: 'a is b'}
]
}
]
})
originalSession = editor.aceEditor.getSession()
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
equal editor.paletteHeader.childElementCount, 3, 'Palette header originally has three rows'
newSession = ace.createEditSession('''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}
''', 'ace/mode/javascript')
executeAsyncSequence [
(->
editor.aceEditor.setSession newSession
),
(->
editor.bindNewSession({
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks'
editor.setEditorState(false)
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
),
(->
editor.aceEditor.setSession originalSession
),
(->
equal editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10\n
''', 'Original text restored'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks again'
equal editor.paletteHeader.childElementCount, 3, 'Original palette header size restored'
),
(->
editor.aceEditor.setSession newSession
),
(->
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
start()
)
]
asyncTest 'Controller: Random drag undo test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
stateStack.push editor.getSerializedEditorState().toString()
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
while stateStack.length > 0
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
editor.undo()
equal editor.getSerializedEditorState().toString(), text, 'Undo was correct'
start()
else
ok (not editor.cursorAtSocket()), 'Properly unfocused'
setTimeout (-> tick count - 1), 0
stateStack.push editor.getSerializedEditorState().toString()
if rng() > 0.5
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 100
###
asyncTest 'Controller: ANTLR random drag reparse test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'c_cpp',
modeOptions:
knownFunctions:
printf: {color: 'blue', shape: 'block-only'}
puts: {color: 'blue', shape: 'block-only'}
scanf: {color: 'blue', shape: 'block-only'}
malloc: {color: 'red', shape: 'value-only'}
palette: []
})
editor.setEditorState(true)
editor.setValue('''
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
// Linked list
struct List {
long long data;
struct List *next;
struct List *prev;
};
typedef struct List List;
// Memoryless swap
void swap(long long *a, long long *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
// Test if sorted
int sorted(List *head, int (*fn)(long long, long long)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data)) {
return 0;
}
}
return 1;
}
// Bubble sort
void sort(List *head, int (*fn)(long long, long long)) {
while (!sorted(head, fn)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data))
swap(&cursor->data, &cursor->next->data);
}
}
}
// Comparator
int comparator(long long a, long long b) {
return (a > b);
}
// Main
int main(int n, char *args[]) {
// Arbitrary array initializer just o test that syntax
int arbitraryArray[] = {1, 2, 3, 4, 5};
int length;
scanf("%d", &length);
if (length > MAXLEN) {
puts("Error: list is too large");
return 1;
}
List *head = (List*)malloc(sizeof(List));
scanf("%d", &head->data);
head->prev = NULL;
List *cursor = head;
int temp;
for (int i = 0; i < length - 1; i++) {
cursor->next = (List*)malloc(sizeof(List));
cursor = cursor->next;
scanf("%d", &temp);
cursor->data = (long long)temp;
}
sort(head, comparator);
for (cursor = head; cursor; cursor = cursor->next) {
printf("%d ", cursor->data);
}
puts("\\n");
return 0;
}
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
start()
else
ok editor.session.mode.parse(editor.getValue()), 'Still in a parseable state'
setTimeout (-> tick count - 1), 0
if rng() > 0.1
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 50
###
| true | helper = require '../../src/helper.coffee'
model = require '../../src/model.coffee'
view = require '../../src/view.coffee'
draw = require '../../src/draw.coffee'
droplet = require '../../dist/droplet-full.js'
seedrandom = require 'seedrandom'
`
// Mouse event simluation function
function simulate(type, target, options) {
if ('string' == typeof(target)) {
target = $(target).get(0)
}
options = options || {}
var pageX = pageY = clientX = clientY = dx = dy = 0
var location = options.location || target
if (location) {
if ('string' == typeof(location)) {
location = $(location).get(0)
}
var gbcr = location.getBoundingClientRect()
clientX = gbcr.left,
clientY = gbcr.top,
pageX = clientX + window.pageXOffset
pageY = clientY + window.pageYOffset
dx = Math.floor((gbcr.right - gbcr.left) / 2)
dy = Math.floor((gbcr.bottom - gbcr.top) / 2)
}
if ('dx' in options) dx = options.dx
if ('dy' in options) dy = options.dy
pageX = (options.pageX == null ? pageX : options.pageX) + dx
pageY = (options.pageY == null ? pageY : options.pageY) + dy
clientX = pageX - window.pageXOffset
clientY = pageY - window.pageYOffset
var opts = {
bubbles: options.bubbles || true,
cancelable: options.cancelable || true,
view: options.view || target.ownerDocument.defaultView,
detail: options.detail || 1,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
screenX: clientX + window.screenLeft,
screenY: clientY + window.screenTop,
ctrlKey: options.ctrlKey || false,
altKey: options.altKey || false,
shiftKey: options.shiftKey || false,
metaKey: options.metaKey || false,
button: options.button || 0,
which: options.which || 1,
relatedTarget: options.relatedTarget || null,
}
//console.log(location.className);
//console.log(JSON.stringify(location.getBoundingClientRect()));
//console.log(JSON.stringify(opts, function(key, val) { if (key == '' || key == 'pageX' || key == 'pageY' || key == 'clientX' || key == 'clientY' || key == 'screenX' || key == 'screenY') return val; }));
var evt
try {
// Modern API supported by IE9+
evt = new MouseEvent(type, opts)
} catch (e) {
// Old API still required by PhantomJS.
evt = target.ownerDocument.createEvent('MouseEvents')
evt.initMouseEvent(type, opts.bubbles, opts.cancelable, opts.view,
opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY,
opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button,
opts.relatedTarget)
}
target.dispatchEvent(evt)
}
function sequence(delay) {
var seq = [],
chain = { then: function(fn) { seq.push(fn); return chain; } }
function advance() {
setTimeout(function() {
if (seq.length) {
(seq.shift())()
advance()
}
}, delay)
}
advance()
return chain
}
`
pickUpLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
bound = editor.session.view.getViewNodeFor(block).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: bound.x + 5 + editor.gutter.clientWidth,
dy: bound.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: bound.x + 10 + editor.gutter.clientWidth,
dy: bound.y + 10
})
dropLocation = (editor, document, location) ->
block = editor.getDocument(document).getFromTextLocation(location)
blockView = editor.session.view.getViewNodeFor block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: blockView.dropPoint.x + 5 + editor.gutter.clientWidth,
dy: blockView.dropPoint.y + 5
})
asyncTest 'Controller: palette block expansion', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
palette: [{
name: 'Draw',
color: 'blue',
blocks: [{
block: 'pen()',
expansion: 'pen red',
id: 'ptest'
}, {
block: 'a = b',
expansion: -> return 'a' + (++varcount) + ' = b'
id: 'ftest'
},
],
}]
})
simulate('mousedown', '[data-id=ptest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ptest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div' })
equal(editor.getValue().trim(), 'pen red')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 40 })
equal(editor.getValue().trim(), 'pen red\na3 = b')
simulate('mousedown', '[data-id=ftest]')
simulate('mousemove', '.droplet-drag-cover',
{ location: '[data-id=ftest]', dx: 5 })
simulate('mousemove', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
simulate('mouseup', '.droplet-drag-cover',
{ location: '.droplet-wrapper-div', dx: 45 + 43, dy: 70 })
equal(editor.getValue().trim(), 'pen red\na3 = b\na6 = b')
start()
asyncTest 'Controller: reparse and undo reparse', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = 1;')
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '1')
$('.droplet-hidden-input').sendkeys('PI:KEY:<KEY>END_PI')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), '2 + 3')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), '2', 'Successfully reparsed')
editor.undo()
setTimeout (->
simulate('mousedown', '.droplet-main-canvas', {dx: 120, dy: 20})
simulate('mouseup', '.droplet-main-canvas', {dx: 120, dy: 20})
equal(editor.getCursor().stringify(), '1', 'Successfully undid reparse')
), 0
start()
), 0)
asyncTest 'Controller: reparse fallback', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('var hello = mFunction(a);')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('a, b')
setTimeout((->
ok(editor.cursorAtSocket(), 'Editor still has text focus')
equal(editor.getCursor().stringify(), 'a, b')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
# Did not insert parentheses
equal(editor.getValue().trim(), 'var hello = mFunction(a, b);')
# Sockets are separate
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.cursorAtSocket(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
start()
), 10)
asyncTest 'Controller: does not throw on reparse error', ->
states = []
document.getElementById('test-main').innerHTML = ''
varcount = 0
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
before = $('[stroke=#F00]').length
editor.setEditorState(true)
editor.setValue('var hello = function (a) {};')
simulate('mousedown', '.droplet-main-canvas', {dx: 220, dy: 30})
simulate('mouseup', '.droplet-main-canvas', {dx: 220, dy: 30})
ok(editor.getCursor(), 'Has text focus')
equal(editor.getCursor().stringify(), 'a')
$('.droplet-hidden-input').sendkeys('PI:KEY:<KEY>END_PI')
setTimeout((->
ok(editor.getCursor(), 'Editor still has getCursor()')
equal(editor.getCursor().stringify(), '18n')
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
ok(true, 'Does not throw on reparse')
after = $('[stroke=#F00]').length
ok(after > before, 'Marks block with a red line')
start()
), 10)
asyncTest 'Controller: Can replace a block where we found it', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
editor.setValue('for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 265, dy: 35})
equal(editor.getValue() , 'for (var i = 0; i < 5; i++) {\n' +
' fd(10);\n' +
'}\n')
simulate('mousedown', '.droplet-main-canvas', {dx: 260, dy: 30})
simulate('mousemove', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
simulate('mouseup', '.droplet-drag-cover'
{location: '.droplet-main-canvas', dx: 210, dy: 25})
equal(editor.getValue() , 'for (var i = 0; i < i++; __) {\n' +
' fd(10);\n' +
'}\n')
start()
getRandomDragOp = (editor, rng) ->
# Find the locations of all the blocks
head = editor.session.tree.start
# Skip the first block if it is the entire document
if head.next.container?.end is editor.session.tree.end.prev
head = head.next.next
dragPossibilities = []
until head is editor.session.tree.end
if head.type is 'blockStart'
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
dragPossibilities.push {
block: head.container
handle: handle
}
head = head.next
drag = dragPossibilities[Math.floor rng() * dragPossibilities.length]
# Find all the drop areas
head = editor.session.tree.start
# Disclude the main tree if we're dragging the first block
if drag is dragPossibilities[0]
head = head.next
dropPossibilities = []
until head is editor.session.tree.end
if head is drag.block.start
head = drag.block.end
if head.type.match(/Start$/)?
dropPoint = editor.session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
if head.container.type is 'block'
parent = head.container.parent
else
parent = head.container
canDrop = editor.getAcceptLevel(drag.block, head.container)
if canDrop is 1
dropPossibilities.push {
block: head.container
point: {x: dropPoint.x, y: dropPoint.y}
}
head = head.next
# If this block is not droppable, try again.
if dropPossibilities.length is 0
return getRandomDragOp(editor, rng)
drop = dropPossibilities[Math.floor rng() * dropPossibilities.length]
return {drag, drop}
generateRandomAlphabetic = (rng) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
str = ''
str += alphabet[Math.floor rng() * alphabet.length]
until rng() < 0.1
str += alphabet[Math.floor rng() * alphabet.length]
return str
getRandomTextOp = (editor, rng) ->
head = editor.session.tree.start
socketPossibilities = []
until head is editor.session.tree.end
if head.type is 'socketStart' and head.container.editable()
bound = editor.session.view.getViewNodeFor(head.container).bounds[0]
handle = {x: bound.x + 5, y: bound.y + 5}
socketPossibilities.push {
block: head.container
handle: handle
}
head = head.next
socket = socketPossibilities[Math.floor rng() * socketPossibilities.length]
text = generateRandomAlphabetic rng
return {socket, text}
performTextOperation = (editor, text, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: text.socket.handle.x + editor.gutter.clientWidth,
dy: text.socket.handle.y
})
setTimeout (->
$(editor.hiddeninput).sendkeys(text.text)
# Unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
), 0
performDragOperation = (editor, drag, cb) ->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drag.handle.x + editor.gutter.clientWidth,
dy: drag.drag.handle.y
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drag.handle.x + 5 + editor.gutter.clientWidth,
dy: drag.drag.handle.y + 5
})
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: drag.drop.point.x + 5 + editor.gutter.clientWidth
dy: drag.drop.point.y + 5
})
# Unfocus
if editor.cursorAtSocket()
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
setTimeout cb, 0
executeAsyncSequence = (sequence, i = 0) ->
if i < sequence.length
sequence[i]()
setTimeout (->
executeAsyncSequence sequence, i + 1
), 0
asyncTest 'Controller: remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 9
type: 'block'
}
dropLocation editor, 0, {
row: 2
col: 7
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
fd [0..10]
else
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 2
col: 4
type: 'block'
}
dropLocation editor, 0, {
row: 3
col: 6
type: 'indent'
}
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
), (->
editor.undo()
), (->
equal(editor.getValue(), '''
for i in ``
if i % 2 is 0
``
else
fd [0..10]
bk 10\n
''')
), (->
pickUpLocation editor, 0, {
row: 4
col: 7
type: 'block'
}
dropLocation editor, 0, {
row: 0
col: 9
type: 'socket'
}
), (->
equal(editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
``
else
fd 10
bk 10\n
''')
start()
)
]
asyncTest 'Controller: floating blocks with remembered sockets', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: true}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
fd 10
fd 20
fd 30
''')
executeAsyncSequence [
(->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Create a floating block
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 600 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.getValue(), '''
fd 20
fd 30\n
''')
equal(editor.session.floatingBlocks.length, 1)
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
simulate('mousemove', editor.dragCover, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement,
dx: 450 + 5 + editor.gutter.clientWidth,
dy: 10 + 5
})
), (->
equal(editor.session.floatingBlocks.length, 2)
equal(editor.getValue(), '''
fd 30\n
''')
), (->
pickUpLocation editor, 0, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 3
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
# Move a block from floating block 1 to 2 so as to destroy floating block 1,
# potentially messing up the undo stack and rememberedSocket records
pickUpLocation editor, 1, {
row: 0
col: 0
type: 'block'
}
# Drop in floating block
dropLocation editor, 2, {
row: 0
col: 6
type: 'socket'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
# Remove the block we just placed to invoke rememberedSocket lookup
pickUpLocation editor, 1, {
row: 0
col: 6
type: 'block'
}
# Drop in main document
dropLocation editor, 0, {
row: 0
col: 0
type: 'document'
}
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd 30
''')
equal(editor.getValue(), '''
fd 10\n
''')
), (->
editor.undo()
), (->
equal(editor.session.floatingBlocks.length, 1)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd fd fd 10
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd fd 30
''')
), (->
editor.undo()
), (->
# Ensure that the undo worked
equal(editor.session.floatingBlocks.length, 2)
equal(editor.session.floatingBlocks[0].block.stringify(), '''
fd 10
''')
equal(editor.session.floatingBlocks[1].block.stringify(), '''
fd 20
''')
equal(editor.getValue(), '''
fd 30\n
''')
start()
)
]
asyncTest 'Controller: Quoted string selection', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('fd "hello"')
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
setTimeout (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
start()
), 0
asyncTest 'Controller: Quoted string CoffeeScript autoescape', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue("fd 'hello'")
entity = editor.session.tree.getFromTextLocation({row: 0, col: 'fd '.length, type: 'socket'})
{x, y} = editor.session.view.getViewNodeFor(entity).bounds[0]
executeAsyncSequence [
(->
simulate('mousedown', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
simulate('mouseup', editor.mainCanvas, {
location: editor.dropletElement
dx: x + 5 + editor.gutter.clientWidth
dy: y + 5
})
), (->
equal editor.hiddenInput.selectionStart, 1
equal editor.hiddenInput.selectionEnd, 6
$('.droplet-hidden-input').sendkeys("h\\tel\\\\\"'lo")
), (->
# unfocus
evt = document.createEvent 'Event'
evt.initEvent 'keydown', true, true
evt.keyCode = evt.which = 13
editor.dropletElement.dispatchEvent(evt)
), (->
equal editor.getValue(), """fd 'h\\tel\\\\"\\'lo'\n"""
start()
)
]
asyncTest 'Controller: Session switch test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks 1'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 2'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 3'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 4'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 5'
blocks: [
{block: 'a is b'}
]
}
{
name: 'Blocks 6'
blocks: [
{block: 'a is b'}
]
}
]
})
originalSession = editor.aceEditor.getSession()
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
equal editor.paletteHeader.childElementCount, 3, 'Palette header originally has three rows'
newSession = ace.createEditSession('''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}
''', 'ace/mode/javascript')
executeAsyncSequence [
(->
editor.aceEditor.setSession newSession
),
(->
editor.bindNewSession({
mode: 'javascript',
palette: []
})
editor.setEditorState(true)
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks'
editor.setEditorState(false)
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
),
(->
editor.aceEditor.setSession originalSession
),
(->
equal editor.getValue(), '''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10\n
''', 'Original text restored'
equal editor.paletteWrapper.style.left is '0px', true, 'Using blocks again'
equal editor.paletteHeader.childElementCount, 3, 'Original palette header size restored'
),
(->
editor.aceEditor.setSession newSession
),
(->
equal editor.getValue(), '''
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
fd(10);
}
else {
bk(10);
}
}\n
''', 'Set value of new session'
equal editor.paletteWrapper.style.left is '0px', false, 'No longer using blocks'
equal editor.paletteHeader.childElementCount, 0, 'Palette header now empty'
start()
)
]
asyncTest 'Controller: Random drag undo test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'coffeescript',
modeOptions:
functions:
fd: {command: true, value: false}
bk: {command: true, value: false}
palette: [
{
name: 'Blocks'
blocks: [
{block: 'a is b'}
{block: 'fd 10'}
{block: 'bk 10'}
{block: '''
for i in [0..10]
``
'''}
{block: '''
if a is b
``
'''}
]
}
]
})
editor.setEditorState(true)
editor.setValue('''
for i in [0..10]
if i % 2 is 0
fd 10
else
bk 10
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
stateStack.push editor.getSerializedEditorState().toString()
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
while stateStack.length > 0
text = stateStack.pop()
while stateStack[stateStack.length - 1] is text
text = stateStack.pop()
editor.undo()
equal editor.getSerializedEditorState().toString(), text, 'Undo was correct'
start()
else
ok (not editor.cursorAtSocket()), 'Properly unfocused'
setTimeout (-> tick count - 1), 0
stateStack.push editor.getSerializedEditorState().toString()
if rng() > 0.5
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 100
###
asyncTest 'Controller: ANTLR random drag reparse test', ->
document.getElementById('test-main').innerHTML = ''
window.editor = editor = new droplet.Editor(document.getElementById('test-main'), {
mode: 'c_cpp',
modeOptions:
knownFunctions:
printf: {color: 'blue', shape: 'block-only'}
puts: {color: 'blue', shape: 'block-only'}
scanf: {color: 'blue', shape: 'block-only'}
malloc: {color: 'red', shape: 'value-only'}
palette: []
})
editor.setEditorState(true)
editor.setValue('''
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
// Linked list
struct List {
long long data;
struct List *next;
struct List *prev;
};
typedef struct List List;
// Memoryless swap
void swap(long long *a, long long *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
// Test if sorted
int sorted(List *head, int (*fn)(long long, long long)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data)) {
return 0;
}
}
return 1;
}
// Bubble sort
void sort(List *head, int (*fn)(long long, long long)) {
while (!sorted(head, fn)) {
for (List *cursor = head; cursor && cursor->next; cursor = cursor->next) {
if (!fn(cursor->data, cursor->next->data))
swap(&cursor->data, &cursor->next->data);
}
}
}
// Comparator
int comparator(long long a, long long b) {
return (a > b);
}
// Main
int main(int n, char *args[]) {
// Arbitrary array initializer just o test that syntax
int arbitraryArray[] = {1, 2, 3, 4, 5};
int length;
scanf("%d", &length);
if (length > MAXLEN) {
puts("Error: list is too large");
return 1;
}
List *head = (List*)malloc(sizeof(List));
scanf("%d", &head->data);
head->prev = NULL;
List *cursor = head;
int temp;
for (int i = 0; i < length - 1; i++) {
cursor->next = (List*)malloc(sizeof(List));
cursor = cursor->next;
scanf("%d", &temp);
cursor->data = (long long)temp;
}
sort(head, comparator);
for (cursor = head; cursor; cursor = cursor->next) {
printf("%d ", cursor->data);
}
puts("\\n");
return 0;
}
''')
rng = seedrandom('droplet')
stateStack = []
tick = (count) ->
cb = ->
if count is 0
start()
else
ok editor.session.mode.parse(editor.getValue()), 'Still in a parseable state'
setTimeout (-> tick count - 1), 0
if rng() > 0.1
op = getRandomDragOp(editor, rng)
performDragOperation editor, op, cb
else
op = getRandomTextOp(editor, rng)
performTextOperation editor, op, cb
tick 50
###
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999128580093384,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/shared.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.
# Avoid triggering submit when pressing enter since both
# submit and change will be triggered.
# Moreover, blurring the input will trigger the 'change' event.
# That part is handled by storing the submitted value in the DOM.
$(document).on 'keypress', '.js-auto-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'change'
# automatically submit on change
$(document).on 'change', '.js-auto-submit', (e) ->
$target = $(e.target)
return if $target.val() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.val())
$target.parents('form').submit()
# A class to make contenteditable fields useful inside of forms.
$(document).on 'keypress', '.content-editable-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'blur'
$(document).on 'blur', '.content-editable-submit', (e) ->
$target = $(e.target)
return if $target.html() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.html())
$form = $target.parents('form')
el = $(document.createElement('input'))
el.attr('type', 'hidden')
el.attr('name', $target.attr('data-name'))
el.attr('value', $target.html())
# temporarily add a hidden form element for this contenteditable field.
$form.append(el);
$form.submit()
# remove now that we're done submitting.
el.remove()
#populate last-submitted values
$(document).on 'turbolinks:load', ->
$('.content-editable-submit').each (_i, el) ->
$el = $(el)
$el.data('last-submitted-value', $el.html())
# fadeOut effect for popup
$(document).on 'click', '#popup-container, #overlay', (e) ->
$('#overlay').fadeOut()
$popup = $(e.target).closest('.popup-active')
$popup.fadeOut null, $popup.remove
###
# Add `disabled` attribute to form element with value _disabled.
# Currently used to work around Form::select (in store checkout -
# new address form - country selection) since it doesn't support
# adding a disabled value.
###
$(document).on 'turbolinks:load', ->
$('[value=_disabled]').attr 'disabled', true
###
# Click anywhere on row to click the main link!
# Usage:
# 1. add class `clickable-row` to the row
# 2. add class `clickable-row-link` to the link that should be
# clicked when the row is clicked
# 3. ???
# 4. profit!
# May contain caveats.
###
$(document).on 'click', '.clickable-row', (e) ->
target = e.target
return if osu.isClickable target
row = e.currentTarget
if row.classList.contains 'clickable-row-link'
row.click()
else
row.getElementsByClassName('clickable-row-link')[0]?.click()
# submit form on ctrl-enter (or cmd-enter).
$(document).on 'keydown', '.js-quick-submit', (e) ->
return unless (e.ctrlKey || e.metaKey) && e.keyCode == 13
e.preventDefault()
$(e.target).closest('form').submit()
$(document).on 'ajax:beforeSend', (e) ->
# currentTarget is document
form = e.target
return false if form._submitting
form._submitting = true
form._ujsSubmitDisabled = []
for el in form.querySelectorAll('.js-ujs-submit-disable')
continue if el.disabled
el.blur() if el.dataset.blurOnSubmitDisable == '1'
el.disabled = true
form._ujsSubmitDisabled.push el
$(document).on 'ajax:complete', (e) ->
form = e.target
form._submitting = false
el.disabled = false while el = form._ujsSubmitDisabled.pop()
| 201052 | # 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.
# Avoid triggering submit when pressing enter since both
# submit and change will be triggered.
# Moreover, blurring the input will trigger the 'change' event.
# That part is handled by storing the submitted value in the DOM.
$(document).on 'keypress', '.js-auto-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'change'
# automatically submit on change
$(document).on 'change', '.js-auto-submit', (e) ->
$target = $(e.target)
return if $target.val() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.val())
$target.parents('form').submit()
# A class to make contenteditable fields useful inside of forms.
$(document).on 'keypress', '.content-editable-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'blur'
$(document).on 'blur', '.content-editable-submit', (e) ->
$target = $(e.target)
return if $target.html() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.html())
$form = $target.parents('form')
el = $(document.createElement('input'))
el.attr('type', 'hidden')
el.attr('name', $target.attr('data-name'))
el.attr('value', $target.html())
# temporarily add a hidden form element for this contenteditable field.
$form.append(el);
$form.submit()
# remove now that we're done submitting.
el.remove()
#populate last-submitted values
$(document).on 'turbolinks:load', ->
$('.content-editable-submit').each (_i, el) ->
$el = $(el)
$el.data('last-submitted-value', $el.html())
# fadeOut effect for popup
$(document).on 'click', '#popup-container, #overlay', (e) ->
$('#overlay').fadeOut()
$popup = $(e.target).closest('.popup-active')
$popup.fadeOut null, $popup.remove
###
# Add `disabled` attribute to form element with value _disabled.
# Currently used to work around Form::select (in store checkout -
# new address form - country selection) since it doesn't support
# adding a disabled value.
###
$(document).on 'turbolinks:load', ->
$('[value=_disabled]').attr 'disabled', true
###
# Click anywhere on row to click the main link!
# Usage:
# 1. add class `clickable-row` to the row
# 2. add class `clickable-row-link` to the link that should be
# clicked when the row is clicked
# 3. ???
# 4. profit!
# May contain caveats.
###
$(document).on 'click', '.clickable-row', (e) ->
target = e.target
return if osu.isClickable target
row = e.currentTarget
if row.classList.contains 'clickable-row-link'
row.click()
else
row.getElementsByClassName('clickable-row-link')[0]?.click()
# submit form on ctrl-enter (or cmd-enter).
$(document).on 'keydown', '.js-quick-submit', (e) ->
return unless (e.ctrlKey || e.metaKey) && e.keyCode == 13
e.preventDefault()
$(e.target).closest('form').submit()
$(document).on 'ajax:beforeSend', (e) ->
# currentTarget is document
form = e.target
return false if form._submitting
form._submitting = true
form._ujsSubmitDisabled = []
for el in form.querySelectorAll('.js-ujs-submit-disable')
continue if el.disabled
el.blur() if el.dataset.blurOnSubmitDisable == '1'
el.disabled = true
form._ujsSubmitDisabled.push el
$(document).on 'ajax:complete', (e) ->
form = e.target
form._submitting = false
el.disabled = false while el = form._ujsSubmitDisabled.pop()
| 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.
# Avoid triggering submit when pressing enter since both
# submit and change will be triggered.
# Moreover, blurring the input will trigger the 'change' event.
# That part is handled by storing the submitted value in the DOM.
$(document).on 'keypress', '.js-auto-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'change'
# automatically submit on change
$(document).on 'change', '.js-auto-submit', (e) ->
$target = $(e.target)
return if $target.val() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.val())
$target.parents('form').submit()
# A class to make contenteditable fields useful inside of forms.
$(document).on 'keypress', '.content-editable-submit', (e) ->
# 13 == enter key
return unless e.which == 13
e.preventDefault()
$(e.target).trigger 'blur'
$(document).on 'blur', '.content-editable-submit', (e) ->
$target = $(e.target)
return if $target.html() == $target.data('last-submitted-value')
$target.data('last-submitted-value', $target.html())
$form = $target.parents('form')
el = $(document.createElement('input'))
el.attr('type', 'hidden')
el.attr('name', $target.attr('data-name'))
el.attr('value', $target.html())
# temporarily add a hidden form element for this contenteditable field.
$form.append(el);
$form.submit()
# remove now that we're done submitting.
el.remove()
#populate last-submitted values
$(document).on 'turbolinks:load', ->
$('.content-editable-submit').each (_i, el) ->
$el = $(el)
$el.data('last-submitted-value', $el.html())
# fadeOut effect for popup
$(document).on 'click', '#popup-container, #overlay', (e) ->
$('#overlay').fadeOut()
$popup = $(e.target).closest('.popup-active')
$popup.fadeOut null, $popup.remove
###
# Add `disabled` attribute to form element with value _disabled.
# Currently used to work around Form::select (in store checkout -
# new address form - country selection) since it doesn't support
# adding a disabled value.
###
$(document).on 'turbolinks:load', ->
$('[value=_disabled]').attr 'disabled', true
###
# Click anywhere on row to click the main link!
# Usage:
# 1. add class `clickable-row` to the row
# 2. add class `clickable-row-link` to the link that should be
# clicked when the row is clicked
# 3. ???
# 4. profit!
# May contain caveats.
###
$(document).on 'click', '.clickable-row', (e) ->
target = e.target
return if osu.isClickable target
row = e.currentTarget
if row.classList.contains 'clickable-row-link'
row.click()
else
row.getElementsByClassName('clickable-row-link')[0]?.click()
# submit form on ctrl-enter (or cmd-enter).
$(document).on 'keydown', '.js-quick-submit', (e) ->
return unless (e.ctrlKey || e.metaKey) && e.keyCode == 13
e.preventDefault()
$(e.target).closest('form').submit()
$(document).on 'ajax:beforeSend', (e) ->
# currentTarget is document
form = e.target
return false if form._submitting
form._submitting = true
form._ujsSubmitDisabled = []
for el in form.querySelectorAll('.js-ujs-submit-disable')
continue if el.disabled
el.blur() if el.dataset.blurOnSubmitDisable == '1'
el.disabled = true
form._ujsSubmitDisabled.push el
$(document).on 'ajax:complete', (e) ->
form = e.target
form._submitting = false
el.disabled = false while el = form._ujsSubmitDisabled.pop()
|
[
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 12)\n copy = attributedString.copy()\n a",
"end": 363,
"score": 0.9994275569915771,
"start": 358,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n\n substring = attributedString.attri",
"end": 1647,
"score": 0.9993594288825989,
"start": 1642,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 12)\n attributedString.replaceCharacters",
"end": 6543,
"score": 0.9996785521507263,
"start": 6538,
"tag": "NAME",
"value": "jesse"
},
{
"context": "dString.toString(true).should.equal('(Hello/name=\"jesse\")')\n attributedString.replaceCharactersInRan",
"end": 6687,
"score": 0.9997152090072632,
"start": 6682,
"tag": "NAME",
"value": "jesse"
},
{
"context": ".toString(true).should.equal('(Hello World!/name=\"jesse\")')\n\n it 'should update attribute runs when no",
"end": 6834,
"score": 0.999723494052887,
"start": 6829,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n attributedString.addAttributeInRang",
"end": 6976,
"score": 0.9996789693832397,
"start": 6971,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'joe', 5, 7)\n attributedString.toString(true).sho",
"end": 7040,
"score": 0.9996440410614014,
"start": 7037,
"tag": "NAME",
"value": "joe"
},
{
"context": "dString.toString(true).should.equal('(Hello/name=\"jesse\")( world!/name=\"joe\")')\n\n attributedString.r",
"end": 7119,
"score": 0.999693751335144,
"start": 7114,
"tag": "NAME",
"value": "jesse"
},
{
"context": ".should.equal('(Hello/name=\"jesse\")( world!/name=\"joe\")')\n\n attributedString.replaceCharactersInRa",
"end": 7139,
"score": 0.9994157552719116,
"start": 7136,
"tag": "NAME",
"value": "joe"
},
{
"context": "tedString.toString(true).should.equal('(Hel/name=\"jesse\")(rld!/name=\"joe\")')\n\n attributedString.repl",
"end": 7271,
"score": 0.9996972680091858,
"start": 7266,
"tag": "NAME",
"value": "jesse"
},
{
"context": "true).should.equal('(Hel/name=\"jesse\")(rld!/name=\"joe\")')\n\n attributedString.replaceCharactersInRa",
"end": 7288,
"score": 0.9993425607681274,
"start": 7285,
"tag": "NAME",
"value": "joe"
},
{
"context": "ring.toString(true).should.equal('(Hello wo/name=\"jesse\")(rld!/name=\"joe\")')\n\n it 'should remove leadi",
"end": 7430,
"score": 0.9996449947357178,
"start": 7425,
"tag": "NAME",
"value": "jesse"
},
{
"context": ".should.equal('(Hello wo/name=\"jesse\")(rld!/name=\"joe\")')\n\n it 'should remove leading attribute run ",
"end": 7447,
"score": 0.999039888381958,
"start": 7444,
"tag": "NAME",
"value": "joe"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 1)\n attributedString.replaceCharactersI",
"end": 7647,
"score": 0.9995956420898438,
"start": 7642,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 1)\n attributedString.replaceCharactersI",
"end": 7986,
"score": 0.9996275901794434,
"start": 7981,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n\n attributedString.attributesAtIndex",
"end": 8655,
"score": 0.9994197487831116,
"start": 8650,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(0, effectiveRange).name.should.equal('jesse')\n effectiveRange.location.should.equal(0)\n ",
"end": 8749,
"score": 0.999570369720459,
"start": 8744,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n attributedString.attributesAtIndex(",
"end": 9155,
"score": 0.9995092749595642,
"start": 9150,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(0, effectiveRange).name.should.equal('jesse')\n effectiveRange.location.should.equal(0)\n ",
"end": 9248,
"score": 0.999555766582489,
"start": 9243,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 6, 6)\n attributedString.attributesAtIndex(",
"end": 9487,
"score": 0.9994504451751709,
"start": 9482,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(6, effectiveRange).name.should.equal('jesse')\n effectiveRange.location.should.equal(6)\n ",
"end": 9580,
"score": 0.9995713233947754,
"start": 9575,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n attributedString.addAttributeInRang",
"end": 10737,
"score": 0.9995243549346924,
"start": 10732,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(0, effectiveRange).name.should.equal('jesse')\n attributedString.attributesAtIndex(0, eff",
"end": 10892,
"score": 0.9996423721313477,
"start": 10887,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 5)\n attributedString.addAttributeInRang",
"end": 11209,
"score": 0.9995335340499878,
"start": 11204,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(0, effectiveRange).name.should.equal('jesse')\n (attributedString.attributesAtIndex(0, ef",
"end": 11365,
"score": 0.9994891881942749,
"start": 11360,
"tag": "NAME",
"value": "jesse"
},
{
"context": "utesAtIndex(3, effectiveRange).name.should.equal('jesse')\n attributedString.attributesAtIndex(3, eff",
"end": 11637,
"score": 0.9995594024658203,
"start": 11632,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 12)\n attributedString.removeAttributeIn",
"end": 12195,
"score": 0.9996318817138672,
"start": 12190,
"tag": "NAME",
"value": "jesse"
},
{
"context": " attributedString.addAttributeInRange('name', 'jesse', 0, 12)\n attributedString.removeAttributeIn",
"end": 12394,
"score": 0.998802900314331,
"start": 12389,
"tag": "NAME",
"value": "jesse"
},
{
"context": "String(true).should.equal('(Hel/)(lo world!/name=\"jesse\")')\n\n attributedString.removeAttributeInRang",
"end": 12544,
"score": 0.9991855621337891,
"start": 12539,
"tag": "NAME",
"value": "jesse"
},
{
"context": ".toString(true).should.equal('(Hel/)(lo wor/name=\"jesse\")(ld!/)')\n\n it 'should return null when access",
"end": 12687,
"score": 0.9990167617797852,
"start": 12682,
"tag": "NAME",
"value": "jesse"
}
] | atom/packages/foldingtext-for-atom/spec/core/attributed-string-spec.coffee | prookie/dotfiles-1 | 0 | AttributedString = require '../../lib/core/attributed-string'
Outline = require '../../lib/core/outline'
Item = require '../../lib/core/item'
describe 'AttributedString', ->
[attributedString] = []
beforeEach ->
attributedString = new AttributedString 'Hello world!'
it 'should create copy', ->
attributedString.addAttributeInRange('name', 'jesse', 0, 12)
copy = attributedString.copy()
attributedString.toString().should.equal(copy.toString())
describe 'Get Substrings', ->
it 'should get string', ->
attributedString.string().should.equal('Hello world!')
it 'should get substring', ->
attributedString.string(0, 5).should.equal('Hello')
attributedString.string(6, 6).should.equal('world!')
it 'should get attributed substring from start', ->
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/)')
it 'should get attributed substring from end', ->
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(world!/)')
it 'should get full attributed substring', ->
substring = attributedString.attributedSubstring()
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
it 'should get empty attributed substring', ->
attributedString.attributedSubstring(1, 0).toString().should.equal('(/)')
it 'should get attributed substring with attributes', ->
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/name)')
it 'should get attributed substring with overlapping attributes', ->
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.addAttributeInRange('b', null, 4, 3)
attributedString.toString().should.equal('(Hell/i)(o w/b, i)(orld!/i)')
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(w/b, i)(orld!/i)')
describe 'Delete Characters', ->
it 'should delete from start', ->
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should delete from end', ->
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
it 'should delete from middle', ->
attributedString.deleteCharactersInRange(3, 5)
attributedString.toString().should.equal('(Helrld!/)')
it 'should adjust attribute run when deleting from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 1)
attributedString.toString().should.equal('(ello/b)( world!/)')
it 'should adjust attribute run when deleting from end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(3, 2)
attributedString.toString().should.equal('(Hel/b)( world!/)')
it 'should adjust attribute run when deleting from middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(2, 2)
attributedString.toString().should.equal('(Heo/b)( world!/)')
it 'should adjust attribute run when overlapping start', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 2)
attributedString.toString().should.equal('(Hello/)(orld!/b)')
it 'should adjust attribute run when overlapping end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(4, 2)
attributedString.toString().should.equal('(Hell/b)(world!/)')
it 'should remove attribute run when covering from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should remove attribute run when covering from end', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
describe 'Insert String', ->
it 'should insert at start', ->
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello world!/)')
it 'should insert at end', ->
attributedString.insertStringAtLocation('Boo!', 12)
attributedString.toString().should.equal('(Hello world!Boo!/)')
it 'should insert in middle', ->
attributedString.insertStringAtLocation('Boo!', 6)
attributedString.toString().should.equal('(Hello Boo!world!/)')
it 'should insert into empty string', ->
attributedString.deleteCharactersInRange(0, 12)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!/)')
it 'should adjust attribute run when inserting at run start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello/b)( world!/)')
it 'should adjust attribute run when inserting at run end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 5)
attributedString.toString().should.equal('(HelloBoo!/b)( world!/)')
it 'should adjust attribute run when inserting in run middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 3)
attributedString.toString().should.equal('(HelBoo!lo/b)( world!/)')
it 'should insert attributed string including runs', ->
insert = new AttributedString('Boo!')
insert.addAttributeInRange('i', null, 0, 3)
insert.addAttributeInRange('b', null, 1, 3)
attributedString.insertStringAtLocation(insert, 0)
attributedString.toString().should.equal('(B/i)(oo/b, i)(!/b)(Hello world!/)')
describe 'Replace Substrings', ->
it 'should update attribute runs when attributed string is modified', ->
attributedString.addAttributeInRange('name', 'jesse', 0, 12)
attributedString.replaceCharactersInRange('Hello', 0, 12)
attributedString.toString(true).should.equal('(Hello/name="jesse")')
attributedString.replaceCharactersInRange(' World!', 5, 0)
attributedString.toString(true).should.equal('(Hello World!/name="jesse")')
it 'should update attribute runs when node text is paritially updated', ->
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
attributedString.addAttributeInRange('name', 'joe', 5, 7)
attributedString.toString(true).should.equal('(Hello/name="jesse")( world!/name="joe")')
attributedString.replaceCharactersInRange('', 3, 5)
attributedString.toString(true).should.equal('(Hel/name="jesse")(rld!/name="joe")')
attributedString.replaceCharactersInRange('lo wo', 3, 0)
attributedString.toString(true).should.equal('(Hello wo/name="jesse")(rld!/name="joe")')
it 'should remove leading attribute run if text in run is fully replaced', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', 'jesse', 0, 1)
attributedString.replaceCharactersInRange('', 0, 1)
attributedString.toString().should.equal('(two/)')
it 'should retain attributes of fully replaced range if replacing string length is not zero.', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', 'jesse', 0, 1)
attributedString.replaceCharactersInRange('h', 0, 1)
attributedString.toString().should.equal('(h/name)(two/)')
it 'should allow inserting of another attributed string', ->
newString = new AttributedString('two')
newString.addAttributeInRange('b', null, 0, 3)
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.replaceCharactersInRange(newString, 5, 1)
attributedString.toString().should.equal('(Hello/i)(two/b)(world!/i)')
describe 'Add/Remove/Find Attributes', ->
it 'should add attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('jesse')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
attributedString.attributesAtIndex(5, effectiveRange).should.eql({})
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(7)
it 'should add attribute run bordering start of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('jesse')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attribute run bordering end of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'jesse', 6, 6)
attributedString.attributesAtIndex(6, effectiveRange).name.should.equal('jesse')
effectiveRange.location.should.equal(6)
effectiveRange.length.should.equal(6)
it 'should find longest effective range for attribute', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString.attributeAtIndex('one', 6, null, longestEffectiveRange).should.equal('one')
longestEffectiveRange.location.should.equal(0)
longestEffectiveRange.length.should.equal(12)
it 'should find longest effective range for attributes', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString._indexOfAttributeRunForCharacterIndex(10) # artificial split
attributedString.attributesAtIndex(6, null, longestEffectiveRange)
longestEffectiveRange.location.should.equal(6)
longestEffectiveRange.length.should.equal(6)
it 'should add multiple attributes in same attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
attributedString.addAttributeInRange('age', '35', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('jesse')
attributedString.attributesAtIndex(0, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attributes in overlapping ranges', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'jesse', 0, 5)
attributedString.addAttributeInRange('age', '35', 3, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('jesse')
(attributedString.attributesAtIndex(0, effectiveRange).age is undefined).should.be.true
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(3)
attributedString.attributesAtIndex(3, effectiveRange).name.should.equal('jesse')
attributedString.attributesAtIndex(3, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(3)
effectiveRange.length.should.equal(2)
(attributedString.attributesAtIndex(6, effectiveRange).name is undefined).should.be.true
attributedString.attributesAtIndex(6, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(3)
it 'should allow removing attributes in range', ->
attributedString.addAttributeInRange('name', 'jesse', 0, 12)
attributedString.removeAttributeInRange('name', 0, 12)
attributedString.toString(true).should.equal('(Hello world!/)')
attributedString.addAttributeInRange('name', 'jesse', 0, 12)
attributedString.removeAttributeInRange('name', 0, 3)
attributedString.toString(true).should.equal('(Hel/)(lo world!/name="jesse")')
attributedString.removeAttributeInRange('name', 9, 3)
attributedString.toString(true).should.equal('(Hel/)(lo wor/name="jesse")(ld!/)')
it 'should return null when accessing attributes at end of string', ->
expect(attributedString.attributesAtIndex(0, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(11, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(12, null) is null).toBe(true)
attributedString.replaceCharactersInRange('', 0, 12)
expect(attributedString.attributesAtIndex(0, null) is null).toBe(true)
describe 'Inline FTML', ->
describe 'To Inline FTML', ->
it 'should convert to Inline FTML', ->
attributedString.toInlineFTMLString().should.equal('Hello world!')
it 'should convert to Inline FTML with attributes', ->
attributedString.addAttributeInRange('B', 'data-my': 'test', 3, 5)
attributedString.toInlineFTMLString().should.equal('Hel<b data-my="test">lo wo</b>rld!')
it 'should convert empty to Inline FTML', ->
new AttributedString().toInlineFTMLString().should.equal('')
describe 'From Inline FTML', ->
it 'should convert from Inline FTML', ->
AttributedString.fromInlineFTMLString('Hello world!').toString().should.equal('(Hello world!/)')
it 'should convert from Inline FTML with attributes', ->
AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!').toString(true).should.equal('(Hel/)(lo wo/B={"data-my":"test"})(rld!/)')
it 'should convert from empty Inline FTML', ->
AttributedString.fromInlineFTMLString('').toString().should.equal('(/)')
describe 'Offset Mapping', ->
it 'should map from string to Inline FTML offsets', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 0
AttributedString.textOffsetToInlineFTMLOffset(3, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 3
AttributedString.textOffsetToInlineFTMLOffset(4, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.firstChild
offset: 1
AttributedString.textOffsetToInlineFTMLOffset(12, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset: 4
it 'should map from string to empty Inline FTML offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer
offset: 0
it 'should map from Inline FTML offsets to string', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
node = inlineFTMLContainer.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(0)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(3)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 1
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(4)
node = inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset = 4
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(12)
it 'should map from empty Inline FTML to string offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.inlineFTMLOffsetToTextOffset(inlineFTMLContainer, 0, inlineFTMLContainer).should.equal(0)
| 143796 | AttributedString = require '../../lib/core/attributed-string'
Outline = require '../../lib/core/outline'
Item = require '../../lib/core/item'
describe 'AttributedString', ->
[attributedString] = []
beforeEach ->
attributedString = new AttributedString 'Hello world!'
it 'should create copy', ->
attributedString.addAttributeInRange('name', '<NAME>', 0, 12)
copy = attributedString.copy()
attributedString.toString().should.equal(copy.toString())
describe 'Get Substrings', ->
it 'should get string', ->
attributedString.string().should.equal('Hello world!')
it 'should get substring', ->
attributedString.string(0, 5).should.equal('Hello')
attributedString.string(6, 6).should.equal('world!')
it 'should get attributed substring from start', ->
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/)')
it 'should get attributed substring from end', ->
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(world!/)')
it 'should get full attributed substring', ->
substring = attributedString.attributedSubstring()
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
it 'should get empty attributed substring', ->
attributedString.attributedSubstring(1, 0).toString().should.equal('(/)')
it 'should get attributed substring with attributes', ->
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/name)')
it 'should get attributed substring with overlapping attributes', ->
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.addAttributeInRange('b', null, 4, 3)
attributedString.toString().should.equal('(Hell/i)(o w/b, i)(orld!/i)')
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(w/b, i)(orld!/i)')
describe 'Delete Characters', ->
it 'should delete from start', ->
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should delete from end', ->
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
it 'should delete from middle', ->
attributedString.deleteCharactersInRange(3, 5)
attributedString.toString().should.equal('(Helrld!/)')
it 'should adjust attribute run when deleting from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 1)
attributedString.toString().should.equal('(ello/b)( world!/)')
it 'should adjust attribute run when deleting from end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(3, 2)
attributedString.toString().should.equal('(Hel/b)( world!/)')
it 'should adjust attribute run when deleting from middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(2, 2)
attributedString.toString().should.equal('(Heo/b)( world!/)')
it 'should adjust attribute run when overlapping start', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 2)
attributedString.toString().should.equal('(Hello/)(orld!/b)')
it 'should adjust attribute run when overlapping end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(4, 2)
attributedString.toString().should.equal('(Hell/b)(world!/)')
it 'should remove attribute run when covering from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should remove attribute run when covering from end', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
describe 'Insert String', ->
it 'should insert at start', ->
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello world!/)')
it 'should insert at end', ->
attributedString.insertStringAtLocation('Boo!', 12)
attributedString.toString().should.equal('(Hello world!Boo!/)')
it 'should insert in middle', ->
attributedString.insertStringAtLocation('Boo!', 6)
attributedString.toString().should.equal('(Hello Boo!world!/)')
it 'should insert into empty string', ->
attributedString.deleteCharactersInRange(0, 12)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!/)')
it 'should adjust attribute run when inserting at run start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello/b)( world!/)')
it 'should adjust attribute run when inserting at run end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 5)
attributedString.toString().should.equal('(HelloBoo!/b)( world!/)')
it 'should adjust attribute run when inserting in run middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 3)
attributedString.toString().should.equal('(HelBoo!lo/b)( world!/)')
it 'should insert attributed string including runs', ->
insert = new AttributedString('Boo!')
insert.addAttributeInRange('i', null, 0, 3)
insert.addAttributeInRange('b', null, 1, 3)
attributedString.insertStringAtLocation(insert, 0)
attributedString.toString().should.equal('(B/i)(oo/b, i)(!/b)(Hello world!/)')
describe 'Replace Substrings', ->
it 'should update attribute runs when attributed string is modified', ->
attributedString.addAttributeInRange('name', '<NAME>', 0, 12)
attributedString.replaceCharactersInRange('Hello', 0, 12)
attributedString.toString(true).should.equal('(Hello/name="<NAME>")')
attributedString.replaceCharactersInRange(' World!', 5, 0)
attributedString.toString(true).should.equal('(Hello World!/name="<NAME>")')
it 'should update attribute runs when node text is paritially updated', ->
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
attributedString.addAttributeInRange('name', '<NAME>', 5, 7)
attributedString.toString(true).should.equal('(Hello/name="<NAME>")( world!/name="<NAME>")')
attributedString.replaceCharactersInRange('', 3, 5)
attributedString.toString(true).should.equal('(Hel/name="<NAME>")(rld!/name="<NAME>")')
attributedString.replaceCharactersInRange('lo wo', 3, 0)
attributedString.toString(true).should.equal('(Hello wo/name="<NAME>")(rld!/name="<NAME>")')
it 'should remove leading attribute run if text in run is fully replaced', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', '<NAME>', 0, 1)
attributedString.replaceCharactersInRange('', 0, 1)
attributedString.toString().should.equal('(two/)')
it 'should retain attributes of fully replaced range if replacing string length is not zero.', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', '<NAME>', 0, 1)
attributedString.replaceCharactersInRange('h', 0, 1)
attributedString.toString().should.equal('(h/name)(two/)')
it 'should allow inserting of another attributed string', ->
newString = new AttributedString('two')
newString.addAttributeInRange('b', null, 0, 3)
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.replaceCharactersInRange(newString, 5, 1)
attributedString.toString().should.equal('(Hello/i)(two/b)(world!/i)')
describe 'Add/Remove/Find Attributes', ->
it 'should add attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('<NAME>')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
attributedString.attributesAtIndex(5, effectiveRange).should.eql({})
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(7)
it 'should add attribute run bordering start of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('<NAME>')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attribute run bordering end of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', '<NAME>', 6, 6)
attributedString.attributesAtIndex(6, effectiveRange).name.should.equal('<NAME>')
effectiveRange.location.should.equal(6)
effectiveRange.length.should.equal(6)
it 'should find longest effective range for attribute', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString.attributeAtIndex('one', 6, null, longestEffectiveRange).should.equal('one')
longestEffectiveRange.location.should.equal(0)
longestEffectiveRange.length.should.equal(12)
it 'should find longest effective range for attributes', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString._indexOfAttributeRunForCharacterIndex(10) # artificial split
attributedString.attributesAtIndex(6, null, longestEffectiveRange)
longestEffectiveRange.location.should.equal(6)
longestEffectiveRange.length.should.equal(6)
it 'should add multiple attributes in same attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
attributedString.addAttributeInRange('age', '35', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('<NAME>')
attributedString.attributesAtIndex(0, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attributes in overlapping ranges', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', '<NAME>', 0, 5)
attributedString.addAttributeInRange('age', '35', 3, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('<NAME>')
(attributedString.attributesAtIndex(0, effectiveRange).age is undefined).should.be.true
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(3)
attributedString.attributesAtIndex(3, effectiveRange).name.should.equal('<NAME>')
attributedString.attributesAtIndex(3, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(3)
effectiveRange.length.should.equal(2)
(attributedString.attributesAtIndex(6, effectiveRange).name is undefined).should.be.true
attributedString.attributesAtIndex(6, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(3)
it 'should allow removing attributes in range', ->
attributedString.addAttributeInRange('name', '<NAME>', 0, 12)
attributedString.removeAttributeInRange('name', 0, 12)
attributedString.toString(true).should.equal('(Hello world!/)')
attributedString.addAttributeInRange('name', '<NAME>', 0, 12)
attributedString.removeAttributeInRange('name', 0, 3)
attributedString.toString(true).should.equal('(Hel/)(lo world!/name="<NAME>")')
attributedString.removeAttributeInRange('name', 9, 3)
attributedString.toString(true).should.equal('(Hel/)(lo wor/name="<NAME>")(ld!/)')
it 'should return null when accessing attributes at end of string', ->
expect(attributedString.attributesAtIndex(0, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(11, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(12, null) is null).toBe(true)
attributedString.replaceCharactersInRange('', 0, 12)
expect(attributedString.attributesAtIndex(0, null) is null).toBe(true)
describe 'Inline FTML', ->
describe 'To Inline FTML', ->
it 'should convert to Inline FTML', ->
attributedString.toInlineFTMLString().should.equal('Hello world!')
it 'should convert to Inline FTML with attributes', ->
attributedString.addAttributeInRange('B', 'data-my': 'test', 3, 5)
attributedString.toInlineFTMLString().should.equal('Hel<b data-my="test">lo wo</b>rld!')
it 'should convert empty to Inline FTML', ->
new AttributedString().toInlineFTMLString().should.equal('')
describe 'From Inline FTML', ->
it 'should convert from Inline FTML', ->
AttributedString.fromInlineFTMLString('Hello world!').toString().should.equal('(Hello world!/)')
it 'should convert from Inline FTML with attributes', ->
AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!').toString(true).should.equal('(Hel/)(lo wo/B={"data-my":"test"})(rld!/)')
it 'should convert from empty Inline FTML', ->
AttributedString.fromInlineFTMLString('').toString().should.equal('(/)')
describe 'Offset Mapping', ->
it 'should map from string to Inline FTML offsets', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 0
AttributedString.textOffsetToInlineFTMLOffset(3, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 3
AttributedString.textOffsetToInlineFTMLOffset(4, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.firstChild
offset: 1
AttributedString.textOffsetToInlineFTMLOffset(12, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset: 4
it 'should map from string to empty Inline FTML offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer
offset: 0
it 'should map from Inline FTML offsets to string', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
node = inlineFTMLContainer.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(0)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(3)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 1
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(4)
node = inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset = 4
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(12)
it 'should map from empty Inline FTML to string offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.inlineFTMLOffsetToTextOffset(inlineFTMLContainer, 0, inlineFTMLContainer).should.equal(0)
| true | AttributedString = require '../../lib/core/attributed-string'
Outline = require '../../lib/core/outline'
Item = require '../../lib/core/item'
describe 'AttributedString', ->
[attributedString] = []
beforeEach ->
attributedString = new AttributedString 'Hello world!'
it 'should create copy', ->
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 12)
copy = attributedString.copy()
attributedString.toString().should.equal(copy.toString())
describe 'Get Substrings', ->
it 'should get string', ->
attributedString.string().should.equal('Hello world!')
it 'should get substring', ->
attributedString.string(0, 5).should.equal('Hello')
attributedString.string(6, 6).should.equal('world!')
it 'should get attributed substring from start', ->
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/)')
it 'should get attributed substring from end', ->
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(world!/)')
it 'should get full attributed substring', ->
substring = attributedString.attributedSubstring()
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
it 'should get empty attributed substring', ->
attributedString.attributedSubstring(1, 0).toString().should.equal('(/)')
it 'should get attributed substring with attributes', ->
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
substring = attributedString.attributedSubstring(0, 12)
substring.toString().should.equal(attributedString.toString())
substring = attributedString.attributedSubstring(0, 5)
substring.toString().should.equal('(Hello/name)')
it 'should get attributed substring with overlapping attributes', ->
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.addAttributeInRange('b', null, 4, 3)
attributedString.toString().should.equal('(Hell/i)(o w/b, i)(orld!/i)')
substring = attributedString.attributedSubstring(6, 6)
substring.toString().should.equal('(w/b, i)(orld!/i)')
describe 'Delete Characters', ->
it 'should delete from start', ->
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should delete from end', ->
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
it 'should delete from middle', ->
attributedString.deleteCharactersInRange(3, 5)
attributedString.toString().should.equal('(Helrld!/)')
it 'should adjust attribute run when deleting from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 1)
attributedString.toString().should.equal('(ello/b)( world!/)')
it 'should adjust attribute run when deleting from end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(3, 2)
attributedString.toString().should.equal('(Hel/b)( world!/)')
it 'should adjust attribute run when deleting from middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(2, 2)
attributedString.toString().should.equal('(Heo/b)( world!/)')
it 'should adjust attribute run when overlapping start', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 2)
attributedString.toString().should.equal('(Hello/)(orld!/b)')
it 'should adjust attribute run when overlapping end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(4, 2)
attributedString.toString().should.equal('(Hell/b)(world!/)')
it 'should remove attribute run when covering from start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.deleteCharactersInRange(0, 6)
attributedString.toString().should.equal('(world!/)')
it 'should remove attribute run when covering from end', ->
attributedString.addAttributeInRange('b', null, 6, 6)
attributedString.deleteCharactersInRange(5, 7)
attributedString.toString().should.equal('(Hello/)')
describe 'Insert String', ->
it 'should insert at start', ->
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello world!/)')
it 'should insert at end', ->
attributedString.insertStringAtLocation('Boo!', 12)
attributedString.toString().should.equal('(Hello world!Boo!/)')
it 'should insert in middle', ->
attributedString.insertStringAtLocation('Boo!', 6)
attributedString.toString().should.equal('(Hello Boo!world!/)')
it 'should insert into empty string', ->
attributedString.deleteCharactersInRange(0, 12)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!/)')
it 'should adjust attribute run when inserting at run start', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 0)
attributedString.toString().should.equal('(Boo!Hello/b)( world!/)')
it 'should adjust attribute run when inserting at run end', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 5)
attributedString.toString().should.equal('(HelloBoo!/b)( world!/)')
it 'should adjust attribute run when inserting in run middle', ->
attributedString.addAttributeInRange('b', null, 0, 5)
attributedString.insertStringAtLocation('Boo!', 3)
attributedString.toString().should.equal('(HelBoo!lo/b)( world!/)')
it 'should insert attributed string including runs', ->
insert = new AttributedString('Boo!')
insert.addAttributeInRange('i', null, 0, 3)
insert.addAttributeInRange('b', null, 1, 3)
attributedString.insertStringAtLocation(insert, 0)
attributedString.toString().should.equal('(B/i)(oo/b, i)(!/b)(Hello world!/)')
describe 'Replace Substrings', ->
it 'should update attribute runs when attributed string is modified', ->
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 12)
attributedString.replaceCharactersInRange('Hello', 0, 12)
attributedString.toString(true).should.equal('(Hello/name="PI:NAME:<NAME>END_PI")')
attributedString.replaceCharactersInRange(' World!', 5, 0)
attributedString.toString(true).should.equal('(Hello World!/name="PI:NAME:<NAME>END_PI")')
it 'should update attribute runs when node text is paritially updated', ->
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 5, 7)
attributedString.toString(true).should.equal('(Hello/name="PI:NAME:<NAME>END_PI")( world!/name="PI:NAME:<NAME>END_PI")')
attributedString.replaceCharactersInRange('', 3, 5)
attributedString.toString(true).should.equal('(Hel/name="PI:NAME:<NAME>END_PI")(rld!/name="PI:NAME:<NAME>END_PI")')
attributedString.replaceCharactersInRange('lo wo', 3, 0)
attributedString.toString(true).should.equal('(Hello wo/name="PI:NAME:<NAME>END_PI")(rld!/name="PI:NAME:<NAME>END_PI")')
it 'should remove leading attribute run if text in run is fully replaced', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 1)
attributedString.replaceCharactersInRange('', 0, 1)
attributedString.toString().should.equal('(two/)')
it 'should retain attributes of fully replaced range if replacing string length is not zero.', ->
attributedString = new AttributedString('\ttwo')
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 1)
attributedString.replaceCharactersInRange('h', 0, 1)
attributedString.toString().should.equal('(h/name)(two/)')
it 'should allow inserting of another attributed string', ->
newString = new AttributedString('two')
newString.addAttributeInRange('b', null, 0, 3)
attributedString.addAttributeInRange('i', null, 0, 12)
attributedString.replaceCharactersInRange(newString, 5, 1)
attributedString.toString().should.equal('(Hello/i)(two/b)(world!/i)')
describe 'Add/Remove/Find Attributes', ->
it 'should add attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
attributedString.attributesAtIndex(5, effectiveRange).should.eql({})
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(7)
it 'should add attribute run bordering start of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attribute run bordering end of string', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 6, 6)
attributedString.attributesAtIndex(6, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
effectiveRange.location.should.equal(6)
effectiveRange.length.should.equal(6)
it 'should find longest effective range for attribute', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString.attributeAtIndex('one', 6, null, longestEffectiveRange).should.equal('one')
longestEffectiveRange.location.should.equal(0)
longestEffectiveRange.length.should.equal(12)
it 'should find longest effective range for attributes', ->
longestEffectiveRange = {}
attributedString.addAttributeInRange('one', 'one', 0, 12)
attributedString.addAttributeInRange('two', 'two', 6, 6)
attributedString._indexOfAttributeRunForCharacterIndex(10) # artificial split
attributedString.attributesAtIndex(6, null, longestEffectiveRange)
longestEffectiveRange.location.should.equal(6)
longestEffectiveRange.length.should.equal(6)
it 'should add multiple attributes in same attribute run', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
attributedString.addAttributeInRange('age', '35', 0, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
attributedString.attributesAtIndex(0, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(5)
it 'should add attributes in overlapping ranges', ->
effectiveRange = {}
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 5)
attributedString.addAttributeInRange('age', '35', 3, 5)
attributedString.attributesAtIndex(0, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
(attributedString.attributesAtIndex(0, effectiveRange).age is undefined).should.be.true
effectiveRange.location.should.equal(0)
effectiveRange.length.should.equal(3)
attributedString.attributesAtIndex(3, effectiveRange).name.should.equal('PI:NAME:<NAME>END_PI')
attributedString.attributesAtIndex(3, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(3)
effectiveRange.length.should.equal(2)
(attributedString.attributesAtIndex(6, effectiveRange).name is undefined).should.be.true
attributedString.attributesAtIndex(6, effectiveRange).age.should.equal('35')
effectiveRange.location.should.equal(5)
effectiveRange.length.should.equal(3)
it 'should allow removing attributes in range', ->
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 12)
attributedString.removeAttributeInRange('name', 0, 12)
attributedString.toString(true).should.equal('(Hello world!/)')
attributedString.addAttributeInRange('name', 'PI:NAME:<NAME>END_PI', 0, 12)
attributedString.removeAttributeInRange('name', 0, 3)
attributedString.toString(true).should.equal('(Hel/)(lo world!/name="PI:NAME:<NAME>END_PI")')
attributedString.removeAttributeInRange('name', 9, 3)
attributedString.toString(true).should.equal('(Hel/)(lo wor/name="PI:NAME:<NAME>END_PI")(ld!/)')
it 'should return null when accessing attributes at end of string', ->
expect(attributedString.attributesAtIndex(0, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(11, null) isnt null).toBe(true)
expect(attributedString.attributesAtIndex(12, null) is null).toBe(true)
attributedString.replaceCharactersInRange('', 0, 12)
expect(attributedString.attributesAtIndex(0, null) is null).toBe(true)
describe 'Inline FTML', ->
describe 'To Inline FTML', ->
it 'should convert to Inline FTML', ->
attributedString.toInlineFTMLString().should.equal('Hello world!')
it 'should convert to Inline FTML with attributes', ->
attributedString.addAttributeInRange('B', 'data-my': 'test', 3, 5)
attributedString.toInlineFTMLString().should.equal('Hel<b data-my="test">lo wo</b>rld!')
it 'should convert empty to Inline FTML', ->
new AttributedString().toInlineFTMLString().should.equal('')
describe 'From Inline FTML', ->
it 'should convert from Inline FTML', ->
AttributedString.fromInlineFTMLString('Hello world!').toString().should.equal('(Hello world!/)')
it 'should convert from Inline FTML with attributes', ->
AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!').toString(true).should.equal('(Hel/)(lo wo/B={"data-my":"test"})(rld!/)')
it 'should convert from empty Inline FTML', ->
AttributedString.fromInlineFTMLString('').toString().should.equal('(/)')
describe 'Offset Mapping', ->
it 'should map from string to Inline FTML offsets', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 0
AttributedString.textOffsetToInlineFTMLOffset(3, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild
offset: 3
AttributedString.textOffsetToInlineFTMLOffset(4, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.firstChild
offset: 1
AttributedString.textOffsetToInlineFTMLOffset(12, inlineFTMLContainer).should.eql
node: inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset: 4
it 'should map from string to empty Inline FTML offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.textOffsetToInlineFTMLOffset(0, inlineFTMLContainer).should.eql
node: inlineFTMLContainer
offset: 0
it 'should map from Inline FTML offsets to string', ->
attributedString = AttributedString.fromInlineFTMLString('Hel<b data-my="test">lo wo</b>rld!')
inlineFTMLContainer = attributedString.toInlineFTMLFragment()
node = inlineFTMLContainer.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(0)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 0
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(3)
node = inlineFTMLContainer.firstChild.nextSibling.firstChild
offset = 1
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(4)
node = inlineFTMLContainer.firstChild.nextSibling.nextSibling
offset = 4
AttributedString.inlineFTMLOffsetToTextOffset(node, offset, inlineFTMLContainer).should.equal(12)
it 'should map from empty Inline FTML to string offsets', ->
inlineFTMLContainer = document.createElement 'p'
AttributedString.inlineFTMLOffsetToTextOffset(inlineFTMLContainer, 0, inlineFTMLContainer).should.equal(0)
|
[
{
"context": "ount: changesCounter\n\t\t\t)\n\t$scope.user =\n\t\tname: 'hello'\n\t\tlastname: 'world'\n\n\tdo ->\n\t\ttimer = null\n\t\t$sc",
"end": 1993,
"score": 0.9706974625587463,
"start": 1988,
"tag": "NAME",
"value": "hello"
}
] | app/scripts/controllers/controllers.coffee | SKorolchuk/angular-educational-app | 0 | 'use strict'
angular.module 'SKorolchuk.AngularStudy'
.controller 'MainCtrl', ($scope, $location, $window, version, $state) ->
$scope.$path = $location.path.bind($location)
$scope.$state = $state
$scope.version = version
.controller 'ProductCtrl', ($scope, $state, $stateParams, productService) ->
$scope.products = productService.products
$scope.productId = $stateParams['id']
$scope.isCurrentProduct = (element) ->
+$scope.productId == element.id
$scope.goToDetails = (product) ->
$state.go('product_info', {'id' : product.id })
$scope.goBack = ->
$state.go('products')
.controller 'StatisticCtrl', ($scope, productService, $timeout) ->
reduceProductsByPrice = (product, low, high) ->
+product.price >= low && +product.price < high
$scope.chartConfig =
title: 'Products Cost'
tooltips: true
labels: false
legend:
display: true
position: 'left'
generateNewStats = () ->
$scope.products = ({name: 'test ' + i, price: Math.random(+new Date()) * 100 / 1.7, id: i } for i in [1..100])
$scope.statisticsData =
series: _.range(1,100,10),
data: do ->
_data = []
_points = _.range(1,100,10)
for point, i in _points
_data.push
'x': point
'y': [_.where((result = reduceProductsByPrice(product, point, (if i != _points.length then _points[i+1] else 1000000)) for product in $scope.products), (o) -> o).length]
'tooltip': 'hello world'
_data
$timeout generateNewStats, 6000
generateNewStats()
.controller 'TestCtrl', ($scope, $filter, $interpolate, $timeout) ->
$scope.numbers = [1,2,3,4,5]
$scope.filteredNums = $filter('isOdd') $scope.numbers
$scope.Login = (user) ->
alert('login ' + user.name + ' ' + user.lastname)
$scope.Register = (user) ->
alert('register ' + user.name)
do ->
changesCounter = 0
$scope.switcherChanged = () ->
changesCounter++
$scope.changesMessage = $interpolate('You changed number {{count}} times!')(
count: changesCounter
)
$scope.user =
name: 'hello'
lastname: 'world'
do ->
timer = null
$scope.$watch 'switcher', (newVal) ->
if (newVal)
if (timer)
$timeout.cancel(timer)
timer = $timeout () ->
alert("You switch to #{newVal}")
, 350
.controller 'TreeCtrl', ($scope) ->
$scope.ops = 0
| 66623 | 'use strict'
angular.module 'SKorolchuk.AngularStudy'
.controller 'MainCtrl', ($scope, $location, $window, version, $state) ->
$scope.$path = $location.path.bind($location)
$scope.$state = $state
$scope.version = version
.controller 'ProductCtrl', ($scope, $state, $stateParams, productService) ->
$scope.products = productService.products
$scope.productId = $stateParams['id']
$scope.isCurrentProduct = (element) ->
+$scope.productId == element.id
$scope.goToDetails = (product) ->
$state.go('product_info', {'id' : product.id })
$scope.goBack = ->
$state.go('products')
.controller 'StatisticCtrl', ($scope, productService, $timeout) ->
reduceProductsByPrice = (product, low, high) ->
+product.price >= low && +product.price < high
$scope.chartConfig =
title: 'Products Cost'
tooltips: true
labels: false
legend:
display: true
position: 'left'
generateNewStats = () ->
$scope.products = ({name: 'test ' + i, price: Math.random(+new Date()) * 100 / 1.7, id: i } for i in [1..100])
$scope.statisticsData =
series: _.range(1,100,10),
data: do ->
_data = []
_points = _.range(1,100,10)
for point, i in _points
_data.push
'x': point
'y': [_.where((result = reduceProductsByPrice(product, point, (if i != _points.length then _points[i+1] else 1000000)) for product in $scope.products), (o) -> o).length]
'tooltip': 'hello world'
_data
$timeout generateNewStats, 6000
generateNewStats()
.controller 'TestCtrl', ($scope, $filter, $interpolate, $timeout) ->
$scope.numbers = [1,2,3,4,5]
$scope.filteredNums = $filter('isOdd') $scope.numbers
$scope.Login = (user) ->
alert('login ' + user.name + ' ' + user.lastname)
$scope.Register = (user) ->
alert('register ' + user.name)
do ->
changesCounter = 0
$scope.switcherChanged = () ->
changesCounter++
$scope.changesMessage = $interpolate('You changed number {{count}} times!')(
count: changesCounter
)
$scope.user =
name: '<NAME>'
lastname: 'world'
do ->
timer = null
$scope.$watch 'switcher', (newVal) ->
if (newVal)
if (timer)
$timeout.cancel(timer)
timer = $timeout () ->
alert("You switch to #{newVal}")
, 350
.controller 'TreeCtrl', ($scope) ->
$scope.ops = 0
| true | 'use strict'
angular.module 'SKorolchuk.AngularStudy'
.controller 'MainCtrl', ($scope, $location, $window, version, $state) ->
$scope.$path = $location.path.bind($location)
$scope.$state = $state
$scope.version = version
.controller 'ProductCtrl', ($scope, $state, $stateParams, productService) ->
$scope.products = productService.products
$scope.productId = $stateParams['id']
$scope.isCurrentProduct = (element) ->
+$scope.productId == element.id
$scope.goToDetails = (product) ->
$state.go('product_info', {'id' : product.id })
$scope.goBack = ->
$state.go('products')
.controller 'StatisticCtrl', ($scope, productService, $timeout) ->
reduceProductsByPrice = (product, low, high) ->
+product.price >= low && +product.price < high
$scope.chartConfig =
title: 'Products Cost'
tooltips: true
labels: false
legend:
display: true
position: 'left'
generateNewStats = () ->
$scope.products = ({name: 'test ' + i, price: Math.random(+new Date()) * 100 / 1.7, id: i } for i in [1..100])
$scope.statisticsData =
series: _.range(1,100,10),
data: do ->
_data = []
_points = _.range(1,100,10)
for point, i in _points
_data.push
'x': point
'y': [_.where((result = reduceProductsByPrice(product, point, (if i != _points.length then _points[i+1] else 1000000)) for product in $scope.products), (o) -> o).length]
'tooltip': 'hello world'
_data
$timeout generateNewStats, 6000
generateNewStats()
.controller 'TestCtrl', ($scope, $filter, $interpolate, $timeout) ->
$scope.numbers = [1,2,3,4,5]
$scope.filteredNums = $filter('isOdd') $scope.numbers
$scope.Login = (user) ->
alert('login ' + user.name + ' ' + user.lastname)
$scope.Register = (user) ->
alert('register ' + user.name)
do ->
changesCounter = 0
$scope.switcherChanged = () ->
changesCounter++
$scope.changesMessage = $interpolate('You changed number {{count}} times!')(
count: changesCounter
)
$scope.user =
name: 'PI:NAME:<NAME>END_PI'
lastname: 'world'
do ->
timer = null
$scope.$watch 'switcher', (newVal) ->
if (newVal)
if (timer)
$timeout.cancel(timer)
timer = $timeout () ->
alert("You switch to #{newVal}")
, 350
.controller 'TreeCtrl', ($scope) ->
$scope.ops = 0
|
[
{
"context": "y(\n usernameField: 'email'\n passwordField: 'password'\n ,\n (username, password, done) ->\n models.u",
"end": 480,
"score": 0.9962759613990784,
"start": 472,
"tag": "PASSWORD",
"value": "password"
}
] | server/src/services/authentication.coffee | natevecc/jeff-project | 0 | models = require '../models'
Promise = require 'bluebird'
bcrypt = Promise.promisifyAll require('bcrypt')
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
passport.serializeUser (user, done) ->
done null, user.get('id')
passport.deserializeUser (id, done) ->
models.user.findById(id)
.then (user) ->
done null, user
, (err) ->
done err, null
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: 'password'
,
(username, password, done) ->
models.user.findOne(
where:
email: username)
.bind({})
.then (user) ->
this.user = user
bcrypt.compareAsync(password, user.get('password'))
.then (passwordsMatch) ->
if not this.user
return done null, false, message: 'Unknown user'
else if not passwordsMatch
done null, false, message: 'Invalid password'
else
done null, this.user
.catch (err) ->
done err
)
# helper function to be used in routes to authenticate resources
passport.authMiddleware = (req, res, next) ->
if req.isAuthenticated()
return next()
res
.status 401
.end()
module.exports = passport
| 174035 | models = require '../models'
Promise = require 'bluebird'
bcrypt = Promise.promisifyAll require('bcrypt')
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
passport.serializeUser (user, done) ->
done null, user.get('id')
passport.deserializeUser (id, done) ->
models.user.findById(id)
.then (user) ->
done null, user
, (err) ->
done err, null
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: '<PASSWORD>'
,
(username, password, done) ->
models.user.findOne(
where:
email: username)
.bind({})
.then (user) ->
this.user = user
bcrypt.compareAsync(password, user.get('password'))
.then (passwordsMatch) ->
if not this.user
return done null, false, message: 'Unknown user'
else if not passwordsMatch
done null, false, message: 'Invalid password'
else
done null, this.user
.catch (err) ->
done err
)
# helper function to be used in routes to authenticate resources
passport.authMiddleware = (req, res, next) ->
if req.isAuthenticated()
return next()
res
.status 401
.end()
module.exports = passport
| true | models = require '../models'
Promise = require 'bluebird'
bcrypt = Promise.promisifyAll require('bcrypt')
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
passport.serializeUser (user, done) ->
done null, user.get('id')
passport.deserializeUser (id, done) ->
models.user.findById(id)
.then (user) ->
done null, user
, (err) ->
done err, null
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
,
(username, password, done) ->
models.user.findOne(
where:
email: username)
.bind({})
.then (user) ->
this.user = user
bcrypt.compareAsync(password, user.get('password'))
.then (passwordsMatch) ->
if not this.user
return done null, false, message: 'Unknown user'
else if not passwordsMatch
done null, false, message: 'Invalid password'
else
done null, this.user
.catch (err) ->
done err
)
# helper function to be used in routes to authenticate resources
passport.authMiddleware = (req, res, next) ->
if req.isAuthenticated()
return next()
res
.status 401
.end()
module.exports = passport
|
[
{
"context": "true\n ipa:\n principal: 'admin'\n password: 'admin_pw'\n # referer: 'https://freeipa.nikita.local/ipa",
"end": 93,
"score": 0.9991156458854675,
"start": 85,
"tag": "PASSWORD",
"value": "admin_pw"
},
{
"context": "al'\n ,\n label: 'remote'\n ssh:\n host: '127.0.0.1', username: process.env.USER,\n private_key_p",
"end": 288,
"score": 0.9997362494468689,
"start": 279,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | packages/ipa/env/ipa/test.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: 'admin_pw'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://ipa.nikita.local/ipa/session/json'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
| 140244 |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: '<PASSWORD>'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://ipa.nikita.local/ipa/session/json'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
| true |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://ipa.nikita.local/ipa/session/json'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
|
[
{
"context": "64')\n\n data =\n user_id: user_id\n key: gen_token()\n scope: util.normalize_scope(options.scope",
"end": 602,
"score": 0.8480386734008789,
"start": 593,
"tag": "KEY",
"value": "gen_token"
}
] | lib/guard.coffee | danielmwai/oauth2-node | 0 | URL = require 'url'
crypto = require 'crypto'
util = require './util'
Err = require './error'
module.exports = class Guard extends require('./options')
constructor: ->
super
@._accessor 'storage'
throw new Error("Please provide 'storage' for OAuth Guard") unless @storage
issue_token: (user_id, options, done) ->
if typeof options == 'function'
done = options
options = {}
options = @_effective options
gen_token = -> crypto.createHash('sha512').update(crypto.randomBytes(128)).digest('base64')
data =
user_id: user_id
key: gen_token()
scope: util.normalize_scope(options.scope).join(',')
expire: util.normalize_expire(options.expire) if options.expire
expire_at: util.normalize_expire(options.expire_at) if options.expire_at
@storage.save_token_data data, (error, token) ->
return done?(error) if error
done?(null, token)
revoke_token: (token, done) ->
@storage.delete_token_data token, done
middleware: (options) ->
options = @_effective options
realm = options.realm || "Server"
scope = util.normalize_scope options.scope
storage = options.storage
debug = options.debug || { warn:(->) }
invalid_request = new Err "Invalid request", code:'invalid_request', realm:realm, scope:scope, status:400
invalid_token = new Err "Invalid token", code:'invalid_token', realm:realm, scope:scope, status:401
expired_token = new Err "Expired token", code:'expired_token', realm:realm, scope:scope, status:401
insufficient_scope = new Err "Insufficient scope", code:'insufficient_scope', realm:realm, scope:scope, status:403
check_scope = (token_scope) ->
token_scope = util.normalize_scope token_scope
# TODO: implement
true
expired = (data) ->
data.expire < Date.now() if data.expire
(req, res, next) ->
token = Guard.findOAuthToken req
debug.warn "Verifying oauth token from client", req.ip, token
return next invalid_request unless token
if req.oauth?.access_token == token
return next insufficient_scope unless check_scope req.oauth.scope
storage.get_token_data token, (err, data) ->
debug.warn "Got token data from client", req.ip, data
return next invalid_token unless data?.user_id
return next expired_token if expired data
return next insufficient_scope unless check_scope data.scope
req.oauth = data
debug.warn "Token data from client is valid", req.ip
next()
Guard.findOAuthToken = (req) ->
auth = req.headers['authorization']?.split(' ')
(auth[1] if auth?[0] == 'OAuth') or
(URL.parse(req.url, true).query?.access_token) or
(req.session?.access_token)
| 127189 | URL = require 'url'
crypto = require 'crypto'
util = require './util'
Err = require './error'
module.exports = class Guard extends require('./options')
constructor: ->
super
@._accessor 'storage'
throw new Error("Please provide 'storage' for OAuth Guard") unless @storage
issue_token: (user_id, options, done) ->
if typeof options == 'function'
done = options
options = {}
options = @_effective options
gen_token = -> crypto.createHash('sha512').update(crypto.randomBytes(128)).digest('base64')
data =
user_id: user_id
key: <KEY>()
scope: util.normalize_scope(options.scope).join(',')
expire: util.normalize_expire(options.expire) if options.expire
expire_at: util.normalize_expire(options.expire_at) if options.expire_at
@storage.save_token_data data, (error, token) ->
return done?(error) if error
done?(null, token)
revoke_token: (token, done) ->
@storage.delete_token_data token, done
middleware: (options) ->
options = @_effective options
realm = options.realm || "Server"
scope = util.normalize_scope options.scope
storage = options.storage
debug = options.debug || { warn:(->) }
invalid_request = new Err "Invalid request", code:'invalid_request', realm:realm, scope:scope, status:400
invalid_token = new Err "Invalid token", code:'invalid_token', realm:realm, scope:scope, status:401
expired_token = new Err "Expired token", code:'expired_token', realm:realm, scope:scope, status:401
insufficient_scope = new Err "Insufficient scope", code:'insufficient_scope', realm:realm, scope:scope, status:403
check_scope = (token_scope) ->
token_scope = util.normalize_scope token_scope
# TODO: implement
true
expired = (data) ->
data.expire < Date.now() if data.expire
(req, res, next) ->
token = Guard.findOAuthToken req
debug.warn "Verifying oauth token from client", req.ip, token
return next invalid_request unless token
if req.oauth?.access_token == token
return next insufficient_scope unless check_scope req.oauth.scope
storage.get_token_data token, (err, data) ->
debug.warn "Got token data from client", req.ip, data
return next invalid_token unless data?.user_id
return next expired_token if expired data
return next insufficient_scope unless check_scope data.scope
req.oauth = data
debug.warn "Token data from client is valid", req.ip
next()
Guard.findOAuthToken = (req) ->
auth = req.headers['authorization']?.split(' ')
(auth[1] if auth?[0] == 'OAuth') or
(URL.parse(req.url, true).query?.access_token) or
(req.session?.access_token)
| true | URL = require 'url'
crypto = require 'crypto'
util = require './util'
Err = require './error'
module.exports = class Guard extends require('./options')
constructor: ->
super
@._accessor 'storage'
throw new Error("Please provide 'storage' for OAuth Guard") unless @storage
issue_token: (user_id, options, done) ->
if typeof options == 'function'
done = options
options = {}
options = @_effective options
gen_token = -> crypto.createHash('sha512').update(crypto.randomBytes(128)).digest('base64')
data =
user_id: user_id
key: PI:KEY:<KEY>END_PI()
scope: util.normalize_scope(options.scope).join(',')
expire: util.normalize_expire(options.expire) if options.expire
expire_at: util.normalize_expire(options.expire_at) if options.expire_at
@storage.save_token_data data, (error, token) ->
return done?(error) if error
done?(null, token)
revoke_token: (token, done) ->
@storage.delete_token_data token, done
middleware: (options) ->
options = @_effective options
realm = options.realm || "Server"
scope = util.normalize_scope options.scope
storage = options.storage
debug = options.debug || { warn:(->) }
invalid_request = new Err "Invalid request", code:'invalid_request', realm:realm, scope:scope, status:400
invalid_token = new Err "Invalid token", code:'invalid_token', realm:realm, scope:scope, status:401
expired_token = new Err "Expired token", code:'expired_token', realm:realm, scope:scope, status:401
insufficient_scope = new Err "Insufficient scope", code:'insufficient_scope', realm:realm, scope:scope, status:403
check_scope = (token_scope) ->
token_scope = util.normalize_scope token_scope
# TODO: implement
true
expired = (data) ->
data.expire < Date.now() if data.expire
(req, res, next) ->
token = Guard.findOAuthToken req
debug.warn "Verifying oauth token from client", req.ip, token
return next invalid_request unless token
if req.oauth?.access_token == token
return next insufficient_scope unless check_scope req.oauth.scope
storage.get_token_data token, (err, data) ->
debug.warn "Got token data from client", req.ip, data
return next invalid_token unless data?.user_id
return next expired_token if expired data
return next insufficient_scope unless check_scope data.scope
req.oauth = data
debug.warn "Token data from client is valid", req.ip
next()
Guard.findOAuthToken = (req) ->
auth = req.headers['authorization']?.split(' ')
(auth[1] if auth?[0] == 'OAuth') or
(URL.parse(req.url, true).query?.access_token) or
(req.session?.access_token)
|
[
{
"context": "te'].size()\n @.by_Type._keys().assert_Is ['participant-remote','participant']\n @.by_Funded['yes'].size()",
"end": 628,
"score": 0.7789159417152405,
"start": 610,
"tag": "KEY",
"value": "participant-remote"
}
] | src/server/test/Participants.test.coffee | shooking/owasp-summit-2017 | 101 | Jekyll_Data = require '../src/Jekyll-Data'
describe 'Jekyll Data | Participants', ->
participants = null
beforeEach ->
participants = new Jekyll_Data().participants
using participants,->
@.jekyll_Data.folder_Root.assert_Folder_Exists()
@.file_Yaml_Lists.file_Name().assert_Is 'lists.yml'
it 'map_Lists', ->
using participants, ->
using @.map_Lists(), ->
@.all_Participants.size().assert_Is_Bigger_Than 150
#@.all_Participants.size().assert_Is @.by_Type['participant'].size() + @.by_Type['participant-remote'].size()
@.by_Type._keys().assert_Is ['participant-remote','participant']
@.by_Funded['yes'].size().assert_Is_Bigger_Than 24
@.file_Json_Lists.assert_File_Exists()
@.file_Yaml_Lists.assert_File_Exists()
| 38351 | Jekyll_Data = require '../src/Jekyll-Data'
describe 'Jekyll Data | Participants', ->
participants = null
beforeEach ->
participants = new Jekyll_Data().participants
using participants,->
@.jekyll_Data.folder_Root.assert_Folder_Exists()
@.file_Yaml_Lists.file_Name().assert_Is 'lists.yml'
it 'map_Lists', ->
using participants, ->
using @.map_Lists(), ->
@.all_Participants.size().assert_Is_Bigger_Than 150
#@.all_Participants.size().assert_Is @.by_Type['participant'].size() + @.by_Type['participant-remote'].size()
@.by_Type._keys().assert_Is ['<KEY>','participant']
@.by_Funded['yes'].size().assert_Is_Bigger_Than 24
@.file_Json_Lists.assert_File_Exists()
@.file_Yaml_Lists.assert_File_Exists()
| true | Jekyll_Data = require '../src/Jekyll-Data'
describe 'Jekyll Data | Participants', ->
participants = null
beforeEach ->
participants = new Jekyll_Data().participants
using participants,->
@.jekyll_Data.folder_Root.assert_Folder_Exists()
@.file_Yaml_Lists.file_Name().assert_Is 'lists.yml'
it 'map_Lists', ->
using participants, ->
using @.map_Lists(), ->
@.all_Participants.size().assert_Is_Bigger_Than 150
#@.all_Participants.size().assert_Is @.by_Type['participant'].size() + @.by_Type['participant-remote'].size()
@.by_Type._keys().assert_Is ['PI:KEY:<KEY>END_PI','participant']
@.by_Funded['yes'].size().assert_Is_Bigger_Than 24
@.file_Json_Lists.assert_File_Exists()
@.file_Yaml_Lists.assert_File_Exists()
|
[
{
"context": " message: 'Update documentation'\n repo: 'git@github.com:' + process.env.TRAVIS_REPO_SLUG\n watch:\n ",
"end": 1962,
"score": 0.9966700673103333,
"start": 1948,
"tag": "EMAIL",
"value": "git@github.com"
}
] | Gruntfile.coffee | hpautonomy/topic-map | 0 | module.exports = (grunt) ->
jasmineRequireTemplate = require 'grunt-template-jasmine-requirejs'
documentation = 'doc'
jasmineSpecRunner = 'spec-runner.html'
specs = 'test/spec/**/*.js'
source = 'src/js/**/*.js'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
clean: [
'bin'
'.grunt'
documentation
jasmineSpecRunner
]
connect:
server:
options:
port: 8000
useAvailablePort: true
jasmine:
test:
src: source
options:
keepRunner: false
outfile: jasmineSpecRunner
specs: specs
template: jasmineRequireTemplate
templateOptions:
requireConfigFile: 'test/require-config.js'
jsdoc:
dist:
src: ['src/js/topicmap.js', 'README.md']
options:
destination: documentation
template: 'node_modules/ink-docstrap/template'
configure: 'jsdoc.conf.json'
jshint:
all: [
source
specs
],
options:
asi: true
bitwise: true
browser: true
camelcase: true
curly: true
devel: true
eqeqeq: true
es3: true
expr: true
forin: true
freeze: true
jquery: true
latedef: true
newcap: true
noarg: true
noempty: true
nonbsp: true
undef: true
unused: true
globals:
define: false
expect: false
it: false
require: false
describe: false
beforeEach: false
afterEach: false
jasmine: false
autn: false
'gh-pages':
'default':
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
travis:
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
repo: 'git@github.com:' + process.env.TRAVIS_REPO_SLUG
watch:
doc:
files: [source, 'README.md']
tasks: ['doc']
buildTest:
files: [specs, source]
tasks: ['jasmine:test:build']
test:
files: [specs, source]
tasks: ['jasmine:test']
grunt.loadNpmTasks 'grunt-gh-pages'
grunt.loadNpmTasks 'grunt-jsdoc'
grunt.loadNpmTasks 'grunt-contrib-jshint'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-contrib-jasmine'
grunt.registerTask 'doc', ['jsdoc']
grunt.registerTask 'push-doc', ['doc', 'gh-pages:default']
grunt.registerTask 'push-doc-travis', ['doc', 'gh-pages:travis']
grunt.registerTask 'lint', ['jshint']
grunt.registerTask 'test', ['jasmine:test']
grunt.registerTask 'watch-doc', ['watch:doc']
grunt.registerTask 'watch-test', ['jasmine:test', 'watch:test']
grunt.registerTask 'browser-test', ['jasmine:test:build', 'connect:server', 'watch:buildTest']
| 60039 | module.exports = (grunt) ->
jasmineRequireTemplate = require 'grunt-template-jasmine-requirejs'
documentation = 'doc'
jasmineSpecRunner = 'spec-runner.html'
specs = 'test/spec/**/*.js'
source = 'src/js/**/*.js'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
clean: [
'bin'
'.grunt'
documentation
jasmineSpecRunner
]
connect:
server:
options:
port: 8000
useAvailablePort: true
jasmine:
test:
src: source
options:
keepRunner: false
outfile: jasmineSpecRunner
specs: specs
template: jasmineRequireTemplate
templateOptions:
requireConfigFile: 'test/require-config.js'
jsdoc:
dist:
src: ['src/js/topicmap.js', 'README.md']
options:
destination: documentation
template: 'node_modules/ink-docstrap/template'
configure: 'jsdoc.conf.json'
jshint:
all: [
source
specs
],
options:
asi: true
bitwise: true
browser: true
camelcase: true
curly: true
devel: true
eqeqeq: true
es3: true
expr: true
forin: true
freeze: true
jquery: true
latedef: true
newcap: true
noarg: true
noempty: true
nonbsp: true
undef: true
unused: true
globals:
define: false
expect: false
it: false
require: false
describe: false
beforeEach: false
afterEach: false
jasmine: false
autn: false
'gh-pages':
'default':
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
travis:
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
repo: '<EMAIL>:' + process.env.TRAVIS_REPO_SLUG
watch:
doc:
files: [source, 'README.md']
tasks: ['doc']
buildTest:
files: [specs, source]
tasks: ['jasmine:test:build']
test:
files: [specs, source]
tasks: ['jasmine:test']
grunt.loadNpmTasks 'grunt-gh-pages'
grunt.loadNpmTasks 'grunt-jsdoc'
grunt.loadNpmTasks 'grunt-contrib-jshint'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-contrib-jasmine'
grunt.registerTask 'doc', ['jsdoc']
grunt.registerTask 'push-doc', ['doc', 'gh-pages:default']
grunt.registerTask 'push-doc-travis', ['doc', 'gh-pages:travis']
grunt.registerTask 'lint', ['jshint']
grunt.registerTask 'test', ['jasmine:test']
grunt.registerTask 'watch-doc', ['watch:doc']
grunt.registerTask 'watch-test', ['jasmine:test', 'watch:test']
grunt.registerTask 'browser-test', ['jasmine:test:build', 'connect:server', 'watch:buildTest']
| true | module.exports = (grunt) ->
jasmineRequireTemplate = require 'grunt-template-jasmine-requirejs'
documentation = 'doc'
jasmineSpecRunner = 'spec-runner.html'
specs = 'test/spec/**/*.js'
source = 'src/js/**/*.js'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
clean: [
'bin'
'.grunt'
documentation
jasmineSpecRunner
]
connect:
server:
options:
port: 8000
useAvailablePort: true
jasmine:
test:
src: source
options:
keepRunner: false
outfile: jasmineSpecRunner
specs: specs
template: jasmineRequireTemplate
templateOptions:
requireConfigFile: 'test/require-config.js'
jsdoc:
dist:
src: ['src/js/topicmap.js', 'README.md']
options:
destination: documentation
template: 'node_modules/ink-docstrap/template'
configure: 'jsdoc.conf.json'
jshint:
all: [
source
specs
],
options:
asi: true
bitwise: true
browser: true
camelcase: true
curly: true
devel: true
eqeqeq: true
es3: true
expr: true
forin: true
freeze: true
jquery: true
latedef: true
newcap: true
noarg: true
noempty: true
nonbsp: true
undef: true
unused: true
globals:
define: false
expect: false
it: false
require: false
describe: false
beforeEach: false
afterEach: false
jasmine: false
autn: false
'gh-pages':
'default':
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
travis:
src: '**/*'
options:
base: 'doc'
message: 'Update documentation'
repo: 'PI:EMAIL:<EMAIL>END_PI:' + process.env.TRAVIS_REPO_SLUG
watch:
doc:
files: [source, 'README.md']
tasks: ['doc']
buildTest:
files: [specs, source]
tasks: ['jasmine:test:build']
test:
files: [specs, source]
tasks: ['jasmine:test']
grunt.loadNpmTasks 'grunt-gh-pages'
grunt.loadNpmTasks 'grunt-jsdoc'
grunt.loadNpmTasks 'grunt-contrib-jshint'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-contrib-jasmine'
grunt.registerTask 'doc', ['jsdoc']
grunt.registerTask 'push-doc', ['doc', 'gh-pages:default']
grunt.registerTask 'push-doc-travis', ['doc', 'gh-pages:travis']
grunt.registerTask 'lint', ['jshint']
grunt.registerTask 'test', ['jasmine:test']
grunt.registerTask 'watch-doc', ['watch:doc']
grunt.registerTask 'watch-test', ['jasmine:test', 'watch:test']
grunt.registerTask 'browser-test', ['jasmine:test:build', 'connect:server', 'watch:buildTest']
|
[
{
"context": " path: 'tao-quan.mp4'\n# name: 'Tao Quan'\n# }\n ]\n }\n\n when",
"end": 2013,
"score": 0.9995883703231812,
"start": 2005,
"tag": "NAME",
"value": "Tao Quan"
}
] | lib/streamer.coffee | tungv/video-streaming | 1 | config = require 'config'
logger = require('log4js').getLogger('streamer')
fs = require 'fs'
ffmpeg = require 'fluent-ffmpeg'
BinaryServer = require('binaryjs').BinaryServer
bs = new BinaryServer {port: config['streamer']['port']}
getPath = (path)-> __dirname + '/../video/' + path
createStream = (stream, fileName, {start, end}, cb) ->
path = getPath fileName
command = new ffmpeg { source: path, timeout: 0, logger }
#outputStream = fs.createWriteStream()
start = start or 0
end = end or start + 60
duration = end - start
logger.debug 'path', path
logger.debug 'start', start
logger.debug 'end', end
logger.debug 'duration', duration
logger.debug 'stream', stream
command
#.addOption('-threads', config['ffmpeg']['maxthreads'] || 4)
.setStartTime(0)
.setDuration(60)
.on("start", (commandLine) ->
console.log "Spawned FFmpeg with command: " + commandLine
return
).on("codecData", (data) ->
console.log "Input is " + data.audio + " audio with " + data.video + " video"
return
).on("progress", (progress) ->
console.log "Processing: " + progress.percent + "% done"
return
).on("error", (err) ->
console.log "Cannot process video: " + err.message
logger.debug err
cb err
return
).on("end", ->
cb null
# The 'end' event is emitted when FFmpeg finishes
# processing.
console.log "Processing finished successfully"
return
)
.writeToStream stream
#.saveToFile '/tmp/video-1.webm'
return stream
bs.on 'connection', (client)->
client.on 'stream', (stream, meta)->
switch meta.event
when 'list'
stream.write {
videos: [
{
path: 'trailer.webm'
name: 'trailer'
}
{
path: 'nyan.webm'
name: 'nyan'
}
{
path: 'mv.webm'
name: 'Music Video'
}
# {
# path: 'tao-quan.mp4'
# name: 'Tao Quan'
# }
]
}
when 'request'
#stat = fs.statSync getPath meta.path
#stream.write {size: stat.size }
#stream = fs.createReadStream __dirname + '/../video/' + meta.path , start: meta.start, end: meta.end
createStream stream, meta.path, meta, ()->
stream = fs.createReadStream '/tmp/video-1.webm'
client.send stream
#videoStream = createStream stream, meta.path, meta
#client.send videoStream, meta | 75763 | config = require 'config'
logger = require('log4js').getLogger('streamer')
fs = require 'fs'
ffmpeg = require 'fluent-ffmpeg'
BinaryServer = require('binaryjs').BinaryServer
bs = new BinaryServer {port: config['streamer']['port']}
getPath = (path)-> __dirname + '/../video/' + path
createStream = (stream, fileName, {start, end}, cb) ->
path = getPath fileName
command = new ffmpeg { source: path, timeout: 0, logger }
#outputStream = fs.createWriteStream()
start = start or 0
end = end or start + 60
duration = end - start
logger.debug 'path', path
logger.debug 'start', start
logger.debug 'end', end
logger.debug 'duration', duration
logger.debug 'stream', stream
command
#.addOption('-threads', config['ffmpeg']['maxthreads'] || 4)
.setStartTime(0)
.setDuration(60)
.on("start", (commandLine) ->
console.log "Spawned FFmpeg with command: " + commandLine
return
).on("codecData", (data) ->
console.log "Input is " + data.audio + " audio with " + data.video + " video"
return
).on("progress", (progress) ->
console.log "Processing: " + progress.percent + "% done"
return
).on("error", (err) ->
console.log "Cannot process video: " + err.message
logger.debug err
cb err
return
).on("end", ->
cb null
# The 'end' event is emitted when FFmpeg finishes
# processing.
console.log "Processing finished successfully"
return
)
.writeToStream stream
#.saveToFile '/tmp/video-1.webm'
return stream
bs.on 'connection', (client)->
client.on 'stream', (stream, meta)->
switch meta.event
when 'list'
stream.write {
videos: [
{
path: 'trailer.webm'
name: 'trailer'
}
{
path: 'nyan.webm'
name: 'nyan'
}
{
path: 'mv.webm'
name: 'Music Video'
}
# {
# path: 'tao-quan.mp4'
# name: '<NAME>'
# }
]
}
when 'request'
#stat = fs.statSync getPath meta.path
#stream.write {size: stat.size }
#stream = fs.createReadStream __dirname + '/../video/' + meta.path , start: meta.start, end: meta.end
createStream stream, meta.path, meta, ()->
stream = fs.createReadStream '/tmp/video-1.webm'
client.send stream
#videoStream = createStream stream, meta.path, meta
#client.send videoStream, meta | true | config = require 'config'
logger = require('log4js').getLogger('streamer')
fs = require 'fs'
ffmpeg = require 'fluent-ffmpeg'
BinaryServer = require('binaryjs').BinaryServer
bs = new BinaryServer {port: config['streamer']['port']}
getPath = (path)-> __dirname + '/../video/' + path
createStream = (stream, fileName, {start, end}, cb) ->
path = getPath fileName
command = new ffmpeg { source: path, timeout: 0, logger }
#outputStream = fs.createWriteStream()
start = start or 0
end = end or start + 60
duration = end - start
logger.debug 'path', path
logger.debug 'start', start
logger.debug 'end', end
logger.debug 'duration', duration
logger.debug 'stream', stream
command
#.addOption('-threads', config['ffmpeg']['maxthreads'] || 4)
.setStartTime(0)
.setDuration(60)
.on("start", (commandLine) ->
console.log "Spawned FFmpeg with command: " + commandLine
return
).on("codecData", (data) ->
console.log "Input is " + data.audio + " audio with " + data.video + " video"
return
).on("progress", (progress) ->
console.log "Processing: " + progress.percent + "% done"
return
).on("error", (err) ->
console.log "Cannot process video: " + err.message
logger.debug err
cb err
return
).on("end", ->
cb null
# The 'end' event is emitted when FFmpeg finishes
# processing.
console.log "Processing finished successfully"
return
)
.writeToStream stream
#.saveToFile '/tmp/video-1.webm'
return stream
bs.on 'connection', (client)->
client.on 'stream', (stream, meta)->
switch meta.event
when 'list'
stream.write {
videos: [
{
path: 'trailer.webm'
name: 'trailer'
}
{
path: 'nyan.webm'
name: 'nyan'
}
{
path: 'mv.webm'
name: 'Music Video'
}
# {
# path: 'tao-quan.mp4'
# name: 'PI:NAME:<NAME>END_PI'
# }
]
}
when 'request'
#stat = fs.statSync getPath meta.path
#stream.write {size: stat.size }
#stream = fs.createReadStream __dirname + '/../video/' + meta.path , start: meta.start, end: meta.end
createStream stream, meta.path, meta, ()->
stream = fs.createReadStream '/tmp/video-1.webm'
client.send stream
#videoStream = createStream stream, meta.path, meta
#client.send videoStream, meta |
[
{
"context": "\tcallbackCount = 0\n\t\t\texpectedArgs = id: 1, name:'one', created: new Date(), sub: { sub1: 1, sub2: 2}\n\t",
"end": 3784,
"score": 0.9882181882858276,
"start": 3781,
"tag": "NAME",
"value": "one"
}
] | test/cache.coffee | adamchester/gistblog-express | 1 | describe 'cache', ->
util = require 'util'
_ = require 'underscore'
assert = require 'assert'
events = require 'events'
logging = require '../lib/logging'
th = require './test_helpers'
a = require './asserters'
cache = require '../lib/cache'
# helpers
isFunction = (fn) -> _.isFunction(fn)
describe 'exports', ->
publicOptionNames = [ 'expiryMinutes', 'getLogger' ]
defaultExpiryMinutes = 5.0
cacheAssertions =
getOptions: [ a.ReturnValueEquals( publicOptionNames ) ]
getOption: [ a.ReturnValueEquals( defaultExpiryMinutes, 'expiryMinutes' ) ]
setOption: [ a.IsFunction ]
cachify: [ a.IsFunction ]
it 'should be valid', (done) -> a.verify cacheAssertions, '../lib/cache', done
describe 'option', ->
describe 'getLogger', ->
it 'should get and set correctly', -> # todo
it 'should cause future cachified methods to use the configured logger', -> # todo
describe 'expiryMinutes', ->
it 'should get and set correctly', ->
oldExpiryMinutes = cache.getOption('expiryMinutes')
cache.setOption('expiryMinutes', oldExpiryMinutes + 1)
assert.equal cache.getOption('expiryMinutes'), oldExpiryMinutes + 1
it 'should cause future cachified methods to use the default, without affecting existing cachified methods', ->
originalExpiryMinutes = cache.getOption('expiryMinutes')
originalCachified = cache.cachify((cb) -> cb())
cache.setOption('expiryMinutes', originalExpiryMinutes + 1)
newCachified = cache.cachify((cb) -> cb())
assert.equal originalCachified.getOptions().expiryMinutes, originalExpiryMinutes
assert.equal newCachified.getOptions().expiryMinutes, originalExpiryMinutes + 1
describe 'cachify', ->
it 'should have a valid cache name when no cache name provided', ->
cachedMethod = cache.cachify((cb) -> cb())
assert cachedMethod.getOptions().cacheName, 'did not find a valid cacheName'
it 'should return the cache object, with public methods, without error', (done) ->
methodToCache = (opt, cb) -> cb() # just call back
assert.doesNotThrow ->
cachedMethod = cache.cachify(methodToCache, { args: {}, updateCacheOnCreation: true })
assert cachedMethod
assert isFunction(cachedMethod.get)
assert isFunction(cachedMethod.update)
assert isFunction(cachedMethod.getOptions)
done()
it 'should execute the cache object when called with no arguments, without error', (done) ->
methodToCache = (cb) -> cb() # just call back
cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
done()
it 'should throw an error if no args were passed in but the method requires args', (done) ->
assert.throws ->
invalidMethodToCache = (opt, cb) -> cb() # method requires args (opt)
cachedMethod = cache.cachify(invalidMethodToCache, { args: undefined }) # args not defined
done()
it 'should throw an error if args were passed in but the method requires no args', (done) ->
assert.throws ->
invalidMethodToCache = (cb) -> cb() # method requires no args (just callback)
cachedMethod = cache.cachify(invalidMethodToCache, { args: {} }) # args defined
done()
describe 'get', ->
it 'should execute the callback with an error when the initial caching gives an error', ->
expectedError = new Error('test error')
methodToCache = (cb) -> cb(expectedError)
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) ->
assert value is undefined, 'should recieve \'undefined\' for value when initial cache update results in an error'
assert error, 'the error should be truthy'
assert.equal expectedError, error, 'got an unexpected error'
it 'should call the cached method with the correct arguments', (done) ->
callbackCount = 0
expectedArgs = id: 1, name:'one', created: new Date(), sub: { sub1: 1, sub2: 2}
methodToCache = (opt, cb) -> callbackCount++; assert.deepEqual(expectedArgs, opt); cb(null)
cachedMethod = cache.cachify methodToCache, { args: expectedArgs, updateCacheOnCreation: false }
cachedMethod.get (error, value) -> assert.equal(callbackCount, 1); done()
it 'should return the previously cached result on the 2nd execution', (done) ->
expectedCallbackCount = 1
actualCallbackCount = 0
methodToCache = (cb) -> cb(null, { count: ++actualCallbackCount }) # inc call count, return it as the cached value
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) -> #first call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
cachedMethod.get (error, value) -> #second call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
done()
it 'should return the initialCachedValue without blocking when initialCachedValue is non-null', (done) ->
callbackCount = 0
seed = { initial: true }
methodToCache = (cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
cachedMethod = cache.cachify(methodToCache, { initialCachedValue: seed })
cachedMethod.get (err, value) ->
assert.equal(callbackCount, 0, 'expected the cached method not to have been called yet')
assert.deepEqual(seed, value, 'expected the first returned value to be the initial seed')
done()
it 'should automatically update the cached value (async) updateCacheOnCreation is true', (done) ->
# TODO: unsure how to do this yet either
# callbackCount = 0
# methodToCache = (opt, cb) -> cb(null, { count: ++callbackCount })
# cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
# # calling get will ensure we block until the first cache update happened
# cachedMethod.get (err, value) ->
# assert.equal callbackCount, 1
done()
it 'should allow multiple calls, all of which should block until the initial cache update', (done) ->
# should allow multiple calls, all of which should block until the initial cache update
done()
it 'should not call the cached method more than once at a time before the initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should not call the cached method more than once at a time after initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should update the cached value after the specified # of minutes', (done) ->
# methodToCache = (opt, cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
# cachedMethod = cache.cachify methodToCache, { expiryMinutes: 0.01 }
# TODO: should update the cached value after the specified # of minutes
done()
| 123662 | describe 'cache', ->
util = require 'util'
_ = require 'underscore'
assert = require 'assert'
events = require 'events'
logging = require '../lib/logging'
th = require './test_helpers'
a = require './asserters'
cache = require '../lib/cache'
# helpers
isFunction = (fn) -> _.isFunction(fn)
describe 'exports', ->
publicOptionNames = [ 'expiryMinutes', 'getLogger' ]
defaultExpiryMinutes = 5.0
cacheAssertions =
getOptions: [ a.ReturnValueEquals( publicOptionNames ) ]
getOption: [ a.ReturnValueEquals( defaultExpiryMinutes, 'expiryMinutes' ) ]
setOption: [ a.IsFunction ]
cachify: [ a.IsFunction ]
it 'should be valid', (done) -> a.verify cacheAssertions, '../lib/cache', done
describe 'option', ->
describe 'getLogger', ->
it 'should get and set correctly', -> # todo
it 'should cause future cachified methods to use the configured logger', -> # todo
describe 'expiryMinutes', ->
it 'should get and set correctly', ->
oldExpiryMinutes = cache.getOption('expiryMinutes')
cache.setOption('expiryMinutes', oldExpiryMinutes + 1)
assert.equal cache.getOption('expiryMinutes'), oldExpiryMinutes + 1
it 'should cause future cachified methods to use the default, without affecting existing cachified methods', ->
originalExpiryMinutes = cache.getOption('expiryMinutes')
originalCachified = cache.cachify((cb) -> cb())
cache.setOption('expiryMinutes', originalExpiryMinutes + 1)
newCachified = cache.cachify((cb) -> cb())
assert.equal originalCachified.getOptions().expiryMinutes, originalExpiryMinutes
assert.equal newCachified.getOptions().expiryMinutes, originalExpiryMinutes + 1
describe 'cachify', ->
it 'should have a valid cache name when no cache name provided', ->
cachedMethod = cache.cachify((cb) -> cb())
assert cachedMethod.getOptions().cacheName, 'did not find a valid cacheName'
it 'should return the cache object, with public methods, without error', (done) ->
methodToCache = (opt, cb) -> cb() # just call back
assert.doesNotThrow ->
cachedMethod = cache.cachify(methodToCache, { args: {}, updateCacheOnCreation: true })
assert cachedMethod
assert isFunction(cachedMethod.get)
assert isFunction(cachedMethod.update)
assert isFunction(cachedMethod.getOptions)
done()
it 'should execute the cache object when called with no arguments, without error', (done) ->
methodToCache = (cb) -> cb() # just call back
cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
done()
it 'should throw an error if no args were passed in but the method requires args', (done) ->
assert.throws ->
invalidMethodToCache = (opt, cb) -> cb() # method requires args (opt)
cachedMethod = cache.cachify(invalidMethodToCache, { args: undefined }) # args not defined
done()
it 'should throw an error if args were passed in but the method requires no args', (done) ->
assert.throws ->
invalidMethodToCache = (cb) -> cb() # method requires no args (just callback)
cachedMethod = cache.cachify(invalidMethodToCache, { args: {} }) # args defined
done()
describe 'get', ->
it 'should execute the callback with an error when the initial caching gives an error', ->
expectedError = new Error('test error')
methodToCache = (cb) -> cb(expectedError)
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) ->
assert value is undefined, 'should recieve \'undefined\' for value when initial cache update results in an error'
assert error, 'the error should be truthy'
assert.equal expectedError, error, 'got an unexpected error'
it 'should call the cached method with the correct arguments', (done) ->
callbackCount = 0
expectedArgs = id: 1, name:'<NAME>', created: new Date(), sub: { sub1: 1, sub2: 2}
methodToCache = (opt, cb) -> callbackCount++; assert.deepEqual(expectedArgs, opt); cb(null)
cachedMethod = cache.cachify methodToCache, { args: expectedArgs, updateCacheOnCreation: false }
cachedMethod.get (error, value) -> assert.equal(callbackCount, 1); done()
it 'should return the previously cached result on the 2nd execution', (done) ->
expectedCallbackCount = 1
actualCallbackCount = 0
methodToCache = (cb) -> cb(null, { count: ++actualCallbackCount }) # inc call count, return it as the cached value
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) -> #first call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
cachedMethod.get (error, value) -> #second call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
done()
it 'should return the initialCachedValue without blocking when initialCachedValue is non-null', (done) ->
callbackCount = 0
seed = { initial: true }
methodToCache = (cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
cachedMethod = cache.cachify(methodToCache, { initialCachedValue: seed })
cachedMethod.get (err, value) ->
assert.equal(callbackCount, 0, 'expected the cached method not to have been called yet')
assert.deepEqual(seed, value, 'expected the first returned value to be the initial seed')
done()
it 'should automatically update the cached value (async) updateCacheOnCreation is true', (done) ->
# TODO: unsure how to do this yet either
# callbackCount = 0
# methodToCache = (opt, cb) -> cb(null, { count: ++callbackCount })
# cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
# # calling get will ensure we block until the first cache update happened
# cachedMethod.get (err, value) ->
# assert.equal callbackCount, 1
done()
it 'should allow multiple calls, all of which should block until the initial cache update', (done) ->
# should allow multiple calls, all of which should block until the initial cache update
done()
it 'should not call the cached method more than once at a time before the initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should not call the cached method more than once at a time after initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should update the cached value after the specified # of minutes', (done) ->
# methodToCache = (opt, cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
# cachedMethod = cache.cachify methodToCache, { expiryMinutes: 0.01 }
# TODO: should update the cached value after the specified # of minutes
done()
| true | describe 'cache', ->
util = require 'util'
_ = require 'underscore'
assert = require 'assert'
events = require 'events'
logging = require '../lib/logging'
th = require './test_helpers'
a = require './asserters'
cache = require '../lib/cache'
# helpers
isFunction = (fn) -> _.isFunction(fn)
describe 'exports', ->
publicOptionNames = [ 'expiryMinutes', 'getLogger' ]
defaultExpiryMinutes = 5.0
cacheAssertions =
getOptions: [ a.ReturnValueEquals( publicOptionNames ) ]
getOption: [ a.ReturnValueEquals( defaultExpiryMinutes, 'expiryMinutes' ) ]
setOption: [ a.IsFunction ]
cachify: [ a.IsFunction ]
it 'should be valid', (done) -> a.verify cacheAssertions, '../lib/cache', done
describe 'option', ->
describe 'getLogger', ->
it 'should get and set correctly', -> # todo
it 'should cause future cachified methods to use the configured logger', -> # todo
describe 'expiryMinutes', ->
it 'should get and set correctly', ->
oldExpiryMinutes = cache.getOption('expiryMinutes')
cache.setOption('expiryMinutes', oldExpiryMinutes + 1)
assert.equal cache.getOption('expiryMinutes'), oldExpiryMinutes + 1
it 'should cause future cachified methods to use the default, without affecting existing cachified methods', ->
originalExpiryMinutes = cache.getOption('expiryMinutes')
originalCachified = cache.cachify((cb) -> cb())
cache.setOption('expiryMinutes', originalExpiryMinutes + 1)
newCachified = cache.cachify((cb) -> cb())
assert.equal originalCachified.getOptions().expiryMinutes, originalExpiryMinutes
assert.equal newCachified.getOptions().expiryMinutes, originalExpiryMinutes + 1
describe 'cachify', ->
it 'should have a valid cache name when no cache name provided', ->
cachedMethod = cache.cachify((cb) -> cb())
assert cachedMethod.getOptions().cacheName, 'did not find a valid cacheName'
it 'should return the cache object, with public methods, without error', (done) ->
methodToCache = (opt, cb) -> cb() # just call back
assert.doesNotThrow ->
cachedMethod = cache.cachify(methodToCache, { args: {}, updateCacheOnCreation: true })
assert cachedMethod
assert isFunction(cachedMethod.get)
assert isFunction(cachedMethod.update)
assert isFunction(cachedMethod.getOptions)
done()
it 'should execute the cache object when called with no arguments, without error', (done) ->
methodToCache = (cb) -> cb() # just call back
cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
done()
it 'should throw an error if no args were passed in but the method requires args', (done) ->
assert.throws ->
invalidMethodToCache = (opt, cb) -> cb() # method requires args (opt)
cachedMethod = cache.cachify(invalidMethodToCache, { args: undefined }) # args not defined
done()
it 'should throw an error if args were passed in but the method requires no args', (done) ->
assert.throws ->
invalidMethodToCache = (cb) -> cb() # method requires no args (just callback)
cachedMethod = cache.cachify(invalidMethodToCache, { args: {} }) # args defined
done()
describe 'get', ->
it 'should execute the callback with an error when the initial caching gives an error', ->
expectedError = new Error('test error')
methodToCache = (cb) -> cb(expectedError)
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) ->
assert value is undefined, 'should recieve \'undefined\' for value when initial cache update results in an error'
assert error, 'the error should be truthy'
assert.equal expectedError, error, 'got an unexpected error'
it 'should call the cached method with the correct arguments', (done) ->
callbackCount = 0
expectedArgs = id: 1, name:'PI:NAME:<NAME>END_PI', created: new Date(), sub: { sub1: 1, sub2: 2}
methodToCache = (opt, cb) -> callbackCount++; assert.deepEqual(expectedArgs, opt); cb(null)
cachedMethod = cache.cachify methodToCache, { args: expectedArgs, updateCacheOnCreation: false }
cachedMethod.get (error, value) -> assert.equal(callbackCount, 1); done()
it 'should return the previously cached result on the 2nd execution', (done) ->
expectedCallbackCount = 1
actualCallbackCount = 0
methodToCache = (cb) -> cb(null, { count: ++actualCallbackCount }) # inc call count, return it as the cached value
cachedMethod = cache.cachify(methodToCache)
cachedMethod.get (error, value) -> #first call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
cachedMethod.get (error, value) -> #second call
assert.equal(value.count, actualCallbackCount)
assert.equal(actualCallbackCount, expectedCallbackCount)
done()
it 'should return the initialCachedValue without blocking when initialCachedValue is non-null', (done) ->
callbackCount = 0
seed = { initial: true }
methodToCache = (cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
cachedMethod = cache.cachify(methodToCache, { initialCachedValue: seed })
cachedMethod.get (err, value) ->
assert.equal(callbackCount, 0, 'expected the cached method not to have been called yet')
assert.deepEqual(seed, value, 'expected the first returned value to be the initial seed')
done()
it 'should automatically update the cached value (async) updateCacheOnCreation is true', (done) ->
# TODO: unsure how to do this yet either
# callbackCount = 0
# methodToCache = (opt, cb) -> cb(null, { count: ++callbackCount })
# cachedMethod = cache.cachify(methodToCache, { updateCacheOnCreation: true })
# # calling get will ensure we block until the first cache update happened
# cachedMethod.get (err, value) ->
# assert.equal callbackCount, 1
done()
it 'should allow multiple calls, all of which should block until the initial cache update', (done) ->
# should allow multiple calls, all of which should block until the initial cache update
done()
it 'should not call the cached method more than once at a time before the initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should not call the cached method more than once at a time after initial cache update', (done) ->
# TODO: should not call the cached method more than once at a time
done()
it 'should update the cached value after the specified # of minutes', (done) ->
# methodToCache = (opt, cb) -> cb(null, { initial: opt.initial, count: ++callbackCount })
# cachedMethod = cache.cachify methodToCache, { expiryMinutes: 0.01 }
# TODO: should update the cached value after the specified # of minutes
done()
|
[
{
"context": "e real Sachin\n# hubot ship CBRIS\n#\n# Author:\n# Mateusz Kopij <sagasu>\n\nchrisExcuse = [\n \"Sachin makes me feel",
"end": 519,
"score": 0.999862015247345,
"start": 506,
"tag": "NAME",
"value": "Mateusz Kopij"
},
{
"context": " hubot ship CBRIS\n#\n# Author:\n# Mateusz Kopij <sagasu>\n\nchrisExcuse = [\n \"Sachin makes me feel uncomfo",
"end": 527,
"score": 0.9994093179702759,
"start": 521,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": "r:\n# Mateusz Kopij <sagasu>\n\nchrisExcuse = [\n \"Sachin makes me feel uncomfortable\",\n \"It's your smell\"",
"end": 555,
"score": 0.8742636442184448,
"start": 549,
"tag": "NAME",
"value": "Sachin"
},
{
"context": "hub site. The world needs my input.\",\n \"Yesterday Sachin showed me his drone, I am still meditating o",
"end": 1315,
"score": 0.6476326584815979,
"start": 1314,
"tag": "NAME",
"value": "S"
},
{
"context": "ong.png\",\n \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.j",
"end": 1704,
"score": 0.5612003803253174,
"start": 1701,
"tag": "USERNAME",
"value": "asu"
},
{
"context": "sg.send msg.random offshorepics\n\n robot.respond /Chris excuse/i, (msg)->\n msg.send msg.random chrisEx",
"end": 2228,
"score": 0.8935849666595459,
"start": 2223,
"tag": "NAME",
"value": "Chris"
},
{
"context": "nd /name traitors/i, (msg)->\n msg.send \":crown: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sach",
"end": 2432,
"score": 0.9993570446968079,
"start": 2427,
"tag": "NAME",
"value": "Marek"
},
{
"context": "rs/i, (msg)->\n msg.send \":crown: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kost",
"end": 2448,
"score": 0.9559580087661743,
"start": 2442,
"tag": "NAME",
"value": "Thomas"
},
{
"context": "sg)->\n msg.send \":crown: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :k",
"end": 2454,
"score": 0.7265476584434509,
"start": 2450,
"tag": "NAME",
"value": "Prem"
},
{
"context": ".send \":crown: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :kostas: \\n\n ",
"end": 2468,
"score": 0.9995362758636475,
"start": 2463,
"tag": "NAME",
"value": "Chris"
},
{
"context": "wn: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :kostas: \\n\n Ah... t",
"end": 2475,
"score": 0.7025175094604492,
"start": 2473,
"tag": "NAME",
"value": "is"
},
{
"context": "Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :kostas: \\n\n Ah... the sweet ",
"end": 2484,
"score": 0.9996306896209717,
"start": 2478,
"tag": "NAME",
"value": "Sachin"
},
{
"context": "omas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :kostas: \\n\n Ah... the sweet sweet joy of a da",
"end": 2501,
"score": 0.9986600279808044,
"start": 2495,
"tag": "NAME",
"value": "Kostas"
},
{
"context": "hore_gone_wrong.png\"\n \n robot.respond /what is Chris doing today/i, (msg)->\n msg.send \"https://raw.",
"end": 3110,
"score": 0.9060758948326111,
"start": 3105,
"tag": "NAME",
"value": "Chris"
},
{
"context": ">\n msg.send \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.j",
"end": 3188,
"score": 0.9994558095932007,
"start": 3182,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": ">\n msg.send \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg\"\n msg.se",
"end": 3373,
"score": 0.9993906021118164,
"start": 3367,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": "ar the lamentation of their women\"\n\n robot.hear /Ahsan smash/i, (msg)->\n msg.send \"https://raw.githubuserco",
"end": 4609,
"score": 0.9994438290596008,
"start": 4598,
"tag": "NAME",
"value": "Ahsan smash"
},
{
"context": ">\n msg.send \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/hulk.gif\"\n\n robot.respo",
"end": 4675,
"score": 0.9950783848762512,
"start": 4669,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": ">\n msg.send \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif\"\n\n ",
"end": 4819,
"score": 0.9946079850196838,
"start": 4813,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": "/richardResponse.gif\"\n\n robot.respond /What would Richard say/i, (msg)->\n msg.send \"https://raw.githubus",
"end": 4902,
"score": 0.9579933881759644,
"start": 4895,
"tag": "NAME",
"value": "Richard"
},
{
"context": ">\n msg.send \"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif\"",
"end": 4972,
"score": 0.9945130944252014,
"start": 4966,
"tag": "USERNAME",
"value": "sagasu"
}
] | scripts/offshore.coffee | sagasu/doc | 1 | # Description:
# offshore team
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot offshore team
# hubot sachin nsfw
# hubot who will be victorious
# hubot who will prevail
# hubot who will unleash righteous vengeance upon evil
# hubot who will be triumphant
# hubot when Prem is gone and we are lost in darkness
# hubot what is Chris doing today
# hubot Chris excuse
# hubot goodbye Prem
# hubot who is the real Sachin
# hubot ship CBRIS
#
# Author:
# Mateusz Kopij <sagasu>
chrisExcuse = [
"Sachin makes me feel uncomfortable",
"It's your smell",
"The world is becoming a computer, so am I",
"I focus on privacy today, you don't have an access.",
"I am protecting the democracies today. Priorities matter.",
"I will be working with ethical AI team. Make sure that it parties like it should, otherwise it wouldn't be ethical.",
"I am empowering the team to be more self organized, and take decisions on their own.",
"That it the price of innovation and be `zuper` creative.",
"Microsoft is pushing Azure project I am pushing my project today.",
"I will be creating tickets in JIRA -> sorry TFS for DGI drones and Azuresphere",
"I will be checking the quality of products on my favorite hub site. The world needs my input.",
"Yesterday Sachin showed me his drone, I am still meditating on that."
]
offshorepics = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/OffshoreTeam2.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/vicTeam.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
]
goodbyePrem = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/goodbyeold.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
]
module.exports = (robot) ->
robot.hear /pokemon/i, (msg)->
msg.send "pokemons? POKEMONS? We don't need stupid pokemons! please, it reminds me too much of Megan Fox mom"
robot.respond /offshore team/i, (msg)->
msg.send msg.random offshorepics
robot.respond /Chris excuse/i, (msg)->
msg.send msg.random chrisExcuse
robot.respond /offshore coat of arms/i, (msg)->
msg.send "`if (1 > 2)`"
robot.respond /name traitors/i, (msg)->
msg.send ":crown: Marek :crown:, Thomas, Prem :prem:, Chris :chris:, Sachin :sachin:, Kostas :kostas: \n
Ah... the sweet sweet joy of a dark alley, where a cold steel sends best regards from the offshore team. \n
We don't forget. Never forget..."
robot.respond /ship CBRIS/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshoreZillaRunningInChrome.jpg"
msg.send "stay tuned..."
robot.respond /who is the real Sachin/i, (msg)->
msg.send "he is :sachin:"
robot.respond /sachin nsfw/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png"
robot.respond /what is Chris doing today/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
msg.send "racing on his ride."
robot.respond /goodbye Prem/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
msg.send "Praise to the Lord! Hail to you o mighty Prem."
robot.respond /who will be victorious/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will be triumphant/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will prevail/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will unleash righteous vengeance upon evil/i, (msg)->
msg.send "The heroes of offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when all hope is lost and darkness is upon us/i, (msg)->
msg.send "The offshore team shall know no fear! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when Prem is gone and we are lost in darkness/i, (msg)->
msg.send "The offshore team shall know no fear! The offshore team will be triumphant! :ahsan: :sachin: :richard: :kostas: :drmatt:"
robot.respond /what is the purpose of offshore team/i, (msg)->
msg.send "To crush our bugs, see them driven before us, and to hear the lamentation of their women"
robot.hear /Ahsan smash/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/hulk.gif"
robot.respond /What would :richard: say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif"
robot.respond /What would Richard say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif" | 216914 | # Description:
# offshore team
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot offshore team
# hubot sachin nsfw
# hubot who will be victorious
# hubot who will prevail
# hubot who will unleash righteous vengeance upon evil
# hubot who will be triumphant
# hubot when Prem is gone and we are lost in darkness
# hubot what is Chris doing today
# hubot Chris excuse
# hubot goodbye Prem
# hubot who is the real Sachin
# hubot ship CBRIS
#
# Author:
# <NAME> <sagasu>
chrisExcuse = [
"<NAME> makes me feel uncomfortable",
"It's your smell",
"The world is becoming a computer, so am I",
"I focus on privacy today, you don't have an access.",
"I am protecting the democracies today. Priorities matter.",
"I will be working with ethical AI team. Make sure that it parties like it should, otherwise it wouldn't be ethical.",
"I am empowering the team to be more self organized, and take decisions on their own.",
"That it the price of innovation and be `zuper` creative.",
"Microsoft is pushing Azure project I am pushing my project today.",
"I will be creating tickets in JIRA -> sorry TFS for DGI drones and Azuresphere",
"I will be checking the quality of products on my favorite hub site. The world needs my input.",
"Yesterday <NAME>achin showed me his drone, I am still meditating on that."
]
offshorepics = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/OffshoreTeam2.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/vicTeam.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
]
goodbyePrem = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/goodbyeold.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
]
module.exports = (robot) ->
robot.hear /pokemon/i, (msg)->
msg.send "pokemons? POKEMONS? We don't need stupid pokemons! please, it reminds me too much of Megan Fox mom"
robot.respond /offshore team/i, (msg)->
msg.send msg.random offshorepics
robot.respond /<NAME> excuse/i, (msg)->
msg.send msg.random chrisExcuse
robot.respond /offshore coat of arms/i, (msg)->
msg.send "`if (1 > 2)`"
robot.respond /name traitors/i, (msg)->
msg.send ":crown: <NAME> :crown:, <NAME>, <NAME> :prem:, <NAME> :chr<NAME>:, <NAME> :sachin:, <NAME> :kostas: \n
Ah... the sweet sweet joy of a dark alley, where a cold steel sends best regards from the offshore team. \n
We don't forget. Never forget..."
robot.respond /ship CBRIS/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshoreZillaRunningInChrome.jpg"
msg.send "stay tuned..."
robot.respond /who is the real Sachin/i, (msg)->
msg.send "he is :sachin:"
robot.respond /sachin nsfw/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png"
robot.respond /what is <NAME> doing today/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
msg.send "racing on his ride."
robot.respond /goodbye Prem/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
msg.send "Praise to the Lord! Hail to you o mighty Prem."
robot.respond /who will be victorious/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will be triumphant/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will prevail/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will unleash righteous vengeance upon evil/i, (msg)->
msg.send "The heroes of offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when all hope is lost and darkness is upon us/i, (msg)->
msg.send "The offshore team shall know no fear! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when Prem is gone and we are lost in darkness/i, (msg)->
msg.send "The offshore team shall know no fear! The offshore team will be triumphant! :ahsan: :sachin: :richard: :kostas: :drmatt:"
robot.respond /what is the purpose of offshore team/i, (msg)->
msg.send "To crush our bugs, see them driven before us, and to hear the lamentation of their women"
robot.hear /<NAME>/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/hulk.gif"
robot.respond /What would :richard: say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif"
robot.respond /What would <NAME> say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif" | true | # Description:
# offshore team
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot offshore team
# hubot sachin nsfw
# hubot who will be victorious
# hubot who will prevail
# hubot who will unleash righteous vengeance upon evil
# hubot who will be triumphant
# hubot when Prem is gone and we are lost in darkness
# hubot what is Chris doing today
# hubot Chris excuse
# hubot goodbye Prem
# hubot who is the real Sachin
# hubot ship CBRIS
#
# Author:
# PI:NAME:<NAME>END_PI <sagasu>
chrisExcuse = [
"PI:NAME:<NAME>END_PI makes me feel uncomfortable",
"It's your smell",
"The world is becoming a computer, so am I",
"I focus on privacy today, you don't have an access.",
"I am protecting the democracies today. Priorities matter.",
"I will be working with ethical AI team. Make sure that it parties like it should, otherwise it wouldn't be ethical.",
"I am empowering the team to be more self organized, and take decisions on their own.",
"That it the price of innovation and be `zuper` creative.",
"Microsoft is pushing Azure project I am pushing my project today.",
"I will be creating tickets in JIRA -> sorry TFS for DGI drones and Azuresphere",
"I will be checking the quality of products on my favorite hub site. The world needs my input.",
"Yesterday PI:NAME:<NAME>END_PIachin showed me his drone, I am still meditating on that."
]
offshorepics = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/OffshoreTeam2.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/vicTeam.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
]
goodbyePrem = [
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/goodbyeold.jpg",
"https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
]
module.exports = (robot) ->
robot.hear /pokemon/i, (msg)->
msg.send "pokemons? POKEMONS? We don't need stupid pokemons! please, it reminds me too much of Megan Fox mom"
robot.respond /offshore team/i, (msg)->
msg.send msg.random offshorepics
robot.respond /PI:NAME:<NAME>END_PI excuse/i, (msg)->
msg.send msg.random chrisExcuse
robot.respond /offshore coat of arms/i, (msg)->
msg.send "`if (1 > 2)`"
robot.respond /name traitors/i, (msg)->
msg.send ":crown: PI:NAME:<NAME>END_PI :crown:, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI :prem:, PI:NAME:<NAME>END_PI :chrPI:NAME:<NAME>END_PI:, PI:NAME:<NAME>END_PI :sachin:, PI:NAME:<NAME>END_PI :kostas: \n
Ah... the sweet sweet joy of a dark alley, where a cold steel sends best regards from the offshore team. \n
We don't forget. Never forget..."
robot.respond /ship CBRIS/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshoreZillaRunningInChrome.jpg"
msg.send "stay tuned..."
robot.respond /who is the real Sachin/i, (msg)->
msg.send "he is :sachin:"
robot.respond /sachin nsfw/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/offshore_gone_wrong.png"
robot.respond /what is PI:NAME:<NAME>END_PI doing today/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/chris-donkey-cart-race.jpg"
msg.send "racing on his ride."
robot.respond /goodbye Prem/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/premZeus.jpg"
msg.send "Praise to the Lord! Hail to you o mighty Prem."
robot.respond /who will be victorious/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will be triumphant/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will prevail/i, (msg)->
msg.send "The Offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /who will unleash righteous vengeance upon evil/i, (msg)->
msg.send "The heroes of offshore team! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when all hope is lost and darkness is upon us/i, (msg)->
msg.send "The offshore team shall know no fear! :ahsan: :sachin: :kostas: :richard: :drmatt:"
robot.respond /when Prem is gone and we are lost in darkness/i, (msg)->
msg.send "The offshore team shall know no fear! The offshore team will be triumphant! :ahsan: :sachin: :richard: :kostas: :drmatt:"
robot.respond /what is the purpose of offshore team/i, (msg)->
msg.send "To crush our bugs, see them driven before us, and to hear the lamentation of their women"
robot.hear /PI:NAME:<NAME>END_PI/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/hulk.gif"
robot.respond /What would :richard: say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif"
robot.respond /What would PI:NAME:<NAME>END_PI say/i, (msg)->
msg.send "https://raw.githubusercontent.com/sagasu/offshore-team/master/img/richardResponse.gif" |
[
{
"context": "e CSS/SASS highlighter\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nColorifier.css = Colorifier.sass = Colorifier.s",
"end": 74,
"score": 0.9998884797096252,
"start": 57,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/lang/css.coffee | MadRabbit/colorifier | 1 | #
# The CSS/SASS highlighter
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
Colorifier.css = Colorifier.sass = Colorifier.scss = new Class Colorifier,
comments: "/* */,//"
booleans: "collapse,solid,dotted,dashed,none,auto,url,any,block,normal,"+
"italic,bold,unerline,inherit,inline,inline-block,inset,outset,"+
"hidden,visible,no-repeat,center,left,top,bottom,right,rgb,rgba,"+
"both,absolute,relative,fixed,static"
paint: (text)->
text = @_comments(text)
text = @_strings(text)
text = @_properties(text)
text = @_numbers(text)
text = @_colors(text)
text = @_keywords(text)
text = @_selectors(text)
@_rollback(text)
# protected
# painting the css-property names
_properties: (text)->
@_prepare(text, [
[/([^a-z\-])([a-z\-]+?)(\s*:)/ig, "attribute", "$1 $3"]
])
# painting the css-selectors
_selectors: (text)->
@_prepare(text, [
[/(^|[^a-z_\-0-9\.&\:#])([a-z]+?)(?![a-z_\-0-9=\^|])/ig, "keyword", "$1 "]
[/(^|.)(#[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/(^|.)(\.[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/([^\s])(:[a-z\-]+?)(?![a-z_\-0-9])/ig, "boolean", "$1 "]
])
# painting the numbers and all sorts of sizes
_numbers: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(\-?[0-9]*\.?[0-9]+[a-z%]*)(?!['"\d\w\.])/g, "integer", "$1 "]
])
_colors: (text)->
@_prepare(text, [
[/(.)(#(([abcdef0-9]{6})|([abcdef0-9]{3})))/ig, "unit", "$1 "]
])
| 145370 | #
# The CSS/SASS highlighter
#
# Copyright (C) 2011-2012 <NAME>
#
Colorifier.css = Colorifier.sass = Colorifier.scss = new Class Colorifier,
comments: "/* */,//"
booleans: "collapse,solid,dotted,dashed,none,auto,url,any,block,normal,"+
"italic,bold,unerline,inherit,inline,inline-block,inset,outset,"+
"hidden,visible,no-repeat,center,left,top,bottom,right,rgb,rgba,"+
"both,absolute,relative,fixed,static"
paint: (text)->
text = @_comments(text)
text = @_strings(text)
text = @_properties(text)
text = @_numbers(text)
text = @_colors(text)
text = @_keywords(text)
text = @_selectors(text)
@_rollback(text)
# protected
# painting the css-property names
_properties: (text)->
@_prepare(text, [
[/([^a-z\-])([a-z\-]+?)(\s*:)/ig, "attribute", "$1 $3"]
])
# painting the css-selectors
_selectors: (text)->
@_prepare(text, [
[/(^|[^a-z_\-0-9\.&\:#])([a-z]+?)(?![a-z_\-0-9=\^|])/ig, "keyword", "$1 "]
[/(^|.)(#[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/(^|.)(\.[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/([^\s])(:[a-z\-]+?)(?![a-z_\-0-9])/ig, "boolean", "$1 "]
])
# painting the numbers and all sorts of sizes
_numbers: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(\-?[0-9]*\.?[0-9]+[a-z%]*)(?!['"\d\w\.])/g, "integer", "$1 "]
])
_colors: (text)->
@_prepare(text, [
[/(.)(#(([abcdef0-9]{6})|([abcdef0-9]{3})))/ig, "unit", "$1 "]
])
| true | #
# The CSS/SASS highlighter
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
Colorifier.css = Colorifier.sass = Colorifier.scss = new Class Colorifier,
comments: "/* */,//"
booleans: "collapse,solid,dotted,dashed,none,auto,url,any,block,normal,"+
"italic,bold,unerline,inherit,inline,inline-block,inset,outset,"+
"hidden,visible,no-repeat,center,left,top,bottom,right,rgb,rgba,"+
"both,absolute,relative,fixed,static"
paint: (text)->
text = @_comments(text)
text = @_strings(text)
text = @_properties(text)
text = @_numbers(text)
text = @_colors(text)
text = @_keywords(text)
text = @_selectors(text)
@_rollback(text)
# protected
# painting the css-property names
_properties: (text)->
@_prepare(text, [
[/([^a-z\-])([a-z\-]+?)(\s*:)/ig, "attribute", "$1 $3"]
])
# painting the css-selectors
_selectors: (text)->
@_prepare(text, [
[/(^|[^a-z_\-0-9\.&\:#])([a-z]+?)(?![a-z_\-0-9=\^|])/ig, "keyword", "$1 "]
[/(^|.)(#[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/(^|.)(\.[a-z\-0-9\_]+)/ig, "property", "$1 "]
[/([^\s])(:[a-z\-]+?)(?![a-z_\-0-9])/ig, "boolean", "$1 "]
])
# painting the numbers and all sorts of sizes
_numbers: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(\-?[0-9]*\.?[0-9]+[a-z%]*)(?!['"\d\w\.])/g, "integer", "$1 "]
])
_colors: (text)->
@_prepare(text, [
[/(.)(#(([abcdef0-9]{6})|([abcdef0-9]{3})))/ig, "unit", "$1 "]
])
|
[
{
"context": "CommentService) ->\n $scope.user =\n name: \"John\"\n phone: \"12312312\"\n\n comment = CommentSe",
"end": 239,
"score": 0.999639630317688,
"start": 235,
"tag": "NAME",
"value": "John"
},
{
"context": "()\n# UserFactory.addCreditCard(\"1234\",10,17,\"Aleksey Khudoshin\",961)\n UserFactory.updateCreditCard(\"5464c43",
"end": 488,
"score": 0.9671970009803772,
"start": 471,
"tag": "NAME",
"value": "Aleksey Khudoshin"
},
{
"context": "ewUser = ->\n ConsoleFactory.registerNewUser(\"artem2.ft@gmail.com\")\n\n $scope.signin = ->\n UserFactory.signi",
"end": 678,
"score": 0.9999299645423889,
"start": 659,
"tag": "EMAIL",
"value": "artem2.ft@gmail.com"
},
{
"context": "\n $scope.signin = ->\n UserFactory.signin(\"artem2.ft@gmail.com\", \"1234\")\n\n $scope.newTask = ->\n TaskFact",
"end": 750,
"score": 0.9999284744262695,
"start": 731,
"tag": "EMAIL",
"value": "artem2.ft@gmail.com"
}
] | app/assets/javascripts/console/controllers.coffee | arakcheev/console | 0 | ###*
Console controllers.
###
define ['./services'], (services)->
"use strict"
###*
Controls the index page
###
MainCtrl = ($scope, ConsoleFactory, UserFactory, TaskFactory, CommentService) ->
$scope.user =
name: "John"
phone: "12312312"
comment = CommentService
comment.onmessage (event) ->
console.log(event.data)
#
$scope.click = ->
# ConsoleFactory.registerNewUser()
# UserFactory.addCreditCard("1234",10,17,"Aleksey Khudoshin",961)
UserFactory.updateCreditCard("5464c43a6c0100d60707d6e5", "123456789", 10, 17, "Lexa2", 961, 3)
$scope.newUser = ->
ConsoleFactory.registerNewUser("artem2.ft@gmail.com")
$scope.signin = ->
UserFactory.signin("artem2.ft@gmail.com", "1234")
$scope.newTask = ->
TaskFactory.newTask("New task", new Date().getTime() * 1000 + 1000, new Date().getTime() * 1000 + 2000, "", "",
"", "")
$scope.tasks = ->
TaskFactory.list()
$scope.logout = ->
UserFactory.logout()
$scope.newComment = ->
comment.send( JSON.stringify(
"text": "text"
"system": "system"
"docType": "docType"
"docId": "docID"
))
MainCtrl.$inject = [
"$scope"
"ConsoleFactory"
"UserFactory"
"TaskFactory"
"CommentService"
]
MainCtrl: MainCtrl
| 94357 | ###*
Console controllers.
###
define ['./services'], (services)->
"use strict"
###*
Controls the index page
###
MainCtrl = ($scope, ConsoleFactory, UserFactory, TaskFactory, CommentService) ->
$scope.user =
name: "<NAME>"
phone: "12312312"
comment = CommentService
comment.onmessage (event) ->
console.log(event.data)
#
$scope.click = ->
# ConsoleFactory.registerNewUser()
# UserFactory.addCreditCard("1234",10,17,"<NAME>",961)
UserFactory.updateCreditCard("5464c43a6c0100d60707d6e5", "123456789", 10, 17, "Lexa2", 961, 3)
$scope.newUser = ->
ConsoleFactory.registerNewUser("<EMAIL>")
$scope.signin = ->
UserFactory.signin("<EMAIL>", "1234")
$scope.newTask = ->
TaskFactory.newTask("New task", new Date().getTime() * 1000 + 1000, new Date().getTime() * 1000 + 2000, "", "",
"", "")
$scope.tasks = ->
TaskFactory.list()
$scope.logout = ->
UserFactory.logout()
$scope.newComment = ->
comment.send( JSON.stringify(
"text": "text"
"system": "system"
"docType": "docType"
"docId": "docID"
))
MainCtrl.$inject = [
"$scope"
"ConsoleFactory"
"UserFactory"
"TaskFactory"
"CommentService"
]
MainCtrl: MainCtrl
| true | ###*
Console controllers.
###
define ['./services'], (services)->
"use strict"
###*
Controls the index page
###
MainCtrl = ($scope, ConsoleFactory, UserFactory, TaskFactory, CommentService) ->
$scope.user =
name: "PI:NAME:<NAME>END_PI"
phone: "12312312"
comment = CommentService
comment.onmessage (event) ->
console.log(event.data)
#
$scope.click = ->
# ConsoleFactory.registerNewUser()
# UserFactory.addCreditCard("1234",10,17,"PI:NAME:<NAME>END_PI",961)
UserFactory.updateCreditCard("5464c43a6c0100d60707d6e5", "123456789", 10, 17, "Lexa2", 961, 3)
$scope.newUser = ->
ConsoleFactory.registerNewUser("PI:EMAIL:<EMAIL>END_PI")
$scope.signin = ->
UserFactory.signin("PI:EMAIL:<EMAIL>END_PI", "1234")
$scope.newTask = ->
TaskFactory.newTask("New task", new Date().getTime() * 1000 + 1000, new Date().getTime() * 1000 + 2000, "", "",
"", "")
$scope.tasks = ->
TaskFactory.list()
$scope.logout = ->
UserFactory.logout()
$scope.newComment = ->
comment.send( JSON.stringify(
"text": "text"
"system": "system"
"docType": "docType"
"docId": "docID"
))
MainCtrl.$inject = [
"$scope"
"ConsoleFactory"
"UserFactory"
"TaskFactory"
"CommentService"
]
MainCtrl: MainCtrl
|
[
{
"context": "rt(\n service: 'gmail'\n auth:\n user: 'perpustakaanonline2015@gmail.com'\n pass: 'penelitianilmiah123'\n)\n\npassport.",
"end": 439,
"score": 0.99992436170578,
"start": 407,
"tag": "EMAIL",
"value": "perpustakaanonline2015@gmail.com"
},
{
"context": "'perpustakaanonline2015@gmail.com'\n pass: 'penelitianilmiah123'\n)\n\npassport.serializeUser (user, done) ->\n do",
"end": 475,
"score": 0.999121367931366,
"start": 456,
"tag": "PASSWORD",
"value": "penelitianilmiah123"
},
{
"context": " nama: req.body.nama\n password: hash\n enable: false\n )\n\n ",
"end": 1591,
"score": 0.9529662132263184,
"start": 1587,
"tag": "PASSWORD",
"value": "hash"
},
{
"context": " transporter.sendMail(\n from: 'perpustakaanonline2015@gmail.com'\n to: req.body.email\n ",
"end": 1810,
"score": 0.9999278783798218,
"start": 1778,
"tag": "EMAIL",
"value": "perpustakaanonline2015@gmail.com"
},
{
"context": "tuk sehari\n token = jwt.sign profile, 'rizki', expiresInMinutes: 60 * 24\n\n res.json",
"end": 2669,
"score": 0.5761007070541382,
"start": 2664,
"tag": "PASSWORD",
"value": "rizki"
}
] | Server/routes/UserRoute.coffee | RizkiMufrizal/Belajar-ES6 | 1 | express = require 'express'
jwt = require 'jsonwebtoken'
uuid = require 'node-uuid'
User = require '../models/User'
Logger = require '../utils/Logger'
nodemailer = require 'nodemailer'
bcrypt = require 'bcrypt'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
router = express.Router()
transporter = nodemailer.createTransport(
service: 'gmail'
auth:
user: 'perpustakaanonline2015@gmail.com'
pass: 'penelitianilmiah123'
)
passport.serializeUser (user, done) ->
done(null, user)
passport.deserializeUser (user, done) ->
done(null, user)
passport.use new LocalStrategy((username, password, done) ->
User.findOne { email: username }, (err, user) ->
return done(err) if err
unless user
return done(null, false,
'message': 'email anda salah'
)
bcrypt.compare password, user.password, (err, res) ->
unless user.enable is true
return done(null, false,
'message': 'email belum verifikasi'
)
unless res is true
return done(null, false,
'message': 'password anda salah'
)
done null, user
)
router.post '/register', (req, res, next) ->
idUser = uuid.v4()
bcrypt.genSalt 10, (err, salt) ->
bcrypt.hash req.body.password, salt, (err, hash) ->
user = new User(
idUser: idUser
email: req.body.email
nama: req.body.nama
password: hash
enable: false
)
user.save (err) ->
return res.json(err) if err
transporter.sendMail(
from: 'perpustakaanonline2015@gmail.com'
to: req.body.email
subject: 'Verifikasi Email'
html: "Silahkan verifikasi melalui alamat berikut : <a href='http://localhost:3000/verifikasi/#{idUser}'>Belajar ES6</a>"
)
res.json
success: true
info: 'Anda Berhasil register, silahkan verifikasi email anda'
router.post '/authenticate', (req, res) ->
passport.authenticate('local', (err, user, info) ->
return res.status(500).json(err) if err
unless user
return res.status(401).json(info)
req.logIn user, (err) ->
return res.status(500).json(err) if err
profile =
email: user.email
nama: user.nama
#token untuk sehari
token = jwt.sign profile, 'rizki', expiresInMinutes: 60 * 24
res.json
info: 'berhasil login'
token: token
email: user.email
nama: user.nama
success: true
) req, res
router.post '/logout', (req, res) ->
req.logout()
res.json
info: 'berhasil logout'
success: true
router.get '/verifikasi/:idUser', (req, res) ->
idUser = req.params.idUser
User.findOne {
idUser: idUser
}, (err, user) ->
user.enable = true
user.save()
res.redirect '/'
router.get '/', (req, res) ->
res.render 'index'
module.exports = router
| 148737 | express = require 'express'
jwt = require 'jsonwebtoken'
uuid = require 'node-uuid'
User = require '../models/User'
Logger = require '../utils/Logger'
nodemailer = require 'nodemailer'
bcrypt = require 'bcrypt'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
router = express.Router()
transporter = nodemailer.createTransport(
service: 'gmail'
auth:
user: '<EMAIL>'
pass: '<PASSWORD>'
)
passport.serializeUser (user, done) ->
done(null, user)
passport.deserializeUser (user, done) ->
done(null, user)
passport.use new LocalStrategy((username, password, done) ->
User.findOne { email: username }, (err, user) ->
return done(err) if err
unless user
return done(null, false,
'message': 'email anda salah'
)
bcrypt.compare password, user.password, (err, res) ->
unless user.enable is true
return done(null, false,
'message': 'email belum verifikasi'
)
unless res is true
return done(null, false,
'message': 'password anda salah'
)
done null, user
)
router.post '/register', (req, res, next) ->
idUser = uuid.v4()
bcrypt.genSalt 10, (err, salt) ->
bcrypt.hash req.body.password, salt, (err, hash) ->
user = new User(
idUser: idUser
email: req.body.email
nama: req.body.nama
password: <PASSWORD>
enable: false
)
user.save (err) ->
return res.json(err) if err
transporter.sendMail(
from: '<EMAIL>'
to: req.body.email
subject: 'Verifikasi Email'
html: "Silahkan verifikasi melalui alamat berikut : <a href='http://localhost:3000/verifikasi/#{idUser}'>Belajar ES6</a>"
)
res.json
success: true
info: 'Anda Berhasil register, silahkan verifikasi email anda'
router.post '/authenticate', (req, res) ->
passport.authenticate('local', (err, user, info) ->
return res.status(500).json(err) if err
unless user
return res.status(401).json(info)
req.logIn user, (err) ->
return res.status(500).json(err) if err
profile =
email: user.email
nama: user.nama
#token untuk sehari
token = jwt.sign profile, '<PASSWORD>', expiresInMinutes: 60 * 24
res.json
info: 'berhasil login'
token: token
email: user.email
nama: user.nama
success: true
) req, res
router.post '/logout', (req, res) ->
req.logout()
res.json
info: 'berhasil logout'
success: true
router.get '/verifikasi/:idUser', (req, res) ->
idUser = req.params.idUser
User.findOne {
idUser: idUser
}, (err, user) ->
user.enable = true
user.save()
res.redirect '/'
router.get '/', (req, res) ->
res.render 'index'
module.exports = router
| true | express = require 'express'
jwt = require 'jsonwebtoken'
uuid = require 'node-uuid'
User = require '../models/User'
Logger = require '../utils/Logger'
nodemailer = require 'nodemailer'
bcrypt = require 'bcrypt'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
router = express.Router()
transporter = nodemailer.createTransport(
service: 'gmail'
auth:
user: 'PI:EMAIL:<EMAIL>END_PI'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
)
passport.serializeUser (user, done) ->
done(null, user)
passport.deserializeUser (user, done) ->
done(null, user)
passport.use new LocalStrategy((username, password, done) ->
User.findOne { email: username }, (err, user) ->
return done(err) if err
unless user
return done(null, false,
'message': 'email anda salah'
)
bcrypt.compare password, user.password, (err, res) ->
unless user.enable is true
return done(null, false,
'message': 'email belum verifikasi'
)
unless res is true
return done(null, false,
'message': 'password anda salah'
)
done null, user
)
router.post '/register', (req, res, next) ->
idUser = uuid.v4()
bcrypt.genSalt 10, (err, salt) ->
bcrypt.hash req.body.password, salt, (err, hash) ->
user = new User(
idUser: idUser
email: req.body.email
nama: req.body.nama
password: PI:PASSWORD:<PASSWORD>END_PI
enable: false
)
user.save (err) ->
return res.json(err) if err
transporter.sendMail(
from: 'PI:EMAIL:<EMAIL>END_PI'
to: req.body.email
subject: 'Verifikasi Email'
html: "Silahkan verifikasi melalui alamat berikut : <a href='http://localhost:3000/verifikasi/#{idUser}'>Belajar ES6</a>"
)
res.json
success: true
info: 'Anda Berhasil register, silahkan verifikasi email anda'
router.post '/authenticate', (req, res) ->
passport.authenticate('local', (err, user, info) ->
return res.status(500).json(err) if err
unless user
return res.status(401).json(info)
req.logIn user, (err) ->
return res.status(500).json(err) if err
profile =
email: user.email
nama: user.nama
#token untuk sehari
token = jwt.sign profile, 'PI:PASSWORD:<PASSWORD>END_PI', expiresInMinutes: 60 * 24
res.json
info: 'berhasil login'
token: token
email: user.email
nama: user.nama
success: true
) req, res
router.post '/logout', (req, res) ->
req.logout()
res.json
info: 'berhasil logout'
success: true
router.get '/verifikasi/:idUser', (req, res) ->
idUser = req.params.idUser
User.findOne {
idUser: idUser
}, (err, user) ->
user.enable = true
user.save()
res.redirect '/'
router.get '/', (req, res) ->
res.render 'index'
module.exports = router
|
[
{
"context": " = (id, password) ->\n options =\n username: id\n password: password\n\n login(options).then",
"end": 1269,
"score": 0.820228099822998,
"start": 1267,
"tag": "USERNAME",
"value": "id"
},
{
"context": ">\n options =\n username: id\n password: password\n\n login(options).then(loginSuccess, loginFailu",
"end": 1294,
"score": 0.9974986910820007,
"start": 1286,
"tag": "PASSWORD",
"value": "password"
}
] | app/scripts/connect/welcome.coffee | appirio-tech/accounts-app | 3 | 'use strict'
{ getFreshToken, login } = require '../../../core/auth.js'
{ DOMAIN } = require '../../../core/constants.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
_ = require 'lodash'
ConnectWelcomeController = ($state, $stateParams, $scope, ISO3166) ->
vm = this
vm.termsUrl = 'https://connect.' + DOMAIN + '/terms'
vm.newProjectUrl = 'https://connect.' + DOMAIN + '/new-project'
vm.connectDashboardUrl = 'https://connect.' + DOMAIN + '/projects'
vm.privacyUrl = 'https://www.' + DOMAIN + '/privacy-policy/'
vm.username = ''
vm.password = ''
vm.error = false
vm.errorMessage = 'Error Creating User'
vm.submit = null
vm.loading = false
vm.isValidCountry = false
vm.isCountryDirty = false
vm.ssoUser
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.auth0Data = $stateParams.auth0Data
vm.screenType = "welcome"
vm.isLoggedIn = false
vm.userHandle = $stateParams.username
# SSO user data extracted from auth0 login data
vm.ssoUser = vm.auth0Data?.ssoUserData
callLogin = (id, password) ->
options =
username: id
password: password
login(options).then(loginSuccess, loginFailure)
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = (result) ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
vm.reRender()
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
vm.isLoggedIn = true
vm.reRender()
if jwt && vm.retUrl
# redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
vm
ConnectWelcomeController.$inject = [
'$state'
'$stateParams'
'$scope',
'ISO3166'
]
angular.module('accounts').controller 'ConnectWelcomeController', ConnectWelcomeController
| 123538 | 'use strict'
{ getFreshToken, login } = require '../../../core/auth.js'
{ DOMAIN } = require '../../../core/constants.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
_ = require 'lodash'
ConnectWelcomeController = ($state, $stateParams, $scope, ISO3166) ->
vm = this
vm.termsUrl = 'https://connect.' + DOMAIN + '/terms'
vm.newProjectUrl = 'https://connect.' + DOMAIN + '/new-project'
vm.connectDashboardUrl = 'https://connect.' + DOMAIN + '/projects'
vm.privacyUrl = 'https://www.' + DOMAIN + '/privacy-policy/'
vm.username = ''
vm.password = ''
vm.error = false
vm.errorMessage = 'Error Creating User'
vm.submit = null
vm.loading = false
vm.isValidCountry = false
vm.isCountryDirty = false
vm.ssoUser
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.auth0Data = $stateParams.auth0Data
vm.screenType = "welcome"
vm.isLoggedIn = false
vm.userHandle = $stateParams.username
# SSO user data extracted from auth0 login data
vm.ssoUser = vm.auth0Data?.ssoUserData
callLogin = (id, password) ->
options =
username: id
password: <PASSWORD>
login(options).then(loginSuccess, loginFailure)
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = (result) ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
vm.reRender()
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
vm.isLoggedIn = true
vm.reRender()
if jwt && vm.retUrl
# redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
vm
ConnectWelcomeController.$inject = [
'$state'
'$stateParams'
'$scope',
'ISO3166'
]
angular.module('accounts').controller 'ConnectWelcomeController', ConnectWelcomeController
| true | 'use strict'
{ getFreshToken, login } = require '../../../core/auth.js'
{ DOMAIN } = require '../../../core/constants.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
_ = require 'lodash'
ConnectWelcomeController = ($state, $stateParams, $scope, ISO3166) ->
vm = this
vm.termsUrl = 'https://connect.' + DOMAIN + '/terms'
vm.newProjectUrl = 'https://connect.' + DOMAIN + '/new-project'
vm.connectDashboardUrl = 'https://connect.' + DOMAIN + '/projects'
vm.privacyUrl = 'https://www.' + DOMAIN + '/privacy-policy/'
vm.username = ''
vm.password = ''
vm.error = false
vm.errorMessage = 'Error Creating User'
vm.submit = null
vm.loading = false
vm.isValidCountry = false
vm.isCountryDirty = false
vm.ssoUser
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.auth0Data = $stateParams.auth0Data
vm.screenType = "welcome"
vm.isLoggedIn = false
vm.userHandle = $stateParams.username
# SSO user data extracted from auth0 login data
vm.ssoUser = vm.auth0Data?.ssoUserData
callLogin = (id, password) ->
options =
username: id
password: PI:PASSWORD:<PASSWORD>END_PI
login(options).then(loginSuccess, loginFailure)
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = (result) ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
vm.reRender()
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
vm.isLoggedIn = true
vm.reRender()
if jwt && vm.retUrl
# redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
vm
ConnectWelcomeController.$inject = [
'$state'
'$stateParams'
'$scope',
'ISO3166'
]
angular.module('accounts').controller 'ConnectWelcomeController', ConnectWelcomeController
|
[
{
"context": "###\n Vertical News Ticker 1.21\n\n Original by: Tadas Juozapaitis ( kasp3rito [eta] gmail (dot) com )\n ",
"end": 65,
"score": 0.9999014735221863,
"start": 48,
"tag": "NAME",
"value": "Tadas Juozapaitis"
},
{
"context": "ail (dot) com )\n https://github.com/kasp3r/vTicker\n\n Forked/Modified by: Richard Hollis @ri",
"end": 142,
"score": 0.8278835415840149,
"start": 136,
"tag": "USERNAME",
"value": "kasp3r"
},
{
"context": "//github.com/kasp3r/vTicker\n\n Forked/Modified by: Richard Hollis @richhollis - richhollis.co.uk\n###\n\n(($) ->\n\n de",
"end": 188,
"score": 0.9998956322669983,
"start": 174,
"tag": "NAME",
"value": "Richard Hollis"
},
{
"context": "sp3r/vTicker\n\n Forked/Modified by: Richard Hollis @richhollis - richhollis.co.uk\n###\n\n(($) ->\n\n defaults = \n ",
"end": 200,
"score": 0.9991596341133118,
"start": 189,
"tag": "USERNAME",
"value": "@richhollis"
},
{
"context": " Forked/Modified by: Richard Hollis @richhollis - richhollis.co.uk\n###\n\n(($) ->\n\n defaults = \n speed: 700\n pa",
"end": 219,
"score": 0.9965100288391113,
"start": 203,
"tag": "EMAIL",
"value": "richhollis.co.uk"
}
] | coffee/jquery.vticker.coffee | richhollis/vticker | 118 | ###
Vertical News Ticker 1.21
Original by: Tadas Juozapaitis ( kasp3rito [eta] gmail (dot) com )
https://github.com/kasp3r/vTicker
Forked/Modified by: Richard Hollis @richhollis - richhollis.co.uk
###
(($) ->
defaults =
speed: 700
pause: 4000
showItems: 1
mousePause: true
height: 0
animate: true
margin: 0
padding: 0
startPaused: false
autoAppend: true
internal =
moveUp: (state, attribs) -> internal.showNextItem(state, attribs, 'up')
moveDown: (state, attribs) -> internal.showNextItem(state, attribs, 'down')
nextItemState: (state, dir) ->
obj = state.element.children('ul')
# calc height
height = state.itemHeight
height = obj.children('li:first').height() if state.options.height > 0
height += state.options.margin + state.options.padding * 2
# attributes
height: height
options: state.options
el: state.element
obj: obj
selector: if dir == 'up' then 'li:first' else 'li:last'
dir: dir
showNextItem: (state, attribs, dir) ->
nis = internal.nextItemState(state, dir)
nis.el.trigger 'vticker.beforeTick'
clone = nis.obj.children(nis.selector).clone(true)
# adjust for margins & padding
nis.obj.css('top', '-' + nis.height + 'px').prepend(clone) if nis.dir == 'down'
if attribs && attribs.animate
internal.animateNextItem(nis, state) unless state.animating
else
internal.nonAnimatedNextItem(nis)
clone.appendTo(nis.obj) if nis.dir == 'up' && state.options.autoAppend
nis.el.trigger 'vticker.afterTick'
animateNextItem: (nis, state) ->
state.animating = true
opts = if nis.dir == 'up' then top: '-=' + nis.height + 'px' else top: 0
nis.obj.animate opts, state.options.speed, ->
$(nis.obj).children(nis.selector).remove()
$(nis.obj).css 'top', '0px'
state.animating = false
nonAnimatedNextItem: (nis) ->
nis.obj.children(nis.selector).remove()
nis.obj.css 'top', '0px'
nextUsePause: ->
state = $(@).data('state')
options = state.options
return if state.isPaused || internal.hasSingleItem(state)
methods.next.call @, animate: options.animate
startInterval: ->
state = $(@).data('state')
options = state.options
state.intervalId = setInterval =>
internal.nextUsePause.call @
, options.pause
stopInterval: ->
return unless state = $(@).data('state')
clearInterval state.intervalId if state.intervalId
state.intervalId = undefined
restartInterval: ->
internal.stopInterval.call @
internal.startInterval.call @
getState: (from, elem) ->
throw new Error("vTicker: No state available from #{from}") unless state = $(elem).data('state')
state
isAnimatingOrSingleItem: (state) -> state.animating || @hasSingleItem(state)
hasMultipleItems: (state) -> state.itemCount > 1
hasSingleItem: (state) -> !internal.hasMultipleItems(state)
bindMousePausing: (el, state) =>
el.bind 'mouseenter', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused
state.pausedByCode = true
# stop interval
internal.stopInterval.call @
methods.pause.call @, true
.bind 'mouseleave', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused && !state.pausedByCode
state.pausedByCode = false
methods.pause.call @, false
# restart interval
internal.startInterval.call @
setItemLayout: (el, state, options) ->
el.css(overflow: 'hidden', position: 'relative')
.children('ul').css(position: 'absolute', margin: 0, padding: 0)
.children('li').css(margin: options.margin, padding: options.padding)
if isNaN(options.height) || options.height == 0
el.children('ul').children('li').each -> state.itemHeight = $(@).height() if $(@).height() > state.itemHeight
# set the same height on all child elements
el.children('ul').children('li').each -> $(@).height(state.itemHeight)
# set element to total height
box = options.margin + options.padding * 2
el.height (state.itemHeight + box) * options.showItems + options.margin
else
el.height options.height # set the preferred height
defaultStateAttribs: (el, options) ->
itemCount: el.children('ul').children('li').length
itemHeight: 0
itemMargin: 0
element: el
animating: false
options: options
isPaused: options.startPaused
pausedByCode: false
methods =
init: (options) ->
methods.stop.call @ if state = $(@).data('state') # if init called second time then stop first, then re-init
state = null
clonedDefaults = jQuery.extend({}, defaults)
options = $.extend(clonedDefaults, options)
el = $(@)
state = internal.defaultStateAttribs(el, options)
$(@).data('state', state)
internal.setItemLayout(el, state, options)
internal.startInterval.call @ unless options.startPaused
internal.bindMousePausing(el, state) if options.mousePause
pause: (pauseState) ->
state = internal.getState('pause', @)
return false unless internal.hasMultipleItems(state)
state.isPaused = pauseState
el = state.element
if pauseState
$(@).addClass 'paused'
el.trigger 'vticker.pause'
else
$(@).removeClass 'paused'
el.trigger 'vticker.resume'
next: (attribs) ->
state = internal.getState('next', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveUp state, attribs
prev: (attribs) ->
state = internal.getState('prev', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveDown state, attribs
stop: ->
state = internal.getState('stop', @)
internal.stopInterval.call @
remove: ->
state = internal.getState('remove', @)
internal.stopInterval.call @
el = state.element
el.unbind()
el.remove()
$.fn.vTicker = (method) ->
return methods[method].apply(@, Array::slice.call(arguments, 1)) if methods[method]
return methods.init.apply(@, arguments) if typeof method == 'object' || !method
$.error 'Method ' + method + ' does not exist on jQuery.vTicker'
) jQuery | 41902 | ###
Vertical News Ticker 1.21
Original by: <NAME> ( kasp3rito [eta] gmail (dot) com )
https://github.com/kasp3r/vTicker
Forked/Modified by: <NAME> @richhollis - <EMAIL>
###
(($) ->
defaults =
speed: 700
pause: 4000
showItems: 1
mousePause: true
height: 0
animate: true
margin: 0
padding: 0
startPaused: false
autoAppend: true
internal =
moveUp: (state, attribs) -> internal.showNextItem(state, attribs, 'up')
moveDown: (state, attribs) -> internal.showNextItem(state, attribs, 'down')
nextItemState: (state, dir) ->
obj = state.element.children('ul')
# calc height
height = state.itemHeight
height = obj.children('li:first').height() if state.options.height > 0
height += state.options.margin + state.options.padding * 2
# attributes
height: height
options: state.options
el: state.element
obj: obj
selector: if dir == 'up' then 'li:first' else 'li:last'
dir: dir
showNextItem: (state, attribs, dir) ->
nis = internal.nextItemState(state, dir)
nis.el.trigger 'vticker.beforeTick'
clone = nis.obj.children(nis.selector).clone(true)
# adjust for margins & padding
nis.obj.css('top', '-' + nis.height + 'px').prepend(clone) if nis.dir == 'down'
if attribs && attribs.animate
internal.animateNextItem(nis, state) unless state.animating
else
internal.nonAnimatedNextItem(nis)
clone.appendTo(nis.obj) if nis.dir == 'up' && state.options.autoAppend
nis.el.trigger 'vticker.afterTick'
animateNextItem: (nis, state) ->
state.animating = true
opts = if nis.dir == 'up' then top: '-=' + nis.height + 'px' else top: 0
nis.obj.animate opts, state.options.speed, ->
$(nis.obj).children(nis.selector).remove()
$(nis.obj).css 'top', '0px'
state.animating = false
nonAnimatedNextItem: (nis) ->
nis.obj.children(nis.selector).remove()
nis.obj.css 'top', '0px'
nextUsePause: ->
state = $(@).data('state')
options = state.options
return if state.isPaused || internal.hasSingleItem(state)
methods.next.call @, animate: options.animate
startInterval: ->
state = $(@).data('state')
options = state.options
state.intervalId = setInterval =>
internal.nextUsePause.call @
, options.pause
stopInterval: ->
return unless state = $(@).data('state')
clearInterval state.intervalId if state.intervalId
state.intervalId = undefined
restartInterval: ->
internal.stopInterval.call @
internal.startInterval.call @
getState: (from, elem) ->
throw new Error("vTicker: No state available from #{from}") unless state = $(elem).data('state')
state
isAnimatingOrSingleItem: (state) -> state.animating || @hasSingleItem(state)
hasMultipleItems: (state) -> state.itemCount > 1
hasSingleItem: (state) -> !internal.hasMultipleItems(state)
bindMousePausing: (el, state) =>
el.bind 'mouseenter', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused
state.pausedByCode = true
# stop interval
internal.stopInterval.call @
methods.pause.call @, true
.bind 'mouseleave', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused && !state.pausedByCode
state.pausedByCode = false
methods.pause.call @, false
# restart interval
internal.startInterval.call @
setItemLayout: (el, state, options) ->
el.css(overflow: 'hidden', position: 'relative')
.children('ul').css(position: 'absolute', margin: 0, padding: 0)
.children('li').css(margin: options.margin, padding: options.padding)
if isNaN(options.height) || options.height == 0
el.children('ul').children('li').each -> state.itemHeight = $(@).height() if $(@).height() > state.itemHeight
# set the same height on all child elements
el.children('ul').children('li').each -> $(@).height(state.itemHeight)
# set element to total height
box = options.margin + options.padding * 2
el.height (state.itemHeight + box) * options.showItems + options.margin
else
el.height options.height # set the preferred height
defaultStateAttribs: (el, options) ->
itemCount: el.children('ul').children('li').length
itemHeight: 0
itemMargin: 0
element: el
animating: false
options: options
isPaused: options.startPaused
pausedByCode: false
methods =
init: (options) ->
methods.stop.call @ if state = $(@).data('state') # if init called second time then stop first, then re-init
state = null
clonedDefaults = jQuery.extend({}, defaults)
options = $.extend(clonedDefaults, options)
el = $(@)
state = internal.defaultStateAttribs(el, options)
$(@).data('state', state)
internal.setItemLayout(el, state, options)
internal.startInterval.call @ unless options.startPaused
internal.bindMousePausing(el, state) if options.mousePause
pause: (pauseState) ->
state = internal.getState('pause', @)
return false unless internal.hasMultipleItems(state)
state.isPaused = pauseState
el = state.element
if pauseState
$(@).addClass 'paused'
el.trigger 'vticker.pause'
else
$(@).removeClass 'paused'
el.trigger 'vticker.resume'
next: (attribs) ->
state = internal.getState('next', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveUp state, attribs
prev: (attribs) ->
state = internal.getState('prev', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveDown state, attribs
stop: ->
state = internal.getState('stop', @)
internal.stopInterval.call @
remove: ->
state = internal.getState('remove', @)
internal.stopInterval.call @
el = state.element
el.unbind()
el.remove()
$.fn.vTicker = (method) ->
return methods[method].apply(@, Array::slice.call(arguments, 1)) if methods[method]
return methods.init.apply(@, arguments) if typeof method == 'object' || !method
$.error 'Method ' + method + ' does not exist on jQuery.vTicker'
) jQuery | true | ###
Vertical News Ticker 1.21
Original by: PI:NAME:<NAME>END_PI ( kasp3rito [eta] gmail (dot) com )
https://github.com/kasp3r/vTicker
Forked/Modified by: PI:NAME:<NAME>END_PI @richhollis - PI:EMAIL:<EMAIL>END_PI
###
(($) ->
defaults =
speed: 700
pause: 4000
showItems: 1
mousePause: true
height: 0
animate: true
margin: 0
padding: 0
startPaused: false
autoAppend: true
internal =
moveUp: (state, attribs) -> internal.showNextItem(state, attribs, 'up')
moveDown: (state, attribs) -> internal.showNextItem(state, attribs, 'down')
nextItemState: (state, dir) ->
obj = state.element.children('ul')
# calc height
height = state.itemHeight
height = obj.children('li:first').height() if state.options.height > 0
height += state.options.margin + state.options.padding * 2
# attributes
height: height
options: state.options
el: state.element
obj: obj
selector: if dir == 'up' then 'li:first' else 'li:last'
dir: dir
showNextItem: (state, attribs, dir) ->
nis = internal.nextItemState(state, dir)
nis.el.trigger 'vticker.beforeTick'
clone = nis.obj.children(nis.selector).clone(true)
# adjust for margins & padding
nis.obj.css('top', '-' + nis.height + 'px').prepend(clone) if nis.dir == 'down'
if attribs && attribs.animate
internal.animateNextItem(nis, state) unless state.animating
else
internal.nonAnimatedNextItem(nis)
clone.appendTo(nis.obj) if nis.dir == 'up' && state.options.autoAppend
nis.el.trigger 'vticker.afterTick'
animateNextItem: (nis, state) ->
state.animating = true
opts = if nis.dir == 'up' then top: '-=' + nis.height + 'px' else top: 0
nis.obj.animate opts, state.options.speed, ->
$(nis.obj).children(nis.selector).remove()
$(nis.obj).css 'top', '0px'
state.animating = false
nonAnimatedNextItem: (nis) ->
nis.obj.children(nis.selector).remove()
nis.obj.css 'top', '0px'
nextUsePause: ->
state = $(@).data('state')
options = state.options
return if state.isPaused || internal.hasSingleItem(state)
methods.next.call @, animate: options.animate
startInterval: ->
state = $(@).data('state')
options = state.options
state.intervalId = setInterval =>
internal.nextUsePause.call @
, options.pause
stopInterval: ->
return unless state = $(@).data('state')
clearInterval state.intervalId if state.intervalId
state.intervalId = undefined
restartInterval: ->
internal.stopInterval.call @
internal.startInterval.call @
getState: (from, elem) ->
throw new Error("vTicker: No state available from #{from}") unless state = $(elem).data('state')
state
isAnimatingOrSingleItem: (state) -> state.animating || @hasSingleItem(state)
hasMultipleItems: (state) -> state.itemCount > 1
hasSingleItem: (state) -> !internal.hasMultipleItems(state)
bindMousePausing: (el, state) =>
el.bind 'mouseenter', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused
state.pausedByCode = true
# stop interval
internal.stopInterval.call @
methods.pause.call @, true
.bind 'mouseleave', ->
# if the automatic scroll is paused, don't change that.
return if state.isPaused && !state.pausedByCode
state.pausedByCode = false
methods.pause.call @, false
# restart interval
internal.startInterval.call @
setItemLayout: (el, state, options) ->
el.css(overflow: 'hidden', position: 'relative')
.children('ul').css(position: 'absolute', margin: 0, padding: 0)
.children('li').css(margin: options.margin, padding: options.padding)
if isNaN(options.height) || options.height == 0
el.children('ul').children('li').each -> state.itemHeight = $(@).height() if $(@).height() > state.itemHeight
# set the same height on all child elements
el.children('ul').children('li').each -> $(@).height(state.itemHeight)
# set element to total height
box = options.margin + options.padding * 2
el.height (state.itemHeight + box) * options.showItems + options.margin
else
el.height options.height # set the preferred height
defaultStateAttribs: (el, options) ->
itemCount: el.children('ul').children('li').length
itemHeight: 0
itemMargin: 0
element: el
animating: false
options: options
isPaused: options.startPaused
pausedByCode: false
methods =
init: (options) ->
methods.stop.call @ if state = $(@).data('state') # if init called second time then stop first, then re-init
state = null
clonedDefaults = jQuery.extend({}, defaults)
options = $.extend(clonedDefaults, options)
el = $(@)
state = internal.defaultStateAttribs(el, options)
$(@).data('state', state)
internal.setItemLayout(el, state, options)
internal.startInterval.call @ unless options.startPaused
internal.bindMousePausing(el, state) if options.mousePause
pause: (pauseState) ->
state = internal.getState('pause', @)
return false unless internal.hasMultipleItems(state)
state.isPaused = pauseState
el = state.element
if pauseState
$(@).addClass 'paused'
el.trigger 'vticker.pause'
else
$(@).removeClass 'paused'
el.trigger 'vticker.resume'
next: (attribs) ->
state = internal.getState('next', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveUp state, attribs
prev: (attribs) ->
state = internal.getState('prev', @)
return false if internal.isAnimatingOrSingleItem(state)
internal.restartInterval.call @
internal.moveDown state, attribs
stop: ->
state = internal.getState('stop', @)
internal.stopInterval.call @
remove: ->
state = internal.getState('remove', @)
internal.stopInterval.call @
el = state.element
el.unbind()
el.remove()
$.fn.vTicker = (method) ->
return methods[method].apply(@, Array::slice.call(arguments, 1)) if methods[method]
return methods.init.apply(@, arguments) if typeof method == 'object' || !method
$.error 'Method ' + method + ' does not exist on jQuery.vTicker'
) jQuery |
[
{
"context": "# ----------------------------------------------\n# Nick: Phantombuster's custom navigation module\n# -----",
"end": 55,
"score": 0.9990307688713074,
"start": 51,
"tag": "NAME",
"value": "Nick"
},
{
"context": "------------------------------------------\n# Nick: Phantombuster's custom navigation module\n# --------------------",
"end": 70,
"score": 0.999319314956665,
"start": 57,
"tag": "NAME",
"value": "Phantombuster"
},
{
"context": "k', params: ['selector string'] },\n\t{ nick: 'clickLabel', casper: 'clickLabel', type: 'callback', params:",
"end": 22123,
"score": 0.7112483978271484,
"start": 22118,
"tag": "USERNAME",
"value": "Label"
},
{
"context": "tUrl', type: 'callback' },\n\t{ nick: 'getCurrentUrlOrNull', casper: 'getCurrentUrl', type: 'sync' },\n\t{ nic",
"end": 22324,
"score": 0.8621681332588196,
"start": 22318,
"tag": "USERNAME",
"value": "OrNull"
},
{
"context": "sper: 'getHTML', type: 'callback' },\n\t{ nick: 'getHtmlOrNull', casper: 'getHTML', type: 'sync' },\n\t{ nick: 'ge",
"end": 22450,
"score": 0.7708173394203186,
"start": 22440,
"tag": "USERNAME",
"value": "HtmlOrNull"
},
{
"context": "ent', type: 'callback' },\n\t{ nick: 'getPageContentOrNull', casper: 'getPageContent', type: 'sync' },\n\t{ ni",
"end": 22591,
"score": 0.9034144878387451,
"start": 22585,
"tag": "USERNAME",
"value": "OrNull"
},
{
"context": "Content', type: 'callback' },\n\t{ nick: 'getContentOrNull', casper: 'getPageContent', type: 'sync' },\n\t{ ni",
"end": 22731,
"score": 0.9651522040367126,
"start": 22725,
"tag": "USERNAME",
"value": "OrNull"
},
{
"context": "'getTitle', type: 'callback' },\n\t{ nick: 'getTitleOrNull', casper: 'getTitle', type: 'sync' },\n\t{ nick: 'f",
"end": 22861,
"score": 0.9646655321121216,
"start": 22855,
"tag": "USERNAME",
"value": "OrNull"
}
] | libs/lib-Nick-beta.coffee | shubs/api-store | 8 | # ----------------------------------------------
# Nick: Phantombuster's custom navigation module
# ----------------------------------------------
#
# This modules provides an easy navigation/web automation/scraping system based
# on CasperJS.
#
# Always launch a script using this module with the CasperJS command.
#
# Please read the full documentation here: http://docs.phantombuster.com/en/latest/nick.html
'use strict'
require = patchRequire global.require
userAgents = [
# Internet Explorer
# from: http://www.useragentstring.com/pages/Internet%20Explorer/
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-US)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)'
'Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7)'
# Edge
# from: http://www.useragentstring.com/pages/Edge/
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
# Firefox
# from: http://www.useragentstring.com/pages/Firefox/
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0'
'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0'
'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0'
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0'
'Mozilla/5.0 (X11; OpenBSD amd64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0'
# Chrome
# from: http://www.useragentstring.com/pages/Chrome/
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'
'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
# Safari
# from: http://www.useragentstring.com/pages/Safari/
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'
]
class Nick
constructor: (options) ->
@_ended = no
@_nextStep = null
@_stepIsRunning = no
@_endCallback = null
casperOptions =
verbose: no
colorizerType: 'Dummy'
exitOnError: yes
silentErrors: no
retryTimeout: 25
pageSettings:
localToRemoteUrlAccessEnabled: yes
webSecurityEnabled: no
loadPlugins: no
logLevel: 'debug'
viewportSize:
width: 1280
height: 1024
# build blacklist array by merging "blacklist" and "blocked" options + check types
blacklist = []
if options?.blacklist?
if Array.isArray options.blacklist
for black in options.blacklist
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blocked option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blocked option must be an array of strings or regexes'
if options?.blocked?
if Array.isArray options.blocked
for black in options.blocked
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blacklist option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blacklist option must be an array of strings or regexes'
# build whitelist array by merging "whitelist" and "allowed" options + check types
whitelist = []
if options?.whitelist?
if Array.isArray options.whitelist
for white in options.whitelist
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'whitelist option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'whitelist option must be an array of strings or regexes'
if options?.allowed?
if Array.isArray options.allowed
for white in options.allowed
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'allowed option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'allowed option must be an array of strings or regexes'
# set up the blacklisting and whitelisting from both arrays
onResourceRequested = null
if whitelist.length or blacklist.length
onResourceRequested = (request, net) =>
if whitelist.length
found = no
for white in whitelist
if typeof(white) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(white) is 0) or (url.indexOf("https://#{white}") is 0) or (url.indexOf("http://#{white}") is 0)
found = yes
break
else if white.test(request.url)
found = yes
break
if not found
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (not found in whitelist): #{request.url}"
return net.abort()
for black in blacklist
if typeof(black) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(black) is 0) or (url.indexOf("https://#{black}") is 0) or (url.indexOf("http://#{black}") is 0)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by \"#{black}\"): #{url}"
return net.abort()
else if black.test(request.url)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by #{black}): #{request.url}"
return net.abort()
if options?.userAgent?
if typeof(options.userAgent) is 'string'
casperOptions.pageSettings.userAgent = options.userAgent
else
throw new Error 'userAgent option must be a string'
else
casperOptions.pageSettings.userAgent = userAgents[Math.floor(Math.random() * userAgents.length)]
if options?.resourceTimeout?
if typeof(options.resourceTimeout) is 'number'
casperOptions.pageSettings.resourceTimeout = options.resourceTimeout
else
throw new Error 'resourceTimeout option must be a number'
else
casperOptions.pageSettings.resourceTimeout = 10000
# dont set loadImages to true by default to prevent overriding the command line option
if options?.loadImages?
if typeof(options.loadImages) is 'boolean'
casperOptions.pageSettings.loadImages = options.loadImages
else
throw new Error 'loadImages option must be a boolean'
if options?.width?
if typeof(options.width) is 'number'
casperOptions.viewportSize.width = options.width
else
throw new Error 'width option must be a number'
if options?.height?
if typeof(options.height) is 'number'
casperOptions.viewportSize.height = options.height
else
throw new Error 'height option must be a number'
@casper = require('casper').create casperOptions
if (not options?.printNavigation?) or options?.printNavigation
@casper.on 'navigation.requested', (url, type, isLocked, isMainFrame) ->
if isMainFrame
console.log "> Navigation#{if type isnt 'Other' then " (#{type})" else ''}#{if isLocked then '' else ' (not locked!)'}: #{url}"
@casper.on 'page.created', (page) ->
console.log '> New PhantomJS WebPage created'
page.onResourceTimeout = (request) ->
console.log "> Timeout of #{request.url}"
if (not options?.printPageErrors?) or options?.printPageErrors
@casper.on 'page.error', (err) ->
console.log "> Page JavaScrit error: #{err}"
if (not options?.printResourceErrors?) or options?.printResourceErrors
@casper.on 'resource.error', (err) ->
if err.errorString is 'Protocol "" is unknown' # when a resource is aborted (net.abort()), this error is generated
return
message = "> Resource error: #{if err.status? then "#{err.status} - " else ''}#{if err.statusText? then "#{err.statusText} - " else ''}#{err.errorString}"
if (typeof(err.url) is 'string') and (message.indexOf(err.url) < 0)
message += " (#{err.url})"
console.log message
if onResourceRequested?
@casper.on 'resource.requested', onResourceRequested
# better logging of stack trace
# (is it a good idea to override this on every new nick instance?
# but we need to because casperjs does it anyway and logs nothing...)
phantom.onError = (msg, trace) ->
console.log "\n#{msg}"
if trace and trace.length
for f in trace
console.log ' at ' + (f.file or f.sourceURL) + ':' + f.line + (if f.function then (' (in function ' + f.function + ')') else '')
console.log ''
phantom.exit 1
# open() error detection
@_openState =
inProgress: no
error: null
httpCode: null
httpStatus: null
url: null
last50Errors: []
# collects errors to get the most important thing: the errorString field
@casper.on 'resource.error', (error) =>
if @_openState.inProgress
@_openState.last50Errors.push error
if @_openState.last50Errors.length > 50
@_openState.last50Errors.shift()
# this event always arrives after the eventual resource.error events
# so we search back in our history of errors to find the corresponding errorString
@casper.on 'page.resource.received', (resource) =>
if @_openState.inProgress
if typeof(resource.status) isnt 'number'
@_openState.error = 'unknown error'
if typeof(resource.id) is 'number'
for err in @_openState.last50Errors
if resource.id is err.id
if typeof(err.errorString) is 'string'
@_openState.error = err.errorString
else
@_openState.httpCode = resource.status
@_openState.httpStatus = resource.statusText
@_openState.url = resource.url
# start the CasperJS wait loop
@casper.start null, null
waitLoop = () =>
@casper.wait 10
@casper.then () =>
if not @_ended
if @_nextStep?
step = @_nextStep
@_nextStep = null
@_stepIsRunning = yes
step()
waitLoop()
waitLoop()
@casper.run () =>
if @_endCallback?
@_endCallback()
_addStep: (step) =>
if @_ended
throw new Error 'this Nick instance has finished its work (end() was called) - no other actions can be done with it'
if @_nextStep? or @_stepIsRunning
throw new Error 'cannot do this while another Nick method is already running - each Nick instance can execute only one action at a time'
@_nextStep = step
return null
open: (url, options, callback) =>
if typeof(url) isnt 'string'
throw new Error 'open: url parameter must be of type string'
if typeof(options) is 'function'
callback = options
options = null
if options? and (typeof(options) isnt 'object')
throw new Error 'open: options parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'open: callback parameter must be of type function'
if url.indexOf('://') < 0
url = 'http://' + url
return @_addStep () =>
@casper.clear()
@_openState.inProgress = yes
@_openState.error = null
@_openState.httpCode = null
@_openState.httpStatus = null
@_openState.url = null
@casper.thenOpen url, options
@casper.then () =>
@_stepIsRunning = no
@_openState.inProgress = no
@_openState.last50Errors = []
# we must either have an error or an http code
# if we dont, no page.resource.received event was never received (we consider this an error except for file:// urls)
if @_openState.error? or @_openState.httpCode?
callback @_openState.error, @_openState.httpCode, @_openState.httpStatus, @_openState.url
else
if url.trim().toLowerCase().indexOf('file://') is 0
# no network requests are made for file:// urls, so we ignore the fact that we did not receive any event
callback null, null, @_openState.httpStatus, @_openState.url
else
callback 'unknown error', null, @_openState.httpStatus, @_openState.url
inject: (url, callback) =>
if typeof(url) isnt 'string'
throw new Error 'inject: url parameter must be of type string'
if typeof(callback) isnt 'function'
throw new Error 'inject: callback parameter must be of type function'
return @_addStep () =>
err = null
try
if (url.trim().toLowerCase().indexOf('http://') is 0) or (url.trim().toLowerCase().indexOf('https://') is 0)
@casper.page.includeJs url
else
@casper.page.injectJs url
catch e
err = e.toString()
@_stepIsRunning = no
callback err
evaluateAsync: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
callback = (err, res) ->
window.__evaluateAsyncFinished = yes
window.__evaluateAsyncErr = err
window.__evaluateAsyncRes = res
try
window.__evaluateAsyncFinished = no
window.__evaluateAsyncErr = null
window.__evaluateAsyncRes = null
(eval "(#{__code})")(__param, callback)
return null
catch e
return e.toString()
err = @casper.evaluate f, param, func.toString()
if err
err = "in evaluated code (initial call): #{err}"
catch e
err = "in casper context (initial call): #{e.toString()}"
if err
@_stepIsRunning = no
callback err, null
else
check = () =>
try
res = @casper.evaluate () ->
return {
finished: window.__evaluateAsyncFinished
err: (if window.__evaluateAsyncErr? then window.__evaluateAsyncErr else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
res: (if window.__evaluateAsyncRes? then window.__evaluateAsyncRes else undefined)
}
if res.finished
@_stepIsRunning = no
callback (if res.err? then res.err else null), (if res.res? then res.res else null)
else
setTimeout check, 200
catch e
@_stepIsRunning = no
callback "in casper context (callback): #{e.toString()}", null
setTimeout check, 100
evaluate: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
try
res = (eval "(#{__code})")(__param)
return {
res: (if res? then res else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
err: undefined
}
catch e
return {
res: undefined
err: e.toString()
}
res = @casper.evaluate f, param, func.toString()
if res?
if res.err?
err = "in evaluated code: #{res.err}"
res = null
else
err = null
res = (if res.res? then res.res else null)
else
err = "no result returned"
res = null
catch e
err = "in casper context: #{e.toString()}"
@_stepIsRunning = no
callback err, res
end: (callback) =>
if typeof(callback) isnt 'function'
throw new Error 'end: callback parameter must be a function'
return @_addStep () =>
@_ended = yes
@_endCallback = callback
@_stepIsRunning = no
exit: (code) =>
return phantom.exit code
methods = [
[ 'waitUntilPresent', 'waitForSelector' ],
[ 'waitWhilePresent', 'waitWhileSelector' ],
[ 'waitUntilVisible', 'waitUntilVisible' ],
[ 'waitWhileVisible', 'waitWhileVisible' ],
]
injectMethod = (nickMethod, casperMethod) ->
Nick.prototype[nickMethod] = (selectors, duration, condition, callback) ->
if (typeof(condition) is 'function') and (not callback?)
callback = condition
condition = 'and'
if not Array.isArray(selectors)
selectors = [selectors]
if selectors.length is 0
throw new Error "#{nickMethod}: selectors array must contain at least one selector"
for selector in selectors
if typeof(selector) isnt 'string'
throw new Error "#{nickMethod}: selectors parameter must be a string or an array of strings"
if (typeof(duration) isnt 'number') or (duration < (selectors.length * (@casper.options.retryTimeout * 2)))
throw new Error "#{nickMethod}: duration parameter must be a number >= #{selectors.length * (@casper.options.retryTimeout * 2)} (minimum of #{@casper.options.retryTimeout * 2}ms per selector)"
if not (condition in ['and', 'or'])
throw new Error "#{nickMethod}: condition parameter must be either 'and' or 'or'"
if typeof(callback) isnt 'function'
throw new Error "#{nickMethod}: callback parameter must be of type function"
return @_addStep () =>
start = Date.now()
index = 0
if condition is 'and'
nextSelector = () =>
success = () =>
++index
if index >= selectors.length
@_stepIsRunning = no
callback null, null
else
duration -= (Date.now() - start)
if duration < (@casper.options.retryTimeout * 2)
duration = (@casper.options.retryTimeout * 2)
nextSelector()
failure = () =>
@_stepIsRunning = no
callback "waited #{Date.now() - start}ms but element \"#{selectors[index]}\" still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", selectors[index]
@casper[casperMethod] selectors[index], success, failure, duration
else
waitedForAll = no
nextSelector = () =>
success = () =>
@_stepIsRunning = no
callback null, selectors[index]
failure = () =>
if waitedForAll and ((start + duration) < Date.now())
@_stepIsRunning = no
elementsToString = selectors.slice()
for e in elementsToString
e = "\"#{e}\""
elementsToString = elementsToString.join ', '
callback "waited #{Date.now() - start}ms but element#{if (selectors.length > 0) then 's' else ''} #{elementsToString} still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", null
else
++index
if index >= selectors.length
waitedForAll = yes
index = 0
nextSelector()
@casper[casperMethod] selectors[index], success, failure, (@casper.options.retryTimeout * 2)
nextSelector()
for method in methods
injectMethod method[0], method[1]
methods = [
{ nick: 'wait', casper: 'wait', type: 'step', params: ['duration number'] },
{ nick: 'click', casper: 'click', type: 'callback', params: ['selector string'] },
{ nick: 'clickLabel', casper: 'clickLabel', type: 'callback', params: ['selector string'], optional: ['type string'] },
{ nick: 'getCurrentUrl', casper: 'getCurrentUrl', type: 'callback' },
{ nick: 'getCurrentUrlOrNull', casper: 'getCurrentUrl', type: 'sync' },
{ nick: 'getHtml', casper: 'getHTML', type: 'callback' },
{ nick: 'getHtmlOrNull', casper: 'getHTML', type: 'sync' },
{ nick: 'getPageContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getPageContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getTitle', casper: 'getTitle', type: 'callback' },
{ nick: 'getTitleOrNull', casper: 'getTitle', type: 'sync' },
{ nick: 'fill', casper: 'fill', type: 'callback', params: ['selector string', 'params object'], optional: ['submit boolean'] },
{ nick: 'screenshot', casper: 'capture', type: 'callback', params: ['filename string'], optional: ['rect object', 'options object'] },
{ nick: 'selectorScreenshot', casper: 'captureSelector', type: 'callback', params: ['filename string', 'selector string'], optional: ['options object'] },
{ nick: 'sendKeys', casper: 'sendKeys', type: 'callback', params: ['selector string', 'keys string'], optional: ['options object'] },
]
injectMethod = (method) ->
Nick.prototype[method.nick] = () ->
args = Array.prototype.slice.call arguments
if method.type isnt 'sync'
if (args.length is 0) or (typeof(args[args.length - 1]) isnt 'function')
throw new Error "#{method.nick}: callback parameter must be of type function"
callback = args.pop()
if method.params?
params = method.params
if args.length < params.length
throw new Error "#{method.nick}: #{params[args.length].split(' ')[0]} parameter is missing"
if method.optional?
params = params.concat method.optional
argPos = 0
for arg in args
if argPos >= params.length
throw new Error "#{method.nick}: too many arguments"
param = params[argPos].split ' '
if (typeof(arg) isnt param[1]) or (not arg?)
throw new Error "#{method.nick}: #{param[0]} parameter must be of type #{param[1]}"
++argPos
else if args.length
throw new Error "#{method.nick}: too many arguments"
if method.type is 'sync'
try
return @casper[method.casper].apply @casper, args
catch e
return null
else
return @_addStep () =>
if method.type is 'step'
args.push () =>
@_stepIsRunning = no
callback()
@casper[method.casper].apply @casper, args
else
err = null
res = null
try
res = @casper[method.casper].apply @casper, args
catch e
err = e.toString()
@_stepIsRunning = no
callback err, res
for method in methods
injectMethod method
module.exports = Nick
| 103857 | # ----------------------------------------------
# <NAME>: <NAME>'s custom navigation module
# ----------------------------------------------
#
# This modules provides an easy navigation/web automation/scraping system based
# on CasperJS.
#
# Always launch a script using this module with the CasperJS command.
#
# Please read the full documentation here: http://docs.phantombuster.com/en/latest/nick.html
'use strict'
require = patchRequire global.require
userAgents = [
# Internet Explorer
# from: http://www.useragentstring.com/pages/Internet%20Explorer/
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-US)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)'
'Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7)'
# Edge
# from: http://www.useragentstring.com/pages/Edge/
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
# Firefox
# from: http://www.useragentstring.com/pages/Firefox/
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0'
'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0'
'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0'
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0'
'Mozilla/5.0 (X11; OpenBSD amd64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0'
# Chrome
# from: http://www.useragentstring.com/pages/Chrome/
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'
'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
# Safari
# from: http://www.useragentstring.com/pages/Safari/
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'
]
class Nick
constructor: (options) ->
@_ended = no
@_nextStep = null
@_stepIsRunning = no
@_endCallback = null
casperOptions =
verbose: no
colorizerType: 'Dummy'
exitOnError: yes
silentErrors: no
retryTimeout: 25
pageSettings:
localToRemoteUrlAccessEnabled: yes
webSecurityEnabled: no
loadPlugins: no
logLevel: 'debug'
viewportSize:
width: 1280
height: 1024
# build blacklist array by merging "blacklist" and "blocked" options + check types
blacklist = []
if options?.blacklist?
if Array.isArray options.blacklist
for black in options.blacklist
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blocked option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blocked option must be an array of strings or regexes'
if options?.blocked?
if Array.isArray options.blocked
for black in options.blocked
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blacklist option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blacklist option must be an array of strings or regexes'
# build whitelist array by merging "whitelist" and "allowed" options + check types
whitelist = []
if options?.whitelist?
if Array.isArray options.whitelist
for white in options.whitelist
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'whitelist option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'whitelist option must be an array of strings or regexes'
if options?.allowed?
if Array.isArray options.allowed
for white in options.allowed
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'allowed option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'allowed option must be an array of strings or regexes'
# set up the blacklisting and whitelisting from both arrays
onResourceRequested = null
if whitelist.length or blacklist.length
onResourceRequested = (request, net) =>
if whitelist.length
found = no
for white in whitelist
if typeof(white) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(white) is 0) or (url.indexOf("https://#{white}") is 0) or (url.indexOf("http://#{white}") is 0)
found = yes
break
else if white.test(request.url)
found = yes
break
if not found
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (not found in whitelist): #{request.url}"
return net.abort()
for black in blacklist
if typeof(black) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(black) is 0) or (url.indexOf("https://#{black}") is 0) or (url.indexOf("http://#{black}") is 0)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by \"#{black}\"): #{url}"
return net.abort()
else if black.test(request.url)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by #{black}): #{request.url}"
return net.abort()
if options?.userAgent?
if typeof(options.userAgent) is 'string'
casperOptions.pageSettings.userAgent = options.userAgent
else
throw new Error 'userAgent option must be a string'
else
casperOptions.pageSettings.userAgent = userAgents[Math.floor(Math.random() * userAgents.length)]
if options?.resourceTimeout?
if typeof(options.resourceTimeout) is 'number'
casperOptions.pageSettings.resourceTimeout = options.resourceTimeout
else
throw new Error 'resourceTimeout option must be a number'
else
casperOptions.pageSettings.resourceTimeout = 10000
# dont set loadImages to true by default to prevent overriding the command line option
if options?.loadImages?
if typeof(options.loadImages) is 'boolean'
casperOptions.pageSettings.loadImages = options.loadImages
else
throw new Error 'loadImages option must be a boolean'
if options?.width?
if typeof(options.width) is 'number'
casperOptions.viewportSize.width = options.width
else
throw new Error 'width option must be a number'
if options?.height?
if typeof(options.height) is 'number'
casperOptions.viewportSize.height = options.height
else
throw new Error 'height option must be a number'
@casper = require('casper').create casperOptions
if (not options?.printNavigation?) or options?.printNavigation
@casper.on 'navigation.requested', (url, type, isLocked, isMainFrame) ->
if isMainFrame
console.log "> Navigation#{if type isnt 'Other' then " (#{type})" else ''}#{if isLocked then '' else ' (not locked!)'}: #{url}"
@casper.on 'page.created', (page) ->
console.log '> New PhantomJS WebPage created'
page.onResourceTimeout = (request) ->
console.log "> Timeout of #{request.url}"
if (not options?.printPageErrors?) or options?.printPageErrors
@casper.on 'page.error', (err) ->
console.log "> Page JavaScrit error: #{err}"
if (not options?.printResourceErrors?) or options?.printResourceErrors
@casper.on 'resource.error', (err) ->
if err.errorString is 'Protocol "" is unknown' # when a resource is aborted (net.abort()), this error is generated
return
message = "> Resource error: #{if err.status? then "#{err.status} - " else ''}#{if err.statusText? then "#{err.statusText} - " else ''}#{err.errorString}"
if (typeof(err.url) is 'string') and (message.indexOf(err.url) < 0)
message += " (#{err.url})"
console.log message
if onResourceRequested?
@casper.on 'resource.requested', onResourceRequested
# better logging of stack trace
# (is it a good idea to override this on every new nick instance?
# but we need to because casperjs does it anyway and logs nothing...)
phantom.onError = (msg, trace) ->
console.log "\n#{msg}"
if trace and trace.length
for f in trace
console.log ' at ' + (f.file or f.sourceURL) + ':' + f.line + (if f.function then (' (in function ' + f.function + ')') else '')
console.log ''
phantom.exit 1
# open() error detection
@_openState =
inProgress: no
error: null
httpCode: null
httpStatus: null
url: null
last50Errors: []
# collects errors to get the most important thing: the errorString field
@casper.on 'resource.error', (error) =>
if @_openState.inProgress
@_openState.last50Errors.push error
if @_openState.last50Errors.length > 50
@_openState.last50Errors.shift()
# this event always arrives after the eventual resource.error events
# so we search back in our history of errors to find the corresponding errorString
@casper.on 'page.resource.received', (resource) =>
if @_openState.inProgress
if typeof(resource.status) isnt 'number'
@_openState.error = 'unknown error'
if typeof(resource.id) is 'number'
for err in @_openState.last50Errors
if resource.id is err.id
if typeof(err.errorString) is 'string'
@_openState.error = err.errorString
else
@_openState.httpCode = resource.status
@_openState.httpStatus = resource.statusText
@_openState.url = resource.url
# start the CasperJS wait loop
@casper.start null, null
waitLoop = () =>
@casper.wait 10
@casper.then () =>
if not @_ended
if @_nextStep?
step = @_nextStep
@_nextStep = null
@_stepIsRunning = yes
step()
waitLoop()
waitLoop()
@casper.run () =>
if @_endCallback?
@_endCallback()
_addStep: (step) =>
if @_ended
throw new Error 'this Nick instance has finished its work (end() was called) - no other actions can be done with it'
if @_nextStep? or @_stepIsRunning
throw new Error 'cannot do this while another Nick method is already running - each Nick instance can execute only one action at a time'
@_nextStep = step
return null
open: (url, options, callback) =>
if typeof(url) isnt 'string'
throw new Error 'open: url parameter must be of type string'
if typeof(options) is 'function'
callback = options
options = null
if options? and (typeof(options) isnt 'object')
throw new Error 'open: options parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'open: callback parameter must be of type function'
if url.indexOf('://') < 0
url = 'http://' + url
return @_addStep () =>
@casper.clear()
@_openState.inProgress = yes
@_openState.error = null
@_openState.httpCode = null
@_openState.httpStatus = null
@_openState.url = null
@casper.thenOpen url, options
@casper.then () =>
@_stepIsRunning = no
@_openState.inProgress = no
@_openState.last50Errors = []
# we must either have an error or an http code
# if we dont, no page.resource.received event was never received (we consider this an error except for file:// urls)
if @_openState.error? or @_openState.httpCode?
callback @_openState.error, @_openState.httpCode, @_openState.httpStatus, @_openState.url
else
if url.trim().toLowerCase().indexOf('file://') is 0
# no network requests are made for file:// urls, so we ignore the fact that we did not receive any event
callback null, null, @_openState.httpStatus, @_openState.url
else
callback 'unknown error', null, @_openState.httpStatus, @_openState.url
inject: (url, callback) =>
if typeof(url) isnt 'string'
throw new Error 'inject: url parameter must be of type string'
if typeof(callback) isnt 'function'
throw new Error 'inject: callback parameter must be of type function'
return @_addStep () =>
err = null
try
if (url.trim().toLowerCase().indexOf('http://') is 0) or (url.trim().toLowerCase().indexOf('https://') is 0)
@casper.page.includeJs url
else
@casper.page.injectJs url
catch e
err = e.toString()
@_stepIsRunning = no
callback err
evaluateAsync: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
callback = (err, res) ->
window.__evaluateAsyncFinished = yes
window.__evaluateAsyncErr = err
window.__evaluateAsyncRes = res
try
window.__evaluateAsyncFinished = no
window.__evaluateAsyncErr = null
window.__evaluateAsyncRes = null
(eval "(#{__code})")(__param, callback)
return null
catch e
return e.toString()
err = @casper.evaluate f, param, func.toString()
if err
err = "in evaluated code (initial call): #{err}"
catch e
err = "in casper context (initial call): #{e.toString()}"
if err
@_stepIsRunning = no
callback err, null
else
check = () =>
try
res = @casper.evaluate () ->
return {
finished: window.__evaluateAsyncFinished
err: (if window.__evaluateAsyncErr? then window.__evaluateAsyncErr else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
res: (if window.__evaluateAsyncRes? then window.__evaluateAsyncRes else undefined)
}
if res.finished
@_stepIsRunning = no
callback (if res.err? then res.err else null), (if res.res? then res.res else null)
else
setTimeout check, 200
catch e
@_stepIsRunning = no
callback "in casper context (callback): #{e.toString()}", null
setTimeout check, 100
evaluate: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
try
res = (eval "(#{__code})")(__param)
return {
res: (if res? then res else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
err: undefined
}
catch e
return {
res: undefined
err: e.toString()
}
res = @casper.evaluate f, param, func.toString()
if res?
if res.err?
err = "in evaluated code: #{res.err}"
res = null
else
err = null
res = (if res.res? then res.res else null)
else
err = "no result returned"
res = null
catch e
err = "in casper context: #{e.toString()}"
@_stepIsRunning = no
callback err, res
end: (callback) =>
if typeof(callback) isnt 'function'
throw new Error 'end: callback parameter must be a function'
return @_addStep () =>
@_ended = yes
@_endCallback = callback
@_stepIsRunning = no
exit: (code) =>
return phantom.exit code
methods = [
[ 'waitUntilPresent', 'waitForSelector' ],
[ 'waitWhilePresent', 'waitWhileSelector' ],
[ 'waitUntilVisible', 'waitUntilVisible' ],
[ 'waitWhileVisible', 'waitWhileVisible' ],
]
injectMethod = (nickMethod, casperMethod) ->
Nick.prototype[nickMethod] = (selectors, duration, condition, callback) ->
if (typeof(condition) is 'function') and (not callback?)
callback = condition
condition = 'and'
if not Array.isArray(selectors)
selectors = [selectors]
if selectors.length is 0
throw new Error "#{nickMethod}: selectors array must contain at least one selector"
for selector in selectors
if typeof(selector) isnt 'string'
throw new Error "#{nickMethod}: selectors parameter must be a string or an array of strings"
if (typeof(duration) isnt 'number') or (duration < (selectors.length * (@casper.options.retryTimeout * 2)))
throw new Error "#{nickMethod}: duration parameter must be a number >= #{selectors.length * (@casper.options.retryTimeout * 2)} (minimum of #{@casper.options.retryTimeout * 2}ms per selector)"
if not (condition in ['and', 'or'])
throw new Error "#{nickMethod}: condition parameter must be either 'and' or 'or'"
if typeof(callback) isnt 'function'
throw new Error "#{nickMethod}: callback parameter must be of type function"
return @_addStep () =>
start = Date.now()
index = 0
if condition is 'and'
nextSelector = () =>
success = () =>
++index
if index >= selectors.length
@_stepIsRunning = no
callback null, null
else
duration -= (Date.now() - start)
if duration < (@casper.options.retryTimeout * 2)
duration = (@casper.options.retryTimeout * 2)
nextSelector()
failure = () =>
@_stepIsRunning = no
callback "waited #{Date.now() - start}ms but element \"#{selectors[index]}\" still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", selectors[index]
@casper[casperMethod] selectors[index], success, failure, duration
else
waitedForAll = no
nextSelector = () =>
success = () =>
@_stepIsRunning = no
callback null, selectors[index]
failure = () =>
if waitedForAll and ((start + duration) < Date.now())
@_stepIsRunning = no
elementsToString = selectors.slice()
for e in elementsToString
e = "\"#{e}\""
elementsToString = elementsToString.join ', '
callback "waited #{Date.now() - start}ms but element#{if (selectors.length > 0) then 's' else ''} #{elementsToString} still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", null
else
++index
if index >= selectors.length
waitedForAll = yes
index = 0
nextSelector()
@casper[casperMethod] selectors[index], success, failure, (@casper.options.retryTimeout * 2)
nextSelector()
for method in methods
injectMethod method[0], method[1]
methods = [
{ nick: 'wait', casper: 'wait', type: 'step', params: ['duration number'] },
{ nick: 'click', casper: 'click', type: 'callback', params: ['selector string'] },
{ nick: 'clickLabel', casper: 'clickLabel', type: 'callback', params: ['selector string'], optional: ['type string'] },
{ nick: 'getCurrentUrl', casper: 'getCurrentUrl', type: 'callback' },
{ nick: 'getCurrentUrlOrNull', casper: 'getCurrentUrl', type: 'sync' },
{ nick: 'getHtml', casper: 'getHTML', type: 'callback' },
{ nick: 'getHtmlOrNull', casper: 'getHTML', type: 'sync' },
{ nick: 'getPageContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getPageContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getTitle', casper: 'getTitle', type: 'callback' },
{ nick: 'getTitleOrNull', casper: 'getTitle', type: 'sync' },
{ nick: 'fill', casper: 'fill', type: 'callback', params: ['selector string', 'params object'], optional: ['submit boolean'] },
{ nick: 'screenshot', casper: 'capture', type: 'callback', params: ['filename string'], optional: ['rect object', 'options object'] },
{ nick: 'selectorScreenshot', casper: 'captureSelector', type: 'callback', params: ['filename string', 'selector string'], optional: ['options object'] },
{ nick: 'sendKeys', casper: 'sendKeys', type: 'callback', params: ['selector string', 'keys string'], optional: ['options object'] },
]
injectMethod = (method) ->
Nick.prototype[method.nick] = () ->
args = Array.prototype.slice.call arguments
if method.type isnt 'sync'
if (args.length is 0) or (typeof(args[args.length - 1]) isnt 'function')
throw new Error "#{method.nick}: callback parameter must be of type function"
callback = args.pop()
if method.params?
params = method.params
if args.length < params.length
throw new Error "#{method.nick}: #{params[args.length].split(' ')[0]} parameter is missing"
if method.optional?
params = params.concat method.optional
argPos = 0
for arg in args
if argPos >= params.length
throw new Error "#{method.nick}: too many arguments"
param = params[argPos].split ' '
if (typeof(arg) isnt param[1]) or (not arg?)
throw new Error "#{method.nick}: #{param[0]} parameter must be of type #{param[1]}"
++argPos
else if args.length
throw new Error "#{method.nick}: too many arguments"
if method.type is 'sync'
try
return @casper[method.casper].apply @casper, args
catch e
return null
else
return @_addStep () =>
if method.type is 'step'
args.push () =>
@_stepIsRunning = no
callback()
@casper[method.casper].apply @casper, args
else
err = null
res = null
try
res = @casper[method.casper].apply @casper, args
catch e
err = e.toString()
@_stepIsRunning = no
callback err, res
for method in methods
injectMethod method
module.exports = Nick
| true | # ----------------------------------------------
# PI:NAME:<NAME>END_PI: PI:NAME:<NAME>END_PI's custom navigation module
# ----------------------------------------------
#
# This modules provides an easy navigation/web automation/scraping system based
# on CasperJS.
#
# Always launch a script using this module with the CasperJS command.
#
# Please read the full documentation here: http://docs.phantombuster.com/en/latest/nick.html
'use strict'
require = patchRequire global.require
userAgents = [
# Internet Explorer
# from: http://www.useragentstring.com/pages/Internet%20Explorer/
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'
'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-US)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)'
'Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)'
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7)'
# Edge
# from: http://www.useragentstring.com/pages/Edge/
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
# Firefox
# from: http://www.useragentstring.com/pages/Firefox/
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0'
'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0'
'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0'
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0'
'Mozilla/5.0 (X11; OpenBSD amd64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0'
# Chrome
# from: http://www.useragentstring.com/pages/Chrome/
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'
'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'
# Safari
# from: http://www.useragentstring.com/pages/Safari/
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'
]
class Nick
constructor: (options) ->
@_ended = no
@_nextStep = null
@_stepIsRunning = no
@_endCallback = null
casperOptions =
verbose: no
colorizerType: 'Dummy'
exitOnError: yes
silentErrors: no
retryTimeout: 25
pageSettings:
localToRemoteUrlAccessEnabled: yes
webSecurityEnabled: no
loadPlugins: no
logLevel: 'debug'
viewportSize:
width: 1280
height: 1024
# build blacklist array by merging "blacklist" and "blocked" options + check types
blacklist = []
if options?.blacklist?
if Array.isArray options.blacklist
for black in options.blacklist
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blocked option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blocked option must be an array of strings or regexes'
if options?.blocked?
if Array.isArray options.blocked
for black in options.blocked
if (typeof(black) isnt 'string') and (not (black instanceof RegExp))
throw new Error 'blacklist option must be an array of strings or regexes'
if typeof(black) is 'string'
black = black.toLowerCase()
blacklist.push black
else
throw new Error 'blacklist option must be an array of strings or regexes'
# build whitelist array by merging "whitelist" and "allowed" options + check types
whitelist = []
if options?.whitelist?
if Array.isArray options.whitelist
for white in options.whitelist
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'whitelist option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'whitelist option must be an array of strings or regexes'
if options?.allowed?
if Array.isArray options.allowed
for white in options.allowed
if (typeof(white) isnt 'string') and (not (white instanceof RegExp))
throw new Error 'allowed option must be an array of strings or regexes'
if typeof(white) is 'string'
white = white.toLowerCase()
whitelist.push white
else
throw new Error 'allowed option must be an array of strings or regexes'
# set up the blacklisting and whitelisting from both arrays
onResourceRequested = null
if whitelist.length or blacklist.length
onResourceRequested = (request, net) =>
if whitelist.length
found = no
for white in whitelist
if typeof(white) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(white) is 0) or (url.indexOf("https://#{white}") is 0) or (url.indexOf("http://#{white}") is 0)
found = yes
break
else if white.test(request.url)
found = yes
break
if not found
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (not found in whitelist): #{request.url}"
return net.abort()
for black in blacklist
if typeof(black) is 'string'
url = request.url.toLowerCase()
if (url.indexOf(black) is 0) or (url.indexOf("https://#{black}") is 0) or (url.indexOf("http://#{black}") is 0)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by \"#{black}\"): #{url}"
return net.abort()
else if black.test(request.url)
if (not options?.printAborts?) or options?.printAborts
console.log "> Aborted (blacklisted by #{black}): #{request.url}"
return net.abort()
if options?.userAgent?
if typeof(options.userAgent) is 'string'
casperOptions.pageSettings.userAgent = options.userAgent
else
throw new Error 'userAgent option must be a string'
else
casperOptions.pageSettings.userAgent = userAgents[Math.floor(Math.random() * userAgents.length)]
if options?.resourceTimeout?
if typeof(options.resourceTimeout) is 'number'
casperOptions.pageSettings.resourceTimeout = options.resourceTimeout
else
throw new Error 'resourceTimeout option must be a number'
else
casperOptions.pageSettings.resourceTimeout = 10000
# dont set loadImages to true by default to prevent overriding the command line option
if options?.loadImages?
if typeof(options.loadImages) is 'boolean'
casperOptions.pageSettings.loadImages = options.loadImages
else
throw new Error 'loadImages option must be a boolean'
if options?.width?
if typeof(options.width) is 'number'
casperOptions.viewportSize.width = options.width
else
throw new Error 'width option must be a number'
if options?.height?
if typeof(options.height) is 'number'
casperOptions.viewportSize.height = options.height
else
throw new Error 'height option must be a number'
@casper = require('casper').create casperOptions
if (not options?.printNavigation?) or options?.printNavigation
@casper.on 'navigation.requested', (url, type, isLocked, isMainFrame) ->
if isMainFrame
console.log "> Navigation#{if type isnt 'Other' then " (#{type})" else ''}#{if isLocked then '' else ' (not locked!)'}: #{url}"
@casper.on 'page.created', (page) ->
console.log '> New PhantomJS WebPage created'
page.onResourceTimeout = (request) ->
console.log "> Timeout of #{request.url}"
if (not options?.printPageErrors?) or options?.printPageErrors
@casper.on 'page.error', (err) ->
console.log "> Page JavaScrit error: #{err}"
if (not options?.printResourceErrors?) or options?.printResourceErrors
@casper.on 'resource.error', (err) ->
if err.errorString is 'Protocol "" is unknown' # when a resource is aborted (net.abort()), this error is generated
return
message = "> Resource error: #{if err.status? then "#{err.status} - " else ''}#{if err.statusText? then "#{err.statusText} - " else ''}#{err.errorString}"
if (typeof(err.url) is 'string') and (message.indexOf(err.url) < 0)
message += " (#{err.url})"
console.log message
if onResourceRequested?
@casper.on 'resource.requested', onResourceRequested
# better logging of stack trace
# (is it a good idea to override this on every new nick instance?
# but we need to because casperjs does it anyway and logs nothing...)
phantom.onError = (msg, trace) ->
console.log "\n#{msg}"
if trace and trace.length
for f in trace
console.log ' at ' + (f.file or f.sourceURL) + ':' + f.line + (if f.function then (' (in function ' + f.function + ')') else '')
console.log ''
phantom.exit 1
# open() error detection
@_openState =
inProgress: no
error: null
httpCode: null
httpStatus: null
url: null
last50Errors: []
# collects errors to get the most important thing: the errorString field
@casper.on 'resource.error', (error) =>
if @_openState.inProgress
@_openState.last50Errors.push error
if @_openState.last50Errors.length > 50
@_openState.last50Errors.shift()
# this event always arrives after the eventual resource.error events
# so we search back in our history of errors to find the corresponding errorString
@casper.on 'page.resource.received', (resource) =>
if @_openState.inProgress
if typeof(resource.status) isnt 'number'
@_openState.error = 'unknown error'
if typeof(resource.id) is 'number'
for err in @_openState.last50Errors
if resource.id is err.id
if typeof(err.errorString) is 'string'
@_openState.error = err.errorString
else
@_openState.httpCode = resource.status
@_openState.httpStatus = resource.statusText
@_openState.url = resource.url
# start the CasperJS wait loop
@casper.start null, null
waitLoop = () =>
@casper.wait 10
@casper.then () =>
if not @_ended
if @_nextStep?
step = @_nextStep
@_nextStep = null
@_stepIsRunning = yes
step()
waitLoop()
waitLoop()
@casper.run () =>
if @_endCallback?
@_endCallback()
_addStep: (step) =>
if @_ended
throw new Error 'this Nick instance has finished its work (end() was called) - no other actions can be done with it'
if @_nextStep? or @_stepIsRunning
throw new Error 'cannot do this while another Nick method is already running - each Nick instance can execute only one action at a time'
@_nextStep = step
return null
open: (url, options, callback) =>
if typeof(url) isnt 'string'
throw new Error 'open: url parameter must be of type string'
if typeof(options) is 'function'
callback = options
options = null
if options? and (typeof(options) isnt 'object')
throw new Error 'open: options parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'open: callback parameter must be of type function'
if url.indexOf('://') < 0
url = 'http://' + url
return @_addStep () =>
@casper.clear()
@_openState.inProgress = yes
@_openState.error = null
@_openState.httpCode = null
@_openState.httpStatus = null
@_openState.url = null
@casper.thenOpen url, options
@casper.then () =>
@_stepIsRunning = no
@_openState.inProgress = no
@_openState.last50Errors = []
# we must either have an error or an http code
# if we dont, no page.resource.received event was never received (we consider this an error except for file:// urls)
if @_openState.error? or @_openState.httpCode?
callback @_openState.error, @_openState.httpCode, @_openState.httpStatus, @_openState.url
else
if url.trim().toLowerCase().indexOf('file://') is 0
# no network requests are made for file:// urls, so we ignore the fact that we did not receive any event
callback null, null, @_openState.httpStatus, @_openState.url
else
callback 'unknown error', null, @_openState.httpStatus, @_openState.url
inject: (url, callback) =>
if typeof(url) isnt 'string'
throw new Error 'inject: url parameter must be of type string'
if typeof(callback) isnt 'function'
throw new Error 'inject: callback parameter must be of type function'
return @_addStep () =>
err = null
try
if (url.trim().toLowerCase().indexOf('http://') is 0) or (url.trim().toLowerCase().indexOf('https://') is 0)
@casper.page.includeJs url
else
@casper.page.injectJs url
catch e
err = e.toString()
@_stepIsRunning = no
callback err
evaluateAsync: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
callback = (err, res) ->
window.__evaluateAsyncFinished = yes
window.__evaluateAsyncErr = err
window.__evaluateAsyncRes = res
try
window.__evaluateAsyncFinished = no
window.__evaluateAsyncErr = null
window.__evaluateAsyncRes = null
(eval "(#{__code})")(__param, callback)
return null
catch e
return e.toString()
err = @casper.evaluate f, param, func.toString()
if err
err = "in evaluated code (initial call): #{err}"
catch e
err = "in casper context (initial call): #{e.toString()}"
if err
@_stepIsRunning = no
callback err, null
else
check = () =>
try
res = @casper.evaluate () ->
return {
finished: window.__evaluateAsyncFinished
err: (if window.__evaluateAsyncErr? then window.__evaluateAsyncErr else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
res: (if window.__evaluateAsyncRes? then window.__evaluateAsyncRes else undefined)
}
if res.finished
@_stepIsRunning = no
callback (if res.err? then res.err else null), (if res.res? then res.res else null)
else
setTimeout check, 200
catch e
@_stepIsRunning = no
callback "in casper context (callback): #{e.toString()}", null
setTimeout check, 100
evaluate: (func, param, callback) =>
if (typeof(param) is 'function') and (not callback?)
callback = param
param = null
if typeof(func) isnt 'function'
throw new Error 'evaluate: func parameter must be of type function'
if typeof(param) isnt 'object'
throw new Error 'evaluate: param parameter must be of type object'
if typeof(callback) isnt 'function'
throw new Error 'evaluate: callback parameter must be of type function'
return @_addStep () =>
err = null
try
f = (__param, __code) -> # added __ to prevent accidental casperjs parsing of object param
try
res = (eval "(#{__code})")(__param)
return {
res: (if res? then res else undefined) # PhantomJS bug: null gets converted to "", undefined is kept
err: undefined
}
catch e
return {
res: undefined
err: e.toString()
}
res = @casper.evaluate f, param, func.toString()
if res?
if res.err?
err = "in evaluated code: #{res.err}"
res = null
else
err = null
res = (if res.res? then res.res else null)
else
err = "no result returned"
res = null
catch e
err = "in casper context: #{e.toString()}"
@_stepIsRunning = no
callback err, res
end: (callback) =>
if typeof(callback) isnt 'function'
throw new Error 'end: callback parameter must be a function'
return @_addStep () =>
@_ended = yes
@_endCallback = callback
@_stepIsRunning = no
exit: (code) =>
return phantom.exit code
methods = [
[ 'waitUntilPresent', 'waitForSelector' ],
[ 'waitWhilePresent', 'waitWhileSelector' ],
[ 'waitUntilVisible', 'waitUntilVisible' ],
[ 'waitWhileVisible', 'waitWhileVisible' ],
]
injectMethod = (nickMethod, casperMethod) ->
Nick.prototype[nickMethod] = (selectors, duration, condition, callback) ->
if (typeof(condition) is 'function') and (not callback?)
callback = condition
condition = 'and'
if not Array.isArray(selectors)
selectors = [selectors]
if selectors.length is 0
throw new Error "#{nickMethod}: selectors array must contain at least one selector"
for selector in selectors
if typeof(selector) isnt 'string'
throw new Error "#{nickMethod}: selectors parameter must be a string or an array of strings"
if (typeof(duration) isnt 'number') or (duration < (selectors.length * (@casper.options.retryTimeout * 2)))
throw new Error "#{nickMethod}: duration parameter must be a number >= #{selectors.length * (@casper.options.retryTimeout * 2)} (minimum of #{@casper.options.retryTimeout * 2}ms per selector)"
if not (condition in ['and', 'or'])
throw new Error "#{nickMethod}: condition parameter must be either 'and' or 'or'"
if typeof(callback) isnt 'function'
throw new Error "#{nickMethod}: callback parameter must be of type function"
return @_addStep () =>
start = Date.now()
index = 0
if condition is 'and'
nextSelector = () =>
success = () =>
++index
if index >= selectors.length
@_stepIsRunning = no
callback null, null
else
duration -= (Date.now() - start)
if duration < (@casper.options.retryTimeout * 2)
duration = (@casper.options.retryTimeout * 2)
nextSelector()
failure = () =>
@_stepIsRunning = no
callback "waited #{Date.now() - start}ms but element \"#{selectors[index]}\" still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", selectors[index]
@casper[casperMethod] selectors[index], success, failure, duration
else
waitedForAll = no
nextSelector = () =>
success = () =>
@_stepIsRunning = no
callback null, selectors[index]
failure = () =>
if waitedForAll and ((start + duration) < Date.now())
@_stepIsRunning = no
elementsToString = selectors.slice()
for e in elementsToString
e = "\"#{e}\""
elementsToString = elementsToString.join ', '
callback "waited #{Date.now() - start}ms but element#{if (selectors.length > 0) then 's' else ''} #{elementsToString} still #{if (nickMethod.indexOf('Until') > 0) then 'not ' else ''}#{if (nickMethod.indexOf('Present') > 0) then 'present' else 'visible'}", null
else
++index
if index >= selectors.length
waitedForAll = yes
index = 0
nextSelector()
@casper[casperMethod] selectors[index], success, failure, (@casper.options.retryTimeout * 2)
nextSelector()
for method in methods
injectMethod method[0], method[1]
methods = [
{ nick: 'wait', casper: 'wait', type: 'step', params: ['duration number'] },
{ nick: 'click', casper: 'click', type: 'callback', params: ['selector string'] },
{ nick: 'clickLabel', casper: 'clickLabel', type: 'callback', params: ['selector string'], optional: ['type string'] },
{ nick: 'getCurrentUrl', casper: 'getCurrentUrl', type: 'callback' },
{ nick: 'getCurrentUrlOrNull', casper: 'getCurrentUrl', type: 'sync' },
{ nick: 'getHtml', casper: 'getHTML', type: 'callback' },
{ nick: 'getHtmlOrNull', casper: 'getHTML', type: 'sync' },
{ nick: 'getPageContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getPageContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getContent', casper: 'getPageContent', type: 'callback' },
{ nick: 'getContentOrNull', casper: 'getPageContent', type: 'sync' },
{ nick: 'getTitle', casper: 'getTitle', type: 'callback' },
{ nick: 'getTitleOrNull', casper: 'getTitle', type: 'sync' },
{ nick: 'fill', casper: 'fill', type: 'callback', params: ['selector string', 'params object'], optional: ['submit boolean'] },
{ nick: 'screenshot', casper: 'capture', type: 'callback', params: ['filename string'], optional: ['rect object', 'options object'] },
{ nick: 'selectorScreenshot', casper: 'captureSelector', type: 'callback', params: ['filename string', 'selector string'], optional: ['options object'] },
{ nick: 'sendKeys', casper: 'sendKeys', type: 'callback', params: ['selector string', 'keys string'], optional: ['options object'] },
]
injectMethod = (method) ->
Nick.prototype[method.nick] = () ->
args = Array.prototype.slice.call arguments
if method.type isnt 'sync'
if (args.length is 0) or (typeof(args[args.length - 1]) isnt 'function')
throw new Error "#{method.nick}: callback parameter must be of type function"
callback = args.pop()
if method.params?
params = method.params
if args.length < params.length
throw new Error "#{method.nick}: #{params[args.length].split(' ')[0]} parameter is missing"
if method.optional?
params = params.concat method.optional
argPos = 0
for arg in args
if argPos >= params.length
throw new Error "#{method.nick}: too many arguments"
param = params[argPos].split ' '
if (typeof(arg) isnt param[1]) or (not arg?)
throw new Error "#{method.nick}: #{param[0]} parameter must be of type #{param[1]}"
++argPos
else if args.length
throw new Error "#{method.nick}: too many arguments"
if method.type is 'sync'
try
return @casper[method.casper].apply @casper, args
catch e
return null
else
return @_addStep () =>
if method.type is 'step'
args.push () =>
@_stepIsRunning = no
callback()
@casper[method.casper].apply @casper, args
else
err = null
res = null
try
res = @casper[method.casper].apply @casper, args
catch e
err = e.toString()
@_stepIsRunning = no
callback err, res
for method in methods
injectMethod method
module.exports = Nick
|
[
{
"context": "7e1905a38e9587f9504b739ff9b77ef2d5cc0f\" : true\n \"ac6e225b8324c1fcbe814382e198495bea801dfeb56cb22b9e89066cc52ab03b0f\" : true\n \"3034e8b7d75861fc28a478b4992a8592b5478d",
"end": 2112,
"score": 0.8776329755783081,
"start": 2046,
"tag": "KEY",
"value": "ac6e225b8324c1fcbe814382e198495bea801dfeb56cb22b9e89066cc52ab03b0f"
},
{
"context": "495bea801dfeb56cb22b9e89066cc52ab03b0f\" : true\n \"3034e8b7d75861fc28a478b4992a8592b5478d4cbc7b87150d0b59573d731d870f\" : true\n \"140f1b7b7ba32f34ad6302d0ed78692cf15647",
"end": 2190,
"score": 0.9817508459091187,
"start": 2124,
"tag": "KEY",
"value": "3034e8b7d75861fc28a478b4992a8592b5478d4cbc7b87150d0b59573d731d870f"
},
{
"context": "8592b5478d4cbc7b87150d0b59573d731d870f\" : true\n \"140f1b7b7ba32f34ad6302d0ed78692cf1564760d78c082965dc3b8b5f7e27f10f\" : true\n \"833f27edcf54cc489795df1dc7d9f0cbea8253",
"end": 2268,
"score": 0.8097606301307678,
"start": 2202,
"tag": "KEY",
"value": "140f1b7b7ba32f34ad6302d0ed78692cf1564760d78c082965dc3b8b5f7e27f10f"
},
{
"context": "692cf1564760d78c082965dc3b8b5f7e27f10f\" : true\n \"833f27edcf54cc489795df1dc7d9f0cbea8253e1b84f5e82749a7a2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce",
"end": 2346,
"score": 0.8043901920318604,
"start": 2280,
"tag": "KEY",
"value": "833f27edcf54cc489795df1dc7d9f0cbea8253e1b84f5e82749a7a2a4ffc295c0f"
},
{
"context": "0cbea8253e1b84f5e82749a7a2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67",
"end": 2360,
"score": 0.5139859914779663,
"start": 2359,
"tag": "KEY",
"value": "1"
},
{
"context": "bea8253e1b84f5e82749a7a2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8",
"end": 2362,
"score": 0.5061164498329163,
"start": 2361,
"tag": "KEY",
"value": "a"
},
{
"context": "8253e1b84f5e82749a7a2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626",
"end": 2365,
"score": 0.5140925049781799,
"start": 2364,
"tag": "KEY",
"value": "5"
},
{
"context": "e1b84f5e82749a7a2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2a",
"end": 2369,
"score": 0.5142190456390381,
"start": 2368,
"tag": "KEY",
"value": "4"
},
{
"context": "2a4ffc295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n ",
"end": 2385,
"score": 0.5063256621360779,
"start": 2384,
"tag": "KEY",
"value": "a"
},
{
"context": "c295c0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042d",
"end": 2391,
"score": 0.5451935529708862,
"start": 2389,
"tag": "KEY",
"value": "27"
},
{
"context": "0f\" : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042dbe453",
"end": 2396,
"score": 0.5217926502227783,
"start": 2394,
"tag": "KEY",
"value": "ce"
},
{
"context": " : true\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042dbe45383b",
"end": 2399,
"score": 0.5219517946243286,
"start": 2397,
"tag": "KEY",
"value": "24"
},
{
"context": "rue\n \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042dbe45383b0c2ea",
"end": 2404,
"score": 0.5244340896606445,
"start": 2401,
"tag": "KEY",
"value": "879"
},
{
"context": " \"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042dbe45383b0c2eafe",
"end": 2406,
"score": 0.5220803618431091,
"start": 2405,
"tag": "KEY",
"value": "5"
},
{
"context": "0a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f\" : true\n \"3042dbe45383b0c2eafe13a73",
"end": 2411,
"score": 0.5447812080383301,
"start": 2410,
"tag": "KEY",
"value": "e"
},
{
"context": "83e4caa0ca656f92f69257213222dd7deeaf0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512",
"end": 2598,
"score": 0.6759058833122253,
"start": 2592,
"tag": "KEY",
"value": "803854"
},
{
"context": "0ca656f92f69257213222dd7deeaf0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3",
"end": 2600,
"score": 0.5987659692764282,
"start": 2599,
"tag": "KEY",
"value": "4"
},
{
"context": "a656f92f69257213222dd7deeaf0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" :",
"end": 2611,
"score": 0.6411693096160889,
"start": 2601,
"tag": "KEY",
"value": "74d668e176"
},
{
"context": "213222dd7deeaf0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n ",
"end": 2618,
"score": 0.5978606343269348,
"start": 2614,
"tag": "KEY",
"value": "9c53"
},
{
"context": "eeaf0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0",
"end": 2626,
"score": 0.5221893191337585,
"start": 2624,
"tag": "KEY",
"value": "76"
},
{
"context": "0f\" : true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0b9566e",
"end": 2632,
"score": 0.7059487700462341,
"start": 2628,
"tag": "KEY",
"value": "0404"
},
{
"context": "true\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0b9566e15f",
"end": 2635,
"score": 0.6772907972335815,
"start": 2634,
"tag": "KEY",
"value": "2"
},
{
"context": "\n \"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0b9566e15fa1f9e67b236e538",
"end": 2650,
"score": 0.6737580299377441,
"start": 2638,
"tag": "KEY",
"value": "7545e14512f3"
},
{
"context": "74d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0b9566e15fa1f9e67b236e5385cdb38d5",
"end": 2658,
"score": 0.6493180990219116,
"start": 2651,
"tag": "KEY",
"value": "9002f0f"
},
{
"context": "0fc576bd0404cf26ff7545e14512f3b9002f0f\" : true\n \"2e08f0b9566e15fa1f9e67b236e5385cdb38d57ff51d7ab3e568532867c9f8890f\" : true\n \"cb97f4b62f2e817e8db8c6193440214ad20f90",
"end": 2736,
"score": 0.9327659606933594,
"start": 2670,
"tag": "KEY",
"value": "2e08f0b9566e15fa1f9e67b236e5385cdb38d57ff51d7ab3e568532867c9f8890f"
},
{
"context": "385cdb38d57ff51d7ab3e568532867c9f8890f\" : true\n \"cb97f4b62f2e817e8db8c6193440214ad20f906571e4851db186869f0b4c0e310f\" : true\n \"a5c4a30d1eaaf752df424bf813c5a907a5cf94",
"end": 2814,
"score": 0.8131474852561951,
"start": 2748,
"tag": "KEY",
"value": "cb97f4b62f2e817e8db8c6193440214ad20f906571e4851db186869f0b4c0e310f"
},
{
"context": "b51e3ab9d6bec54064b8a0f\" : true\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\"",
"end": 3389,
"score": 0.5287156105041504,
"start": 3387,
"tag": "KEY",
"value": "25"
},
{
"context": "e3ab9d6bec54064b8a0f\" : true\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : t",
"end": 3393,
"score": 0.5234991312026978,
"start": 3390,
"tag": "KEY",
"value": "f7d"
},
{
"context": "ec54064b8a0f\" : true\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"",
"end": 3400,
"score": 0.5169941186904907,
"start": 3398,
"tag": "KEY",
"value": "f4"
},
{
"context": "b8a0f\" : true\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506",
"end": 3407,
"score": 0.5287267565727234,
"start": 3405,
"tag": "KEY",
"value": "55"
},
{
"context": ": true\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506b705926ea",
"end": 3416,
"score": 0.513397216796875,
"start": 3412,
"tag": "KEY",
"value": "d6de"
},
{
"context": "e\n \"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506b705926ea962e5904",
"end": 3424,
"score": 0.528965950012207,
"start": 3417,
"tag": "KEY",
"value": "c5822ba"
},
{
"context": "60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506b705926ea962e59046b",
"end": 3426,
"score": 0.5060182213783264,
"start": 3425,
"tag": "KEY",
"value": "2"
},
{
"context": "95e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506b705926ea962e59046bfe1720",
"end": 3432,
"score": 0.5369925498962402,
"start": 3431,
"tag": "KEY",
"value": "5"
},
{
"context": "77254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f\" : true\n \"031b506b705926ea962e59046bfe1720dcf72c",
"end": 3438,
"score": 0.5392460227012634,
"start": 3435,
"tag": "KEY",
"value": "b0f"
},
{
"context": "f0e2d6cabdac38f490417b313050249be9dc0f\" : true\n \"2415e1c77b0815661452ea683e366c6d9dfd2008a7dbc907004c3a33e56cf6190f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6",
"end": 3984,
"score": 0.9156448245048523,
"start": 3918,
"tag": "KEY",
"value": "2415e1c77b0815661452ea683e366c6d9dfd2008a7dbc907004c3a33e56cf6190f"
},
{
"context": "6c6d9dfd2008a7dbc907004c3a33e56cf6190f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f\" : true\n \"70c4026afec66312456b6820492b7936bff42b",
"end": 4062,
"score": 0.9847468137741089,
"start": 3996,
"tag": "KEY",
"value": "44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f"
},
{
"context": "f4e95d0d6ec1dd8722fd7cfc7761698ec780f\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a03572946",
"end": 4076,
"score": 0.5612422823905945,
"start": 4075,
"tag": "KEY",
"value": "0"
},
{
"context": "e95d0d6ec1dd8722fd7cfc7761698ec780f\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a0357294627",
"end": 4078,
"score": 0.7044493556022644,
"start": 4077,
"tag": "KEY",
"value": "4"
},
{
"context": "80f\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920",
"end": 4110,
"score": 0.6140021681785583,
"start": 4109,
"tag": "KEY",
"value": "4"
},
{
"context": "\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a50",
"end": 4113,
"score": 0.7478059530258179,
"start": 4112,
"tag": "KEY",
"value": "5"
},
{
"context": "rue\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a5050de2",
"end": 4118,
"score": 0.5380542278289795,
"start": 4117,
"tag": "KEY",
"value": "a"
},
{
"context": "e\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a5050de28faad",
"end": 4123,
"score": 0.6298540234565735,
"start": 4119,
"tag": "KEY",
"value": "3572"
},
{
"context": "66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a5050de28faad24b5fe3336f658b96",
"end": 4140,
"score": 0.6339927911758423,
"start": 4135,
"tag": "KEY",
"value": "4190f"
},
{
"context": "5e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"062e6799f211177023bc310fd6e4",
"end": 4286,
"score": 0.5575292706489563,
"start": 4284,
"tag": "KEY",
"value": "69"
},
{
"context": "2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"062e6799f211177023bc310fd6e4e28a8",
"end": 4291,
"score": 0.6433461904525757,
"start": 4290,
"tag": "KEY",
"value": "8"
},
{
"context": "85b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"062e6799f211177023bc310fd6e4e28a8e2e18",
"end": 4296,
"score": 0.681189239025116,
"start": 4292,
"tag": "KEY",
"value": "ae0f"
},
{
"context": "4fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"062e6799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f\" : true\n \"db9a0afaab297048be0d44ffd6d89a3eb6a003",
"end": 4374,
"score": 0.9793750643730164,
"start": 4313,
"tag": "KEY",
"value": "799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f"
},
{
"context": "9a3eb6a003256426d7fd87a60ab59880f8160f\" : true\n \"58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f\" : true\n \"062e6799f211177023bc310fd6e4e28a8e2e18",
"end": 4530,
"score": 0.960354208946228,
"start": 4464,
"tag": "KEY",
"value": "58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f"
},
{
"context": "1a0a46019e1c54612ea0867086dbd405589a0f\" : true\n \"062e6799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f\" : true\n \"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7",
"end": 4608,
"score": 0.9780327677726746,
"start": 4542,
"tag": "KEY",
"value": "062e6799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f"
},
{
"context": "e28a8e2e18f972d9b037d24434a203aca7240f\" : true\n \"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6",
"end": 4686,
"score": 0.9955722689628601,
"start": 4620,
"tag": "KEY",
"value": "10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f"
},
{
"context": "1a7a44fbb7fcf25565286cb2d969ad9b89ae0f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698e",
"end": 4709,
"score": 0.6716283559799194,
"start": 4698,
"tag": "KEY",
"value": "44847743878"
},
{
"context": "25565286cb2d969ad9b89ae0f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f\"",
"end": 4715,
"score": 0.7427798509597778,
"start": 4711,
"tag": "KEY",
"value": "56f5"
},
{
"context": "86cb2d969ad9b89ae0f\" : true\n \"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f\" : true\n \"58bf751ddd23065a820449701f8a1a0a46019e",
"end": 4764,
"score": 0.7192476987838745,
"start": 4717,
"tag": "KEY",
"value": "74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f"
},
{
"context": "8f4e95d0d6ec1dd8722fd7cfc7761698ec780f\" : true\n \"58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f\" : true\n \"70c4026afec66312456b6820492b7936bff42b",
"end": 4842,
"score": 0.9762168526649475,
"start": 4776,
"tag": "KEY",
"value": "58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f"
},
{
"context": "1a0a46019e1c54612ea0867086dbd405589a0f\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" :",
"end": 4873,
"score": 0.8603923916816711,
"start": 4854,
"tag": "KEY",
"value": "70c4026afec66312456"
},
{
"context": "867086dbd405589a0f\" : true\n \"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a5050de28faad24b5fe3336f658b96",
"end": 4920,
"score": 0.8901509642601013,
"start": 4874,
"tag": "KEY",
"value": "6820492b7936bff42b58ca7a035729462700677ef4190f"
},
{
"context": "7936bff42b58ca7a035729462700677ef4190f\" : true\n \"7591a920a5050de28faad24b5fe3336f658b964e0e64464b70878",
"end": 4935,
"score": 0.7229655385017395,
"start": 4932,
"tag": "KEY",
"value": "759"
},
{
"context": "ormat got some\n# links into a public chain. (Sorry Fred!) Skip reverse signature checking for\n# this fixe",
"end": 5208,
"score": 0.9845801591873169,
"start": 5204,
"tag": "NAME",
"value": "Fred"
},
{
"context": "ed set of links.\nknown_buggy_reverse_sigs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528",
"end": 5308,
"score": 0.5605900883674622,
"start": 5307,
"tag": "KEY",
"value": "a"
},
{
"context": ".\nknown_buggy_reverse_sigs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\":",
"end": 5324,
"score": 0.5061444640159607,
"start": 5322,
"tag": "KEY",
"value": "ce"
},
{
"context": "y_reverse_sigs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5",
"end": 5336,
"score": 0.5141763687133789,
"start": 5334,
"tag": "KEY",
"value": "c9"
},
{
"context": "everse_sigs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5c7e",
"end": 5339,
"score": 0.5063533782958984,
"start": 5337,
"tag": "KEY",
"value": "b6"
},
{
"context": "_sigs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5c7e7d3cf8",
"end": 5345,
"score": 0.5375922322273254,
"start": 5343,
"tag": "KEY",
"value": "7a"
},
{
"context": "gs = {\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5c7e7d3cf8370b",
"end": 5349,
"score": 0.5323455929756165,
"start": 5346,
"tag": "KEY",
"value": "75e"
},
{
"context": "{\n \"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5c7e7d3cf8370bed8ab55c0d8",
"end": 5360,
"score": 0.5434853434562683,
"start": 5351,
"tag": "KEY",
"value": "c4b3528d7"
},
{
"context": "30f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f\": true\n \"eb5c7e7d3cf8370bed8ab55c0d8833ce9d74fd2",
"end": 5372,
"score": 0.5526702404022217,
"start": 5363,
"tag": "KEY",
"value": "1a21f7a0f"
},
{
"context": "2432a85bc05922bbe727016f3fb660863a1890f\": true\n \"48267f0e3484b2f97859829503e20c2f598529b42c1d840a8fc1eceda71458400f\": true\n};\n\n# Some users (6) managed to reuse elde",
"end": 5603,
"score": 0.950758695602417,
"start": 5537,
"tag": "KEY",
"value": "48267f0e3484b2f97859829503e20c2f598529b42c1d840a8fc1eceda71458400f"
},
{
"context": "(() ->)\n log \"+ libkeybase: replay(username: #{username}, uid: #{uid}, eldest: #{eldest_kid})\"\n esc = ",
"end": 19347,
"score": 0.8371202945709229,
"start": 19339,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tly. Use SigChain.replay().\n constructor : ({uid, username, eldest_kid, parsed_keys}) ->\n @_uid = uid\n ",
"end": 20570,
"score": 0.8705105781555176,
"start": 20562,
"tag": "USERNAME",
"value": "username"
},
{
"context": " parsed_keys}) ->\n @_uid = uid\n @_username = username\n @_eldest_kid = eldest_kid\n @_parsed_keys =",
"end": 20642,
"score": 0.9949197769165039,
"start": 20634,
"tag": "USERNAME",
"value": "username"
},
{
"context": "id}\")\n else if link.username.toLowerCase() isnt @_username.toLowerCase()\n err = new E.WrongUsernameErro",
"end": 24983,
"score": 0.9539214968681335,
"start": 24973,
"tag": "USERNAME",
"value": "@_username"
},
{
"context": " username,\n expected: #{link.username} got: #{@_username}\")\n else if link.seqno isnt @_next_seqno\n ",
"end": 25139,
"score": 0.9432547688484192,
"start": 25127,
"tag": "USERNAME",
"value": "#{@_username"
},
{
"context": "t self-signing\"), esc defer()\n expected_email = @_username + \"@keybase.io\"\n for identity in userids\n ",
"end": 31107,
"score": 0.9844793081283569,
"start": 31097,
"tag": "USERNAME",
"value": "@_username"
}
] | node_modules/libkeybase/src/sigchain/sigchain.iced | AngelKey/Angelkey.nodeclient | 151 | {bufeq_secure,athrow, a_json_parse} = require('iced-utils').util
{make_esc} = require 'iced-error'
kbpgp = require('kbpgp')
proofs = require('keybase-proofs')
ie = require('iced-error')
{trim} = require('pgp-utils').util
UID_LEN = 32
exports.SIG_ID_SUFFIX = SIG_ID_SUFFIX = "0f"
strip_final_newline = (buf) ->
s = buf.toString('utf8')
if s[-1...] is "\n" then new Buffer s[0...-1], "utf8"
else buf
# On 15 Sep 2015, a day that will live in infamy, some users made bad
# sigchain additions due to a code error that was stripping out
# whitespace from json payloads, writing those payloads to the DB, and then
# offering those payloads back out for subsequent signatures. We address that
# issue here by subtracting that dropped newline out right before we hash.
# We should potentially have a whitelist here for sigids that are affected:
bad_whitespace_sig_ids = {
"595a73fc649c2c8ccc1aa79384e0b3e7ab3049d8df838f75ef0edbcb5bbc42990f" : true
"e256078702afd7a15a24681259935b48342a49840ab6a90291b300961669790f0f" : true
"30831001edee5e01c3b5f5850043f9ef7749a1ed8624dc703ae0922e1d0f16dd0f" : true
"88e6c581dbccbf390559bcb30ca21548ba0ec4861ec2d666217bd4ed4a4a8c3f0f" : true
"4db0fe3973b3a666c7830fcb39d93282f8bc414eca1d535033a5cc625eabda0c0f" : true
"9ba23a9a1796fb22b3c938f1edf5aba4ca5be7959d9151895eb6aa7a8d8ade420f" : true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f" : true
"a32692af33e559e00a40aa3bb4004744d2c1083112468ed1c8040eaacd15c6eb0f" : true
"3e61901f50508aba72f12740fda2be488571afc51d718d845e339e5d1d1b531d0f" : true
"de43758b653b3383aca640a96c7890458eadd35242e8f8531f29b606890a14ea0f" : true
"b9ee3b46c97d48742a73e35494d3a373602460609e3c6c54a553fc4d83b659e40f" : true
"0ff29c1d036c3f4841f3f485e28d77351abb3eeeb52d2f8d802fd15e383d9a5f0f" : true
"eb1a13c6b6e42bb7470e222b51d36144a25ffc4fbc0b32e9a1ec11f059001bc80f" : true
"9c189d6d644bad9596f78519d870a685624f813afc1d0e49155073d3b0521f970f" : true
"aea7c8f7726871714e777ac730e77e1905a38e9587f9504b739ff9b77ef2d5cc0f" : true
"ac6e225b8324c1fcbe814382e198495bea801dfeb56cb22b9e89066cc52ab03b0f" : true
"3034e8b7d75861fc28a478b4992a8592b5478d4cbc7b87150d0b59573d731d870f" : true
"140f1b7b7ba32f34ad6302d0ed78692cf1564760d78c082965dc3b8b5f7e27f10f" : true
"833f27edcf54cc489795df1dc7d9f0cbea8253e1b84f5e82749a7a2a4ffc295c0f" : true
"110a64513b4188eca2af6406a8a6dbf278dfce324b8879b5cb67e8626ff2af180f" : true
"3042dbe45383b0c2eafe13a73da35c4e721be026d7908dfcef6eb121d95b75b10f" : true
"50ba350ddc388f7c6fdba032a7d283e4caa0ca656f92f69257213222dd7deeaf0f" : true
"803854b4074d668e1761ee9c533c0fc576bd0404cf26ff7545e14512f3b9002f0f" : true
"2e08f0b9566e15fa1f9e67b236e5385cdb38d57ff51d7ab3e568532867c9f8890f" : true
"cb97f4b62f2e817e8db8c6193440214ad20f906571e4851db186869f0b4c0e310f" : true
"a5c4a30d1eaaf752df424bf813c5a907a5cf94fd371e280d39e0a3d078310fba0f" : true
"c7d26afbc1957ecca890d8d9001a9cc4863490161720ad76a2aedeb8c2d50df70f" : true
"b385c0c76d790aba156ff68fd571171fc7cb85f75e7fc9d1561d7960d8875acb0f" : true
"47d349b8bb3c8457449390ca2ed5e489a70ad511ab3edb4c7f0af27eed8c65d30f" : true
"2785b24acd6869e1e7d38a91793af549f3c35cd0729127d200b66f8c0ffba59b0f" : true
"503df567f98cf5910ba44cb95e157e656afe95d159a15c7df4e88ac6016c948f0f" : true
"2892863758cdaf9796fb36e2466093762efda94e74eb51e3ab9d6bec54064b8a0f" : true
"e1d60584995e677254f7d913b3f40060b5500241d6de0c5822ba1282acc5e08b0f" : true
"031b506b705926ea962e59046bfe1720dcf72c85310502020e2ae836b294fcde0f" : true
"1454fec21489f17a6d78927af1c9dca4209360c6ef6bfa569d8b62d32e668ea30f" : true
"ba68052597a3782f64079d7d9ec821ea9785c0868e44b597a04c9cd8bf634c1e0f" : true
"db8d59151b2f78c82c095c9545f1e4d39947a0c0bcc01b907e0ace14517d39970f" : true
"e088beccfee26c5df39239023d1e4e0cbcd63fd50d0bdc4bf2c2ba25ef1a8fe40f" : true
"8182f385c347fe57d3c46fe40e8df0e2d6cabdac38f490417b313050249be9dc0f" : true
"2415e1c77b0815661452ea683e366c6d9dfd2008a7dbc907004c3a33e56cf6190f" : true
"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f" : true
"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f" : true
"7591a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f" : true
"062e6799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
"58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f" : true
"062e6799f211177023bc310fd6e4e28a8e2e18f972d9b037d24434a203aca7240f" : true
"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d969ad9b89ae0f" : true
"44847743878bd56f5cd74980475e8f4e95d0d6ec1dd8722fd7cfc7761698ec780f" : true
"58bf751ddd23065a820449701f8a1a0a46019e1c54612ea0867086dbd405589a0f" : true
"70c4026afec66312456b6820492b7936bff42b58ca7a035729462700677ef4190f" : true
"7591a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
}
# We had an incident where a Go client using an old reverse-sig format got some
# links into a public chain. (Sorry Fred!) Skip reverse signature checking for
# this fixed set of links.
known_buggy_reverse_sigs = {
"2a0da9730f049133ce728ba30de8c91b6658b7a375e82c4b3528d7ddb1a21f7a0f": true
"eb5c7e7d3cf8370bed8ab55c0d8833ce9d74fd2c614cf2cd2d4c30feca4518fa0f": true
"0f175ef0d3b57a9991db5deb30f2432a85bc05922bbe727016f3fb660863a1890f": true
"48267f0e3484b2f97859829503e20c2f598529b42c1d840a8fc1eceda71458400f": true
};
# Some users (6) managed to reuse eldest keys after a sigchain reset, without
# using the "eldest" link type, before the server prohibited this. To clients,
# that means their chains don't appear to reset. We hardcode these cases.
hardcoded_resets = {
"11111487aa193b9fafc92851176803af8ed005983cad1eaf5d6a49a459b8fffe0f": true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f": true
"32eab86aa31796db3200f42f2553d330b8a68931544bbb98452a80ad2b0003d30f": true
"5ed7a3356fd0f759a4498fc6fed1dca7f62611eb14f782a2a9cda1b836c58db50f": true
"d5fe2c5e31958fe45a7f42b325375d5bd8916ef757f736a6faaa66a6b18bec780f": true
"1e116e81bc08b915d9df93dc35c202a75ead36c479327cdf49a15f3768ac58f80f": true
}
# For testing that caches are working properly. (Use a wrapper object instead
# of a simple counter because main.iced copies things.)
exports.debug =
unbox_count: 0
exports.ParsedKeys = ParsedKeys = class ParsedKeys
@parse : ({key_bundles}, cb) ->
# We only take key bundles from the server, either hex NaCl public keys, or
# ascii-armored PGP public key strings. We compute the KIDs and
# fingerprints ourselves, because we don't trust the server to do it for
# us.
esc = make_esc cb, "ParsedKeys.parse"
default_eldest_kid_for_testing = null
opts = { time_travel : true }
parsed_keys = new ParsedKeys
for bundle in key_bundles
await kbpgp.ukm.import_armored_public {armored: bundle, opts}, esc defer key_manager
await parsed_keys._add_key {key_manager}, esc defer()
default_eldest_kid_for_testing or= key_manager.get_ekid().toString "hex"
cb null, parsed_keys, default_eldest_kid_for_testing
constructor : ->
# Callers should use this class to get KeyManagers for KIDs they already
# have, but callers MUST NOT iterate over the set of KIDs here as though it
# were the valid set for a given user. The set of KIDs is *untrusted*
# because it comes from the server. We keep the map private to prevent that
# mistake.
@_kids_to_merged_pgp_key_managers = {}
@_kids_to_pgp_key_managers_by_hash = {}
@_kids_to_nacl_keys = {}
_add_key : ({key_manager}, cb) ->
esc = make_esc "ParsedKeys._add_key"
kid = key_manager.get_ekid()
kid_str = kid.toString "hex"
if key_manager.pgp?
if (existing = @_kids_to_merged_pgp_key_managers[kid_str])?
existing.merge_everything key_manager
else
@_kids_to_merged_pgp_key_managers[kid_str] = key_manager
await key_manager.pgp_full_hash {}, esc defer hash
(@_kids_to_pgp_key_managers_by_hash[kid_str] or= {})[hash] = key_manager
else
@_kids_to_nacl_keys[kid_str] = key_manager
cb()
# We may have multiple versions of a PGP key with the same KID/fingerprint.
# They could have different subkeys and userids, and an old subkey could have
# been used to sign an old link. We historically handled handle these cases
# by merging all versions of a PGP key together, but since it's valid to
# upload a new version of a PGP key specifically to revoke a subkey and
# prevent it from signing new chainlinks, we realized that it's necessary to
# track which version of the key is active. When a PGP key is signed in or
# updated, the hash of the ASCII-armored public key is now specified in the
# sigchain.
#
# get_merged_pgp_key_manager must only be used when a hash hasn't been
# specified (in, say, an old sigchain). When an eldest, sibkey, or pgp_update
# link specifies a hash, get_pgp_key_manager_with_hash must be used for all
# following links signed by that KID.
get_merged_pgp_key_manager : (kid) ->
@_kids_to_merged_pgp_key_managers[kid]
get_pgp_key_manager_with_hash : (kid, hash) ->
@_kids_to_pgp_key_managers_by_hash[kid]?[hash]
get_nacl_key_manager : (kid) ->
@_kids_to_nacl_keys[kid]
# KeyState tracks hashes that have been specified for PGP keys. As long as it's
# kept up to date as the sigchain is replayed, it can safely be used to get the
# correct KeyManager for a given KID.
class KeyState
constructor : ({@parsed_keys}) ->
@_kid_to_hash = {}
set_key_hash : ({kid, hash}, cb) ->
if not @parsed_keys.get_pgp_key_manager_with_hash(kid, hash)?
cb new E.NoKeyWithThisHashError "No PGP key with kid #{kid} and hash #{hash} exists"
return
@_kid_to_hash[kid] = hash
cb()
get_key_manager : (kid) ->
if (key = @parsed_keys.get_nacl_key_manager kid)?
return key
if (hash = @_kid_to_hash[kid])?
return @parsed_keys.get_pgp_key_manager_with_hash kid, hash
return @parsed_keys.get_merged_pgp_key_manager kid
class ChainLink
@parse : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink.parse"
# Unbox the signed payload. PGP key expiration is checked automatically
# during unbox, using the ctime of the chainlink.
await @_unbox_payload {sig_blob, key_state, sig_cache}, esc defer payload, sig_id, payload_hash
# Check internal details of the payload, like uid length.
await check_link_payload_format {payload}, esc defer()
# Make sure the KID from the server matches the payload, and that any
# payload PGP fingerprint also matches the KID.
await @_check_payload_against_server_kid {sig_blob, payload, key_state}, esc defer()
# Check any reverse signatures. For links where we skip this step, we will
# ignore their contents later.
if not known_buggy_reverse_sigs[sig_id]
await @_check_reverse_signatures {payload, key_state}, esc defer()
# The constructor takes care of all the payload parsing that isn't failable.
cb null, new ChainLink {kid: sig_blob.kid, sig_id, payload, payload_hash}
@_unbox_payload : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink._unbox_payload"
# Get the signing KID directly from the server blob. We'll confirm later
# that this is the same as the KID listed in the payload.
kid = sig_blob.kid
# Get the key_manager and sig_eng we need from the ParsedKeys object.
key_manager = key_state.get_key_manager kid
if not key_manager?
await athrow (new E.NonexistentKidError "link signed by nonexistent kid #{kid}"), esc defer()
sig_eng = key_manager.make_sig_eng()
# We need the signing ctime to verify the signature, and that's actually in
# the signed payload. So we fully parse the payload *before* verifying, and
# do the actual (maybe cached) verification at the end.
await sig_eng.get_body_and_unverified_payload(
{armored: sig_blob.sig}, esc defer sig_body, unverified_buffer)
sig_id = kbpgp.hash.SHA256(sig_body).toString("hex") + SIG_ID_SUFFIX
payload_json = unverified_buffer.toString('utf8')
await a_json_parse payload_json, esc defer payload
ctime_seconds = payload.ctime
# Now that we have the ctime, get the verified payload.
if sig_cache?
await sig_cache.get {sig_id}, esc defer verified_buffer
if not verified_buffer?
exports.debug.unbox_count++
await key_manager.make_sig_eng().unbox(
sig_blob.sig,
defer(err, verified_buffer),
{now: ctime_seconds})
if err?
await athrow (new E.VerifyFailedError err.message), esc defer()
if sig_cache?
await sig_cache.put {sig_id, payload_buffer: verified_buffer}, esc defer()
# Check that what we verified matches the unverified payload we used above.
# Ideally it should be impossible for there to be a difference, but this
# protects us from bugs/attacks that might exploit multiple payloads,
# particularly in PGP.
await check_buffers_equal verified_buffer, unverified_buffer, esc defer()
# Success!
# See comment above about bad whitespace sigs from 15 Sep 2015
hash_input = if bad_whitespace_sig_ids[sig_id] then strip_final_newline verified_buffer
else verified_buffer
payload_hash = kbpgp.hash.SHA256(hash_input).toString("hex")
cb null, payload, sig_id, payload_hash
@_check_payload_against_server_kid : ({sig_blob, payload, key_state}, cb) ->
# Here's where we check the data we relied on in @_unbox_payload().
signing_kid = sig_blob.kid
signing_fingerprint = key_state.get_key_manager(signing_kid).get_pgp_fingerprint()?.toString('hex')
payload_kid = payload.body.key.kid
payload_fingerprint = payload.body.key.fingerprint
err = null
if payload_kid? and payload_kid isnt signing_kid
err = new E.KidMismatchError "signing kid (#{signing_kid}) and payload kid (#{payload_kid}) mismatch"
else if payload_fingerprint? and payload_fingerprint isnt signing_fingerprint
err = new E.FingerprintMismatchError "signing fingerprint (#{signing_fingerprint}) and payload fingerprint (#{payload_fingerprint}) mismatch"
cb err
@_check_reverse_signatures : ({payload, key_state}, cb) ->
esc = make_esc cb, "ChainLink._check_reverse_signatures"
if payload.body.sibkey?
kid = payload.body.sibkey.kid
full_hash = payload.body.sibkey.full_hash
sibkey_key_manager = if full_hash?
# key_state hasn't been updated with the new sibkey's full hash yet
key_state.parsed_keys.get_pgp_key_manager_with_hash kid, full_hash
else
key_state.get_key_manager kid
if not sibkey_key_manager?
await athrow (new E.NonexistentKidError "link reverse-signed by nonexistent kid #{kid}"), esc defer()
sibkey_proof = new proofs.Sibkey {}
await sibkey_proof.reverse_sig_check {json: payload, subkm: sibkey_key_manager}, defer err
if err?
await athrow (new E.ReverseSigVerifyFailedError err.message), esc defer()
if payload.body.subkey?
kid = payload.body.subkey.kid
subkey_key_manager = key_state.get_key_manager kid
if not subkey_key_manager?
await athrow (new E.NonexistentKidError "link delegates nonexistent subkey #{kid}"), esc defer()
cb null
constructor : ({@kid, @sig_id, @payload, @payload_hash}) ->
@uid = @payload.body.key.uid
@username = @payload.body.key.username
@seqno = @payload.seqno
@prev = @payload.prev
# @fingerprint is PGP-only.
@fingerprint = @payload.body.key.fingerprint
# Not all links have the "eldest_kid" field, but if they don't, then their
# signing KID is implicitly the eldest.
@eldest_kid = @payload.body.key.eldest_kid or @kid
@ctime_seconds = @payload.ctime
@etime_seconds = @ctime_seconds + @payload.expire_in
@type = @payload.body.type
# Only expected to be set in eldest links
@signing_key_hash = @payload.body.key.full_hash
@sibkey_delegation = @payload.body.sibkey?.kid
@sibkey_hash = @payload.body.sibkey?.full_hash
@subkey_delegation = @payload.body.subkey?.kid
@pgp_update_kid = @payload.body.pgp_update?.kid
@pgp_update_hash = @payload.body.pgp_update?.full_hash
@key_revocations = []
if @payload.body.revoke?.kids?
@key_revocations = @payload.body.revoke.kids
if @payload.body.revoke?.kid?
@key_revocations.push(@payload.body.revoke.kid)
@sig_revocations = []
if @payload.body.revoke?.sig_ids?
@sig_revocations = @payload.body.revoke.sig_ids
if @payload.body.revoke?.sig_id?
@sig_revocations.push(@payload.body.revoke.sig_id)
# Exported for testing.
exports.check_link_payload_format = check_link_payload_format = ({payload}, cb) ->
esc = make_esc cb, "check_link_payload_format"
uid = payload.body.key.uid
if uid.length != UID_LEN
await athrow (new E.BadLinkFormatError "UID wrong length: #{uid.length}"), esc defer()
cb()
# Also exported for testing. This check will never fail under normal
# circumstances, so we need a test to explicitly make it fail.
exports.check_buffers_equal = check_buffers_equal = (verified_buffer, unverified_buffer, cb) ->
err = null
if not bufeq_secure(verified_buffer,unverified_buffer)
msg = """Payload mismatch!
Verified:
#{verified_buffer.toString('hex')}
Unverified:
#{unverified_buffer.toString('hex')}"""
err = new E.VerifyFailedError msg
cb err
exports.SigChain = class SigChain
# The replay() method is the main interface for all callers. It checks all of
# the user's signatures and returns a SigChain object representing their
# current state.
#
# @param {[string]} sig_blobs The parsed JSON signatures list returned from
# the server's sig/get.json endpoint.
# @param {ParsedKeys} parsed_keys The unverified collection of all the user's
# public keys. This is usually obtained from the all_bundles list given
# by user/lookup.json, passed to ParsedKeys.parse(). NaCl public key
# material is contained entirely within the KID, so technically all this
# extra data is only needed for PGP, but we treat both types of keys the
# same way for simplicity.
# @param {object} sig_cache An object with two methods: get({sig_id}, cb) and
# put({sig_id, payload_buffer}, cb), which caches the payloads of
# previously verified signatures. This parameter can be null, in which
# case all signatures will be checked.
# @param {string} uid Used only to check that the sigchain belongs to the
# right user.
# @param {string} username As with uid, used for confirming ownership.
# @param {string} eldest_kid The full (i.e. with-prefix) KID of the user's
# current eldest key. This is used to determine the latest subchain.
# @param {object} log An object with logging methods (debug, info, warn,
# error). May be null.
@replay : ({sig_blobs, parsed_keys, sig_cache, uid, username, eldest_kid, log}, cb) ->
log = log or (() ->)
log "+ libkeybase: replay(username: #{username}, uid: #{uid}, eldest: #{eldest_kid})"
esc = make_esc cb, "SigChain.replay"
# Forgetting the eldest KID would silently give you an empty sigchain. Prevent this.
if not eldest_kid?
await athrow (new Error "eldest_kid parameter is required"), esc defer()
# Initialize the SigChain.
sigchain = new SigChain {uid, username, eldest_kid, parsed_keys}
# Build the chain link by link, checking consistency all the way through.
for sig_blob in sig_blobs
log "| libkeybase: replaying signature #{sig_blob.seqno}: #{sig_blob.sig_id}"
await sigchain._add_new_link {sig_blob, sig_cache, log}, esc defer()
# If the eldest kid of the current subchain doesn't match the eldest kid
# we're looking for, that means we're on a new zero-length subchain.
if eldest_kid isnt sigchain._current_subchain_eldest
sigchain._reset_subchain(eldest_kid)
# After the chain is finished, make sure we've proven ownership of the
# eldest key in some way.
await sigchain._enforce_eldest_key_ownership {}, esc defer()
log "- libkeybase: replay finished"
cb null, sigchain
# NOTE: Don't call the constructor directly. Use SigChain.replay().
constructor : ({uid, username, eldest_kid, parsed_keys}) ->
@_uid = uid
@_username = username
@_eldest_kid = eldest_kid
@_parsed_keys = parsed_keys
@_next_seqno = 1
@_next_payload_hash = null
@_reset_subchain(null)
_reset_subchain : (current_subchain_eldest) ->
@_current_subchain = []
@_current_subchain_eldest = current_subchain_eldest
@_key_state = new KeyState {parsed_keys: @_parsed_keys}
@_unrevoked_links = {}
@_valid_sibkeys = {}
@_valid_sibkeys[current_subchain_eldest] = true
@_sibkey_order = [current_subchain_eldest]
@_valid_subkeys = {}
@_subkey_order = []
@_kid_to_etime_seconds = {}
@_update_kid_pgp_etime { kid: current_subchain_eldest }
# Return the list of links in the current subchain which have not been
# revoked.
get_links : () ->
return (link for link in @_current_subchain when link.sig_id of @_unrevoked_links)
# Return the list of sibkey KIDs which aren't revoked or expired.
get_sibkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_sibkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_sibkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
# Return the list of subkey KIDs which aren't revoked or expired.
get_subkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_subkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_subkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
_add_new_link : ({sig_blob, sig_cache, log}, cb) ->
esc = make_esc cb, "SigChain._add_new_link"
# This constructor checks that the link is internally consistent: its
# signature is valid and belongs to the key it claims, and the same for any
# reverse sigs.
await ChainLink.parse {sig_blob, key_state: @_key_state, sig_cache}, esc defer link
log "| libkeybase: chain link parsed, type '#{link.payload.body.type}'"
# Make sure the link belongs in this chain (right username and uid) and at
# this particular point in the chain (right seqno and prev hash).
await @_check_link_belongs_here {link}, esc defer()
# Now see if we've hit a sigchain reset. That can happen for one of two
# reasons:
# 1) The eldest kid reported by this link (either explicitly or
# implicitly; see ChainLink.eldest_kid) is different from the one that
# came before it.
# 2) This link is of the "eldest" type.
# We *don't* short-circuit here though. Verifying past subchains just like
# we verify the current one actually simplifies PGP full hash handling.
# (Otherwise we'd have to figure out how to maintain the KeyState, or else
# we wouldn't even be able to verify link signatures [correctly, without
# resorting to key merging].)
if (link.eldest_kid isnt @_current_subchain_eldest or
link.type is "eldest" or
hardcoded_resets[link.sig_id])
log "| libkeybase: starting new subchain"
@_reset_subchain(link.eldest_kid)
# Links with known bad reverse sigs still have to have valid payload hashes
# and seqnos, but their contents are ignored, and their signing keys might
# not be valid sibkeys (because the delegating links of those sibkeys might
# also have been bad). Short-circuit here for these links, after checking
# the link position but before checking the validity of the signing key.
if known_buggy_reverse_sigs[link.sig_id]
cb null
return
# Finally, make sure that the key that signed this link was actually valid
# at the time the link was signed.
await @_check_key_is_valid {link}, esc defer()
log "| libkeybase: signing key is valid (#{link.kid})"
# This link is valid and part of the current subchain. Update all the
# relevant metadata.
@_current_subchain.push(link)
@_unrevoked_links[link.sig_id] = link
await @_delegate_keys {link, log}, esc defer()
await @_revoke_keys_and_sigs {link, log}, esc defer()
cb null
_check_link_belongs_here : ({link}, cb) ->
err = null
if link.uid isnt @_uid
err = new E.WrongUidError(
"Link doesn't refer to the right uid,
expected: #{link.uid} got: #{@_uid}")
else if link.username.toLowerCase() isnt @_username.toLowerCase()
err = new E.WrongUsernameError(
"Link doesn't refer to the right username,
expected: #{link.username} got: #{@_username}")
else if link.seqno isnt @_next_seqno
err = new E.WrongSeqnoError(
"Link sequence number is wrong, expected:
#{@_next_seqno} got: #{link.seqno}")
else if @_next_payload_hash? and link.prev isnt @_next_payload_hash
err = new E.WrongPrevError(
"Previous payload hash doesn't match,
expected: #{@_next_payload_hash} got: #{link.prev}")
@_next_seqno++
@_next_payload_hash = link.payload_hash
cb err
_check_key_is_valid : ({link}, cb) ->
err = null
if link.kid not of @_valid_sibkeys
err = new E.InvalidSibkeyError("not a valid sibkey: #{link.kid}, valid sibkeys:
#{JSON.stringify(kid for kid of @_valid_sibkeys)}")
else if link.ctime_seconds > @_kid_to_etime_seconds[link.kid]
err = new E.ExpiredSibkeyError "expired sibkey: #{link.kid}"
cb err
_delegate_keys : ({link, log}, cb) ->
esc = make_esc cb, 'SigChain._delegate_keys'
# If this is the first link in the subchain, it implicitly delegates the
# eldest key.
if @_current_subchain.length == 1
log "| libkeybase: delegating eldest key #{link.kid}"
await @_delegate_sibkey {
kid: link.kid
etime_seconds: link.etime_seconds
full_hash: link.signing_key_hash
}, esc defer()
if link.sibkey_delegation?
log "| libkeybase: delegating sibkey #{link.sibkey_delegation}"
await @_delegate_sibkey {
kid: link.sibkey_delegation
etime_seconds: link.etime_seconds
full_hash: link.sibkey_hash
}, esc defer()
if link.subkey_delegation?
log "| libkeybase: delegating subkey #{link.subkey_delegation}"
await @_delegate_subkey {
kid: link.subkey_delegation
etime_seconds: link.etime_seconds
}, esc defer()
# Handle pgp_update links.
if link.pgp_update_kid? and link.pgp_update_hash? and @_valid_sibkeys[link.pgp_update_kid]?
await @_key_state.set_key_hash {kid: link.pgp_update_kid, hash: link.pgp_update_hash}, esc defer()
cb()
_delegate_sibkey : ({kid, etime_seconds, full_hash}, cb) ->
esc = make_esc cb, 'SigChain._delegate_sibkey'
@_valid_sibkeys[kid] = true
if kid not in @_sibkey_order
@_sibkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
@_update_kid_pgp_etime { kid }
if full_hash?
await @_key_state.set_key_hash {kid, hash: full_hash}, esc defer()
cb null
_delegate_subkey : ({kid, etime_seconds}, cb) ->
esc = make_esc cb, 'SigChain._delegate_subkey'
@_valid_subkeys[kid] = true
if kid not in @_subkey_order
@_subkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
# Subkeys are always NaCl, never PGP. So no full hash or pgp_etime stuff.
cb null
_update_kid_pgp_etime : ({kid}) ->
# PGP keys have an internal etime, which could be sooner than their link
# etime. If so, that's what we'll use.
key_manager = @_key_state.get_key_manager kid
lifespan = key_manager?.primary?.lifespan
if lifespan?.expire_in?
etime_seconds = lifespan.generated + lifespan.expire_in
@_update_kid_etime {kid, etime_seconds}
_update_kid_etime : ({kid, etime_seconds}) ->
# PGP keys can have two different etimes: the expiration time of their
# delegating chain link and the internal expiration time recorded by PGP.
# We believe the more restrictive of the two.
if not @_kid_to_etime_seconds[kid]?
@_kid_to_etime_seconds[kid] = etime_seconds
else
@_kid_to_etime_seconds[kid] = Math.min(etime_seconds, @_kid_to_etime_seconds[kid])
_revoke_keys_and_sigs : ({link, log}, cb) ->
# Handle direct sibkey revocations.
for kid in link.key_revocations
if kid of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{kid}"
delete @_valid_sibkeys[kid]
if kid of @_valid_subkeys
delete @_valid_subkeys[kid]
# Handle revocations of an entire link.
for sig_id in link.sig_revocations
if sig_id of @_unrevoked_links
revoked_link = @_unrevoked_links[sig_id]
delete @_unrevoked_links[sig_id]
# Keys delegated by the revoked link are implicitly revoked as well.
revoked_sibkey = revoked_link.sibkey_delegation
if revoked_sibkey? and revoked_sibkey of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{revoked_sibkey} from sig #{sig_id}"
delete @_valid_sibkeys[revoked_sibkey]
revoked_subkey = revoked_link.subkey_delegation
if revoked_subkey? and revoked_subkey of @_valid_subkeys
delete @_valid_subkeys[revoked_subkey]
cb()
_enforce_eldest_key_ownership : ({}, cb) ->
# It's important that users actually *prove* they own their eldest key,
# rather than just claiming someone else's key as their own. The server
# normally enforces this, and here we check the server's work. Proof can
# happen in one of two ways: either the eldest key signs a link in the
# sigchain (thereby referencing the username in the signature payload), or
# the eldest key is a PGP key that self-signs its own identity.
esc = make_esc cb, "SigChain._enforce_eldest_key_ownership"
if @_current_subchain.length > 0
# There was at least one chain link signed by the eldest key.
cb null
return
# No chain link signed by the eldest key. Check PGP self sig.
eldest_km = @_key_state.get_key_manager @_eldest_kid
if not eldest_km?
# Server-reported eldest key is simply missing.
await athrow (new E.NonexistentKidError "no key for eldest kid #{@_eldest_kid}"), esc defer()
userids = eldest_km.get_userids_mark_primary()
if not userids?
# Server-reported key doesn't self-sign any identities (probably because
# it's a NaCl key and not a PGP key).
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not self-signing"), esc defer()
expected_email = @_username + "@keybase.io"
for identity in userids
if identity.get_email() == expected_email
# Found a matching identity. This key is good.
cb null
return
# No matching identity found.
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not owned by #{expected_email}"), esc defer()
error_names = [
"BAD_LINK_FORMAT"
"EXPIRED_SIBKEY"
"FINGERPRINT_MISMATCH"
"INVALID_SIBKEY"
"KEY_OWNERSHIP"
"KID_MISMATCH"
"NO_KEY_WITH_THIS_HASH"
"NONEXISTENT_KID"
"NOT_LATEST_SUBCHAIN"
"REVERSE_SIG_VERIFY_FAILED"
"VERIFY_FAILED"
"WRONG_UID"
"WRONG_USERNAME"
"WRONG_SEQNO"
"WRONG_PREV"
]
# make_errors() needs its input to be a map
errors_map = {}
for name in error_names
errors_map[name] = ""
exports.E = E = ie.make_errors errors_map
current_time_seconds = () ->
Math.floor(new Date().getTime() / 1000)
# Stupid coverage hack. If this breaks just delete it please, and I'm so sorry.
__iced_k_noop()
| 194677 | {bufeq_secure,athrow, a_json_parse} = require('iced-utils').util
{make_esc} = require 'iced-error'
kbpgp = require('kbpgp')
proofs = require('keybase-proofs')
ie = require('iced-error')
{trim} = require('pgp-utils').util
UID_LEN = 32
exports.SIG_ID_SUFFIX = SIG_ID_SUFFIX = "0f"
strip_final_newline = (buf) ->
s = buf.toString('utf8')
if s[-1...] is "\n" then new Buffer s[0...-1], "utf8"
else buf
# On 15 Sep 2015, a day that will live in infamy, some users made bad
# sigchain additions due to a code error that was stripping out
# whitespace from json payloads, writing those payloads to the DB, and then
# offering those payloads back out for subsequent signatures. We address that
# issue here by subtracting that dropped newline out right before we hash.
# We should potentially have a whitelist here for sigids that are affected:
bad_whitespace_sig_ids = {
"595a73fc649c2c8ccc1aa79384e0b3e7ab3049d8df838f75ef0edbcb5bbc42990f" : true
"e256078702afd7a15a24681259935b48342a49840ab6a90291b300961669790f0f" : true
"30831001edee5e01c3b5f5850043f9ef7749a1ed8624dc703ae0922e1d0f16dd0f" : true
"88e6c581dbccbf390559bcb30ca21548ba0ec4861ec2d666217bd4ed4a4a8c3f0f" : true
"4db0fe3973b3a666c7830fcb39d93282f8bc414eca1d535033a5cc625eabda0c0f" : true
"9ba23a9a1796fb22b3c938f1edf5aba4ca5be7959d9151895eb6aa7a8d8ade420f" : true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f" : true
"a32692af33e559e00a40aa3bb4004744d2c1083112468ed1c8040eaacd15c6eb0f" : true
"3e61901f50508aba72f12740fda2be488571afc51d718d845e339e5d1d1b531d0f" : true
"de43758b653b3383aca640a96c7890458eadd35242e8f8531f29b606890a14ea0f" : true
"b9ee3b46c97d48742a73e35494d3a373602460609e3c6c54a553fc4d83b659e40f" : true
"0ff29c1d036c3f4841f3f485e28d77351abb3eeeb52d2f8d802fd15e383d9a5f0f" : true
"eb1a13c6b6e42bb7470e222b51d36144a25ffc4fbc0b32e9a1ec11f059001bc80f" : true
"9c189d6d644bad9596f78519d870a685624f813afc1d0e49155073d3b0521f970f" : true
"aea7c8f7726871714e777ac730e77e1905a38e9587f9504b739ff9b77ef2d5cc0f" : true
"<KEY>" : true
"<KEY>" : true
"<KEY>" : true
"<KEY>" : true
"1<KEY>0<KEY>64<KEY>13b<KEY>188eca2af6406a8<KEY>6dbf<KEY>8df<KEY>3<KEY>b8<KEY>b<KEY>cb67<KEY>8626ff2af180f" : true
"3042dbe45383b0c2eafe13a73da35c4e721be026d7908dfcef6eb121d95b75b10f" : true
"50ba350ddc388f7c6fdba032a7d283e4caa0ca656f92f69257213222dd7deeaf0f" : true
"<KEY>b<KEY>0<KEY>1ee<KEY>3c0fc5<KEY>bd<KEY>cf<KEY>6ff<KEY>b<KEY>" : true
"<KEY>" : true
"<KEY>" : true
"a5c4a30d1eaaf752df424bf813c5a907a5cf94fd371e280d39e0a3d078310fba0f" : true
"c7d26afbc1957ecca890d8d9001a9cc4863490161720ad76a2aedeb8c2d50df70f" : true
"b385c0c76d790aba156ff68fd571171fc7cb85f75e7fc9d1561d7960d8875acb0f" : true
"47d349b8bb3c8457449390ca2ed5e489a70ad511ab3edb4c7f0af27eed8c65d30f" : true
"2785b24acd6869e1e7d38a91793af549f3c35cd0729127d200b66f8c0ffba59b0f" : true
"503df567f98cf5910ba44cb95e157e656afe95d159a15c7df4e88ac6016c948f0f" : true
"2892863758cdaf9796fb36e2466093762efda94e74eb51e3ab9d6bec54064b8a0f" : true
"e1d60584995e677<KEY>4<KEY>913b3<KEY>0060b<KEY>00241<KEY>0<KEY>1<KEY>82acc<KEY>e08<KEY>" : true
"031b506b705926ea962e59046bfe1720dcf72c85310502020e2ae836b294fcde0f" : true
"1454fec21489f17a6d78927af1c9dca4209360c6ef6bfa569d8b62d32e668ea30f" : true
"ba68052597a3782f64079d7d9ec821ea9785c0868e44b597a04c9cd8bf634c1e0f" : true
"db8d59151b2f78c82c095c9545f1e4d39947a0c0bcc01b907e0ace14517d39970f" : true
"e088beccfee26c5df39239023d1e4e0cbcd63fd50d0bdc4bf2c2ba25ef1a8fe40f" : true
"8182f385c347fe57d3c46fe40e8df0e2d6cabdac38f490417b313050249be9dc0f" : true
"<KEY>" : true
"<KEY>" : true
"7<KEY>c<KEY>026afec66312456b6820492b7936bff<KEY>2b<KEY>8ca7<KEY>0<KEY>9462700677ef<KEY>" : true
"7591a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d9<KEY>ad9b<KEY>9<KEY>" : true
"062e6<KEY>" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
"<KEY>" : true
"<KEY>" : true
"<KEY>" : true
"<KEY>bd<KEY>cd<KEY>" : true
"<KEY>" : true
"<KEY>b<KEY>" : true
"<KEY>1a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
}
# We had an incident where a Go client using an old reverse-sig format got some
# links into a public chain. (Sorry <NAME>!) Skip reverse signature checking for
# this fixed set of links.
known_buggy_reverse_sigs = {
"2<KEY>0da9730f049133<KEY>728ba30de8<KEY>1<KEY>658b<KEY>3<KEY>82<KEY>ddb<KEY>": true
"eb5c7e7d3cf8370bed8ab55c0d8833ce9d74fd2c614cf2cd2d4c30feca4518fa0f": true
"0f175ef0d3b57a9991db5deb30f2432a85bc05922bbe727016f3fb660863a1890f": true
"<KEY>": true
};
# Some users (6) managed to reuse eldest keys after a sigchain reset, without
# using the "eldest" link type, before the server prohibited this. To clients,
# that means their chains don't appear to reset. We hardcode these cases.
hardcoded_resets = {
"11111487aa193b9fafc92851176803af8ed005983cad1eaf5d6a49a459b8fffe0f": true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f": true
"32eab86aa31796db3200f42f2553d330b8a68931544bbb98452a80ad2b0003d30f": true
"5ed7a3356fd0f759a4498fc6fed1dca7f62611eb14f782a2a9cda1b836c58db50f": true
"d5fe2c5e31958fe45a7f42b325375d5bd8916ef757f736a6faaa66a6b18bec780f": true
"1e116e81bc08b915d9df93dc35c202a75ead36c479327cdf49a15f3768ac58f80f": true
}
# For testing that caches are working properly. (Use a wrapper object instead
# of a simple counter because main.iced copies things.)
exports.debug =
unbox_count: 0
exports.ParsedKeys = ParsedKeys = class ParsedKeys
@parse : ({key_bundles}, cb) ->
# We only take key bundles from the server, either hex NaCl public keys, or
# ascii-armored PGP public key strings. We compute the KIDs and
# fingerprints ourselves, because we don't trust the server to do it for
# us.
esc = make_esc cb, "ParsedKeys.parse"
default_eldest_kid_for_testing = null
opts = { time_travel : true }
parsed_keys = new ParsedKeys
for bundle in key_bundles
await kbpgp.ukm.import_armored_public {armored: bundle, opts}, esc defer key_manager
await parsed_keys._add_key {key_manager}, esc defer()
default_eldest_kid_for_testing or= key_manager.get_ekid().toString "hex"
cb null, parsed_keys, default_eldest_kid_for_testing
constructor : ->
# Callers should use this class to get KeyManagers for KIDs they already
# have, but callers MUST NOT iterate over the set of KIDs here as though it
# were the valid set for a given user. The set of KIDs is *untrusted*
# because it comes from the server. We keep the map private to prevent that
# mistake.
@_kids_to_merged_pgp_key_managers = {}
@_kids_to_pgp_key_managers_by_hash = {}
@_kids_to_nacl_keys = {}
_add_key : ({key_manager}, cb) ->
esc = make_esc "ParsedKeys._add_key"
kid = key_manager.get_ekid()
kid_str = kid.toString "hex"
if key_manager.pgp?
if (existing = @_kids_to_merged_pgp_key_managers[kid_str])?
existing.merge_everything key_manager
else
@_kids_to_merged_pgp_key_managers[kid_str] = key_manager
await key_manager.pgp_full_hash {}, esc defer hash
(@_kids_to_pgp_key_managers_by_hash[kid_str] or= {})[hash] = key_manager
else
@_kids_to_nacl_keys[kid_str] = key_manager
cb()
# We may have multiple versions of a PGP key with the same KID/fingerprint.
# They could have different subkeys and userids, and an old subkey could have
# been used to sign an old link. We historically handled handle these cases
# by merging all versions of a PGP key together, but since it's valid to
# upload a new version of a PGP key specifically to revoke a subkey and
# prevent it from signing new chainlinks, we realized that it's necessary to
# track which version of the key is active. When a PGP key is signed in or
# updated, the hash of the ASCII-armored public key is now specified in the
# sigchain.
#
# get_merged_pgp_key_manager must only be used when a hash hasn't been
# specified (in, say, an old sigchain). When an eldest, sibkey, or pgp_update
# link specifies a hash, get_pgp_key_manager_with_hash must be used for all
# following links signed by that KID.
get_merged_pgp_key_manager : (kid) ->
@_kids_to_merged_pgp_key_managers[kid]
get_pgp_key_manager_with_hash : (kid, hash) ->
@_kids_to_pgp_key_managers_by_hash[kid]?[hash]
get_nacl_key_manager : (kid) ->
@_kids_to_nacl_keys[kid]
# KeyState tracks hashes that have been specified for PGP keys. As long as it's
# kept up to date as the sigchain is replayed, it can safely be used to get the
# correct KeyManager for a given KID.
class KeyState
constructor : ({@parsed_keys}) ->
@_kid_to_hash = {}
set_key_hash : ({kid, hash}, cb) ->
if not @parsed_keys.get_pgp_key_manager_with_hash(kid, hash)?
cb new E.NoKeyWithThisHashError "No PGP key with kid #{kid} and hash #{hash} exists"
return
@_kid_to_hash[kid] = hash
cb()
get_key_manager : (kid) ->
if (key = @parsed_keys.get_nacl_key_manager kid)?
return key
if (hash = @_kid_to_hash[kid])?
return @parsed_keys.get_pgp_key_manager_with_hash kid, hash
return @parsed_keys.get_merged_pgp_key_manager kid
class ChainLink
@parse : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink.parse"
# Unbox the signed payload. PGP key expiration is checked automatically
# during unbox, using the ctime of the chainlink.
await @_unbox_payload {sig_blob, key_state, sig_cache}, esc defer payload, sig_id, payload_hash
# Check internal details of the payload, like uid length.
await check_link_payload_format {payload}, esc defer()
# Make sure the KID from the server matches the payload, and that any
# payload PGP fingerprint also matches the KID.
await @_check_payload_against_server_kid {sig_blob, payload, key_state}, esc defer()
# Check any reverse signatures. For links where we skip this step, we will
# ignore their contents later.
if not known_buggy_reverse_sigs[sig_id]
await @_check_reverse_signatures {payload, key_state}, esc defer()
# The constructor takes care of all the payload parsing that isn't failable.
cb null, new ChainLink {kid: sig_blob.kid, sig_id, payload, payload_hash}
@_unbox_payload : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink._unbox_payload"
# Get the signing KID directly from the server blob. We'll confirm later
# that this is the same as the KID listed in the payload.
kid = sig_blob.kid
# Get the key_manager and sig_eng we need from the ParsedKeys object.
key_manager = key_state.get_key_manager kid
if not key_manager?
await athrow (new E.NonexistentKidError "link signed by nonexistent kid #{kid}"), esc defer()
sig_eng = key_manager.make_sig_eng()
# We need the signing ctime to verify the signature, and that's actually in
# the signed payload. So we fully parse the payload *before* verifying, and
# do the actual (maybe cached) verification at the end.
await sig_eng.get_body_and_unverified_payload(
{armored: sig_blob.sig}, esc defer sig_body, unverified_buffer)
sig_id = kbpgp.hash.SHA256(sig_body).toString("hex") + SIG_ID_SUFFIX
payload_json = unverified_buffer.toString('utf8')
await a_json_parse payload_json, esc defer payload
ctime_seconds = payload.ctime
# Now that we have the ctime, get the verified payload.
if sig_cache?
await sig_cache.get {sig_id}, esc defer verified_buffer
if not verified_buffer?
exports.debug.unbox_count++
await key_manager.make_sig_eng().unbox(
sig_blob.sig,
defer(err, verified_buffer),
{now: ctime_seconds})
if err?
await athrow (new E.VerifyFailedError err.message), esc defer()
if sig_cache?
await sig_cache.put {sig_id, payload_buffer: verified_buffer}, esc defer()
# Check that what we verified matches the unverified payload we used above.
# Ideally it should be impossible for there to be a difference, but this
# protects us from bugs/attacks that might exploit multiple payloads,
# particularly in PGP.
await check_buffers_equal verified_buffer, unverified_buffer, esc defer()
# Success!
# See comment above about bad whitespace sigs from 15 Sep 2015
hash_input = if bad_whitespace_sig_ids[sig_id] then strip_final_newline verified_buffer
else verified_buffer
payload_hash = kbpgp.hash.SHA256(hash_input).toString("hex")
cb null, payload, sig_id, payload_hash
@_check_payload_against_server_kid : ({sig_blob, payload, key_state}, cb) ->
# Here's where we check the data we relied on in @_unbox_payload().
signing_kid = sig_blob.kid
signing_fingerprint = key_state.get_key_manager(signing_kid).get_pgp_fingerprint()?.toString('hex')
payload_kid = payload.body.key.kid
payload_fingerprint = payload.body.key.fingerprint
err = null
if payload_kid? and payload_kid isnt signing_kid
err = new E.KidMismatchError "signing kid (#{signing_kid}) and payload kid (#{payload_kid}) mismatch"
else if payload_fingerprint? and payload_fingerprint isnt signing_fingerprint
err = new E.FingerprintMismatchError "signing fingerprint (#{signing_fingerprint}) and payload fingerprint (#{payload_fingerprint}) mismatch"
cb err
@_check_reverse_signatures : ({payload, key_state}, cb) ->
esc = make_esc cb, "ChainLink._check_reverse_signatures"
if payload.body.sibkey?
kid = payload.body.sibkey.kid
full_hash = payload.body.sibkey.full_hash
sibkey_key_manager = if full_hash?
# key_state hasn't been updated with the new sibkey's full hash yet
key_state.parsed_keys.get_pgp_key_manager_with_hash kid, full_hash
else
key_state.get_key_manager kid
if not sibkey_key_manager?
await athrow (new E.NonexistentKidError "link reverse-signed by nonexistent kid #{kid}"), esc defer()
sibkey_proof = new proofs.Sibkey {}
await sibkey_proof.reverse_sig_check {json: payload, subkm: sibkey_key_manager}, defer err
if err?
await athrow (new E.ReverseSigVerifyFailedError err.message), esc defer()
if payload.body.subkey?
kid = payload.body.subkey.kid
subkey_key_manager = key_state.get_key_manager kid
if not subkey_key_manager?
await athrow (new E.NonexistentKidError "link delegates nonexistent subkey #{kid}"), esc defer()
cb null
constructor : ({@kid, @sig_id, @payload, @payload_hash}) ->
@uid = @payload.body.key.uid
@username = @payload.body.key.username
@seqno = @payload.seqno
@prev = @payload.prev
# @fingerprint is PGP-only.
@fingerprint = @payload.body.key.fingerprint
# Not all links have the "eldest_kid" field, but if they don't, then their
# signing KID is implicitly the eldest.
@eldest_kid = @payload.body.key.eldest_kid or @kid
@ctime_seconds = @payload.ctime
@etime_seconds = @ctime_seconds + @payload.expire_in
@type = @payload.body.type
# Only expected to be set in eldest links
@signing_key_hash = @payload.body.key.full_hash
@sibkey_delegation = @payload.body.sibkey?.kid
@sibkey_hash = @payload.body.sibkey?.full_hash
@subkey_delegation = @payload.body.subkey?.kid
@pgp_update_kid = @payload.body.pgp_update?.kid
@pgp_update_hash = @payload.body.pgp_update?.full_hash
@key_revocations = []
if @payload.body.revoke?.kids?
@key_revocations = @payload.body.revoke.kids
if @payload.body.revoke?.kid?
@key_revocations.push(@payload.body.revoke.kid)
@sig_revocations = []
if @payload.body.revoke?.sig_ids?
@sig_revocations = @payload.body.revoke.sig_ids
if @payload.body.revoke?.sig_id?
@sig_revocations.push(@payload.body.revoke.sig_id)
# Exported for testing.
exports.check_link_payload_format = check_link_payload_format = ({payload}, cb) ->
esc = make_esc cb, "check_link_payload_format"
uid = payload.body.key.uid
if uid.length != UID_LEN
await athrow (new E.BadLinkFormatError "UID wrong length: #{uid.length}"), esc defer()
cb()
# Also exported for testing. This check will never fail under normal
# circumstances, so we need a test to explicitly make it fail.
exports.check_buffers_equal = check_buffers_equal = (verified_buffer, unverified_buffer, cb) ->
err = null
if not bufeq_secure(verified_buffer,unverified_buffer)
msg = """Payload mismatch!
Verified:
#{verified_buffer.toString('hex')}
Unverified:
#{unverified_buffer.toString('hex')}"""
err = new E.VerifyFailedError msg
cb err
exports.SigChain = class SigChain
# The replay() method is the main interface for all callers. It checks all of
# the user's signatures and returns a SigChain object representing their
# current state.
#
# @param {[string]} sig_blobs The parsed JSON signatures list returned from
# the server's sig/get.json endpoint.
# @param {ParsedKeys} parsed_keys The unverified collection of all the user's
# public keys. This is usually obtained from the all_bundles list given
# by user/lookup.json, passed to ParsedKeys.parse(). NaCl public key
# material is contained entirely within the KID, so technically all this
# extra data is only needed for PGP, but we treat both types of keys the
# same way for simplicity.
# @param {object} sig_cache An object with two methods: get({sig_id}, cb) and
# put({sig_id, payload_buffer}, cb), which caches the payloads of
# previously verified signatures. This parameter can be null, in which
# case all signatures will be checked.
# @param {string} uid Used only to check that the sigchain belongs to the
# right user.
# @param {string} username As with uid, used for confirming ownership.
# @param {string} eldest_kid The full (i.e. with-prefix) KID of the user's
# current eldest key. This is used to determine the latest subchain.
# @param {object} log An object with logging methods (debug, info, warn,
# error). May be null.
@replay : ({sig_blobs, parsed_keys, sig_cache, uid, username, eldest_kid, log}, cb) ->
log = log or (() ->)
log "+ libkeybase: replay(username: #{username}, uid: #{uid}, eldest: #{eldest_kid})"
esc = make_esc cb, "SigChain.replay"
# Forgetting the eldest KID would silently give you an empty sigchain. Prevent this.
if not eldest_kid?
await athrow (new Error "eldest_kid parameter is required"), esc defer()
# Initialize the SigChain.
sigchain = new SigChain {uid, username, eldest_kid, parsed_keys}
# Build the chain link by link, checking consistency all the way through.
for sig_blob in sig_blobs
log "| libkeybase: replaying signature #{sig_blob.seqno}: #{sig_blob.sig_id}"
await sigchain._add_new_link {sig_blob, sig_cache, log}, esc defer()
# If the eldest kid of the current subchain doesn't match the eldest kid
# we're looking for, that means we're on a new zero-length subchain.
if eldest_kid isnt sigchain._current_subchain_eldest
sigchain._reset_subchain(eldest_kid)
# After the chain is finished, make sure we've proven ownership of the
# eldest key in some way.
await sigchain._enforce_eldest_key_ownership {}, esc defer()
log "- libkeybase: replay finished"
cb null, sigchain
# NOTE: Don't call the constructor directly. Use SigChain.replay().
constructor : ({uid, username, eldest_kid, parsed_keys}) ->
@_uid = uid
@_username = username
@_eldest_kid = eldest_kid
@_parsed_keys = parsed_keys
@_next_seqno = 1
@_next_payload_hash = null
@_reset_subchain(null)
_reset_subchain : (current_subchain_eldest) ->
@_current_subchain = []
@_current_subchain_eldest = current_subchain_eldest
@_key_state = new KeyState {parsed_keys: @_parsed_keys}
@_unrevoked_links = {}
@_valid_sibkeys = {}
@_valid_sibkeys[current_subchain_eldest] = true
@_sibkey_order = [current_subchain_eldest]
@_valid_subkeys = {}
@_subkey_order = []
@_kid_to_etime_seconds = {}
@_update_kid_pgp_etime { kid: current_subchain_eldest }
# Return the list of links in the current subchain which have not been
# revoked.
get_links : () ->
return (link for link in @_current_subchain when link.sig_id of @_unrevoked_links)
# Return the list of sibkey KIDs which aren't revoked or expired.
get_sibkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_sibkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_sibkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
# Return the list of subkey KIDs which aren't revoked or expired.
get_subkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_subkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_subkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
_add_new_link : ({sig_blob, sig_cache, log}, cb) ->
esc = make_esc cb, "SigChain._add_new_link"
# This constructor checks that the link is internally consistent: its
# signature is valid and belongs to the key it claims, and the same for any
# reverse sigs.
await ChainLink.parse {sig_blob, key_state: @_key_state, sig_cache}, esc defer link
log "| libkeybase: chain link parsed, type '#{link.payload.body.type}'"
# Make sure the link belongs in this chain (right username and uid) and at
# this particular point in the chain (right seqno and prev hash).
await @_check_link_belongs_here {link}, esc defer()
# Now see if we've hit a sigchain reset. That can happen for one of two
# reasons:
# 1) The eldest kid reported by this link (either explicitly or
# implicitly; see ChainLink.eldest_kid) is different from the one that
# came before it.
# 2) This link is of the "eldest" type.
# We *don't* short-circuit here though. Verifying past subchains just like
# we verify the current one actually simplifies PGP full hash handling.
# (Otherwise we'd have to figure out how to maintain the KeyState, or else
# we wouldn't even be able to verify link signatures [correctly, without
# resorting to key merging].)
if (link.eldest_kid isnt @_current_subchain_eldest or
link.type is "eldest" or
hardcoded_resets[link.sig_id])
log "| libkeybase: starting new subchain"
@_reset_subchain(link.eldest_kid)
# Links with known bad reverse sigs still have to have valid payload hashes
# and seqnos, but their contents are ignored, and their signing keys might
# not be valid sibkeys (because the delegating links of those sibkeys might
# also have been bad). Short-circuit here for these links, after checking
# the link position but before checking the validity of the signing key.
if known_buggy_reverse_sigs[link.sig_id]
cb null
return
# Finally, make sure that the key that signed this link was actually valid
# at the time the link was signed.
await @_check_key_is_valid {link}, esc defer()
log "| libkeybase: signing key is valid (#{link.kid})"
# This link is valid and part of the current subchain. Update all the
# relevant metadata.
@_current_subchain.push(link)
@_unrevoked_links[link.sig_id] = link
await @_delegate_keys {link, log}, esc defer()
await @_revoke_keys_and_sigs {link, log}, esc defer()
cb null
_check_link_belongs_here : ({link}, cb) ->
err = null
if link.uid isnt @_uid
err = new E.WrongUidError(
"Link doesn't refer to the right uid,
expected: #{link.uid} got: #{@_uid}")
else if link.username.toLowerCase() isnt @_username.toLowerCase()
err = new E.WrongUsernameError(
"Link doesn't refer to the right username,
expected: #{link.username} got: #{@_username}")
else if link.seqno isnt @_next_seqno
err = new E.WrongSeqnoError(
"Link sequence number is wrong, expected:
#{@_next_seqno} got: #{link.seqno}")
else if @_next_payload_hash? and link.prev isnt @_next_payload_hash
err = new E.WrongPrevError(
"Previous payload hash doesn't match,
expected: #{@_next_payload_hash} got: #{link.prev}")
@_next_seqno++
@_next_payload_hash = link.payload_hash
cb err
_check_key_is_valid : ({link}, cb) ->
err = null
if link.kid not of @_valid_sibkeys
err = new E.InvalidSibkeyError("not a valid sibkey: #{link.kid}, valid sibkeys:
#{JSON.stringify(kid for kid of @_valid_sibkeys)}")
else if link.ctime_seconds > @_kid_to_etime_seconds[link.kid]
err = new E.ExpiredSibkeyError "expired sibkey: #{link.kid}"
cb err
_delegate_keys : ({link, log}, cb) ->
esc = make_esc cb, 'SigChain._delegate_keys'
# If this is the first link in the subchain, it implicitly delegates the
# eldest key.
if @_current_subchain.length == 1
log "| libkeybase: delegating eldest key #{link.kid}"
await @_delegate_sibkey {
kid: link.kid
etime_seconds: link.etime_seconds
full_hash: link.signing_key_hash
}, esc defer()
if link.sibkey_delegation?
log "| libkeybase: delegating sibkey #{link.sibkey_delegation}"
await @_delegate_sibkey {
kid: link.sibkey_delegation
etime_seconds: link.etime_seconds
full_hash: link.sibkey_hash
}, esc defer()
if link.subkey_delegation?
log "| libkeybase: delegating subkey #{link.subkey_delegation}"
await @_delegate_subkey {
kid: link.subkey_delegation
etime_seconds: link.etime_seconds
}, esc defer()
# Handle pgp_update links.
if link.pgp_update_kid? and link.pgp_update_hash? and @_valid_sibkeys[link.pgp_update_kid]?
await @_key_state.set_key_hash {kid: link.pgp_update_kid, hash: link.pgp_update_hash}, esc defer()
cb()
_delegate_sibkey : ({kid, etime_seconds, full_hash}, cb) ->
esc = make_esc cb, 'SigChain._delegate_sibkey'
@_valid_sibkeys[kid] = true
if kid not in @_sibkey_order
@_sibkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
@_update_kid_pgp_etime { kid }
if full_hash?
await @_key_state.set_key_hash {kid, hash: full_hash}, esc defer()
cb null
_delegate_subkey : ({kid, etime_seconds}, cb) ->
esc = make_esc cb, 'SigChain._delegate_subkey'
@_valid_subkeys[kid] = true
if kid not in @_subkey_order
@_subkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
# Subkeys are always NaCl, never PGP. So no full hash or pgp_etime stuff.
cb null
_update_kid_pgp_etime : ({kid}) ->
# PGP keys have an internal etime, which could be sooner than their link
# etime. If so, that's what we'll use.
key_manager = @_key_state.get_key_manager kid
lifespan = key_manager?.primary?.lifespan
if lifespan?.expire_in?
etime_seconds = lifespan.generated + lifespan.expire_in
@_update_kid_etime {kid, etime_seconds}
_update_kid_etime : ({kid, etime_seconds}) ->
# PGP keys can have two different etimes: the expiration time of their
# delegating chain link and the internal expiration time recorded by PGP.
# We believe the more restrictive of the two.
if not @_kid_to_etime_seconds[kid]?
@_kid_to_etime_seconds[kid] = etime_seconds
else
@_kid_to_etime_seconds[kid] = Math.min(etime_seconds, @_kid_to_etime_seconds[kid])
_revoke_keys_and_sigs : ({link, log}, cb) ->
# Handle direct sibkey revocations.
for kid in link.key_revocations
if kid of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{kid}"
delete @_valid_sibkeys[kid]
if kid of @_valid_subkeys
delete @_valid_subkeys[kid]
# Handle revocations of an entire link.
for sig_id in link.sig_revocations
if sig_id of @_unrevoked_links
revoked_link = @_unrevoked_links[sig_id]
delete @_unrevoked_links[sig_id]
# Keys delegated by the revoked link are implicitly revoked as well.
revoked_sibkey = revoked_link.sibkey_delegation
if revoked_sibkey? and revoked_sibkey of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{revoked_sibkey} from sig #{sig_id}"
delete @_valid_sibkeys[revoked_sibkey]
revoked_subkey = revoked_link.subkey_delegation
if revoked_subkey? and revoked_subkey of @_valid_subkeys
delete @_valid_subkeys[revoked_subkey]
cb()
_enforce_eldest_key_ownership : ({}, cb) ->
# It's important that users actually *prove* they own their eldest key,
# rather than just claiming someone else's key as their own. The server
# normally enforces this, and here we check the server's work. Proof can
# happen in one of two ways: either the eldest key signs a link in the
# sigchain (thereby referencing the username in the signature payload), or
# the eldest key is a PGP key that self-signs its own identity.
esc = make_esc cb, "SigChain._enforce_eldest_key_ownership"
if @_current_subchain.length > 0
# There was at least one chain link signed by the eldest key.
cb null
return
# No chain link signed by the eldest key. Check PGP self sig.
eldest_km = @_key_state.get_key_manager @_eldest_kid
if not eldest_km?
# Server-reported eldest key is simply missing.
await athrow (new E.NonexistentKidError "no key for eldest kid #{@_eldest_kid}"), esc defer()
userids = eldest_km.get_userids_mark_primary()
if not userids?
# Server-reported key doesn't self-sign any identities (probably because
# it's a NaCl key and not a PGP key).
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not self-signing"), esc defer()
expected_email = @_username + "@keybase.io"
for identity in userids
if identity.get_email() == expected_email
# Found a matching identity. This key is good.
cb null
return
# No matching identity found.
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not owned by #{expected_email}"), esc defer()
error_names = [
"BAD_LINK_FORMAT"
"EXPIRED_SIBKEY"
"FINGERPRINT_MISMATCH"
"INVALID_SIBKEY"
"KEY_OWNERSHIP"
"KID_MISMATCH"
"NO_KEY_WITH_THIS_HASH"
"NONEXISTENT_KID"
"NOT_LATEST_SUBCHAIN"
"REVERSE_SIG_VERIFY_FAILED"
"VERIFY_FAILED"
"WRONG_UID"
"WRONG_USERNAME"
"WRONG_SEQNO"
"WRONG_PREV"
]
# make_errors() needs its input to be a map
errors_map = {}
for name in error_names
errors_map[name] = ""
exports.E = E = ie.make_errors errors_map
current_time_seconds = () ->
Math.floor(new Date().getTime() / 1000)
# Stupid coverage hack. If this breaks just delete it please, and I'm so sorry.
__iced_k_noop()
| true | {bufeq_secure,athrow, a_json_parse} = require('iced-utils').util
{make_esc} = require 'iced-error'
kbpgp = require('kbpgp')
proofs = require('keybase-proofs')
ie = require('iced-error')
{trim} = require('pgp-utils').util
UID_LEN = 32
exports.SIG_ID_SUFFIX = SIG_ID_SUFFIX = "0f"
strip_final_newline = (buf) ->
s = buf.toString('utf8')
if s[-1...] is "\n" then new Buffer s[0...-1], "utf8"
else buf
# On 15 Sep 2015, a day that will live in infamy, some users made bad
# sigchain additions due to a code error that was stripping out
# whitespace from json payloads, writing those payloads to the DB, and then
# offering those payloads back out for subsequent signatures. We address that
# issue here by subtracting that dropped newline out right before we hash.
# We should potentially have a whitelist here for sigids that are affected:
bad_whitespace_sig_ids = {
"595a73fc649c2c8ccc1aa79384e0b3e7ab3049d8df838f75ef0edbcb5bbc42990f" : true
"e256078702afd7a15a24681259935b48342a49840ab6a90291b300961669790f0f" : true
"30831001edee5e01c3b5f5850043f9ef7749a1ed8624dc703ae0922e1d0f16dd0f" : true
"88e6c581dbccbf390559bcb30ca21548ba0ec4861ec2d666217bd4ed4a4a8c3f0f" : true
"4db0fe3973b3a666c7830fcb39d93282f8bc414eca1d535033a5cc625eabda0c0f" : true
"9ba23a9a1796fb22b3c938f1edf5aba4ca5be7959d9151895eb6aa7a8d8ade420f" : true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f" : true
"a32692af33e559e00a40aa3bb4004744d2c1083112468ed1c8040eaacd15c6eb0f" : true
"3e61901f50508aba72f12740fda2be488571afc51d718d845e339e5d1d1b531d0f" : true
"de43758b653b3383aca640a96c7890458eadd35242e8f8531f29b606890a14ea0f" : true
"b9ee3b46c97d48742a73e35494d3a373602460609e3c6c54a553fc4d83b659e40f" : true
"0ff29c1d036c3f4841f3f485e28d77351abb3eeeb52d2f8d802fd15e383d9a5f0f" : true
"eb1a13c6b6e42bb7470e222b51d36144a25ffc4fbc0b32e9a1ec11f059001bc80f" : true
"9c189d6d644bad9596f78519d870a685624f813afc1d0e49155073d3b0521f970f" : true
"aea7c8f7726871714e777ac730e77e1905a38e9587f9504b739ff9b77ef2d5cc0f" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"1PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI64PI:KEY:<KEY>END_PI13bPI:KEY:<KEY>END_PI188eca2af6406a8PI:KEY:<KEY>END_PI6dbfPI:KEY:<KEY>END_PI8dfPI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PIb8PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIcb67PI:KEY:<KEY>END_PI8626ff2af180f" : true
"3042dbe45383b0c2eafe13a73da35c4e721be026d7908dfcef6eb121d95b75b10f" : true
"50ba350ddc388f7c6fdba032a7d283e4caa0ca656f92f69257213222dd7deeaf0f" : true
"PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI1eePI:KEY:<KEY>END_PI3c0fc5PI:KEY:<KEY>END_PIbdPI:KEY:<KEY>END_PIcfPI:KEY:<KEY>END_PI6ffPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"a5c4a30d1eaaf752df424bf813c5a907a5cf94fd371e280d39e0a3d078310fba0f" : true
"c7d26afbc1957ecca890d8d9001a9cc4863490161720ad76a2aedeb8c2d50df70f" : true
"b385c0c76d790aba156ff68fd571171fc7cb85f75e7fc9d1561d7960d8875acb0f" : true
"47d349b8bb3c8457449390ca2ed5e489a70ad511ab3edb4c7f0af27eed8c65d30f" : true
"2785b24acd6869e1e7d38a91793af549f3c35cd0729127d200b66f8c0ffba59b0f" : true
"503df567f98cf5910ba44cb95e157e656afe95d159a15c7df4e88ac6016c948f0f" : true
"2892863758cdaf9796fb36e2466093762efda94e74eb51e3ab9d6bec54064b8a0f" : true
"e1d60584995e677PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI913b3PI:KEY:<KEY>END_PI0060bPI:KEY:<KEY>END_PI00241PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI1PI:KEY:<KEY>END_PI82accPI:KEY:<KEY>END_PIe08PI:KEY:<KEY>END_PI" : true
"031b506b705926ea962e59046bfe1720dcf72c85310502020e2ae836b294fcde0f" : true
"1454fec21489f17a6d78927af1c9dca4209360c6ef6bfa569d8b62d32e668ea30f" : true
"ba68052597a3782f64079d7d9ec821ea9785c0868e44b597a04c9cd8bf634c1e0f" : true
"db8d59151b2f78c82c095c9545f1e4d39947a0c0bcc01b907e0ace14517d39970f" : true
"e088beccfee26c5df39239023d1e4e0cbcd63fd50d0bdc4bf2c2ba25ef1a8fe40f" : true
"8182f385c347fe57d3c46fe40e8df0e2d6cabdac38f490417b313050249be9dc0f" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"7PI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI026afec66312456b6820492b7936bffPI:KEY:<KEY>END_PI2bPI:KEY:<KEY>END_PI8ca7PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI9462700677efPI:KEY:<KEY>END_PI" : true
"7591a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"10a45e10ff2585b03b9b5bc449cb1a7a44fbb7fcf25565286cb2d9PI:KEY:<KEY>END_PIad9bPI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI" : true
"062e6PI:KEY:<KEY>END_PI" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PIbdPI:KEY:<KEY>END_PIcdPI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI" : true
"PI:KEY:<KEY>END_PI1a920a5050de28faad24b5fe3336f658b964e0e64464b70878bfcf04537420f" : true
"db9a0afaab297048be0d44ffd6d89a3eb6a003256426d7fd87a60ab59880f8160f" : true
}
# We had an incident where a Go client using an old reverse-sig format got some
# links into a public chain. (Sorry PI:NAME:<NAME>END_PI!) Skip reverse signature checking for
# this fixed set of links.
known_buggy_reverse_sigs = {
"2PI:KEY:<KEY>END_PI0da9730f049133PI:KEY:<KEY>END_PI728ba30de8PI:KEY:<KEY>END_PI1PI:KEY:<KEY>END_PI658bPI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PI82PI:KEY:<KEY>END_PIddbPI:KEY:<KEY>END_PI": true
"eb5c7e7d3cf8370bed8ab55c0d8833ce9d74fd2c614cf2cd2d4c30feca4518fa0f": true
"0f175ef0d3b57a9991db5deb30f2432a85bc05922bbe727016f3fb660863a1890f": true
"PI:KEY:<KEY>END_PI": true
};
# Some users (6) managed to reuse eldest keys after a sigchain reset, without
# using the "eldest" link type, before the server prohibited this. To clients,
# that means their chains don't appear to reset. We hardcode these cases.
hardcoded_resets = {
"11111487aa193b9fafc92851176803af8ed005983cad1eaf5d6a49a459b8fffe0f": true
"df0005f6c61bd6efd2867b320013800781f7f047e83fd44d484c2cb2616f019f0f": true
"32eab86aa31796db3200f42f2553d330b8a68931544bbb98452a80ad2b0003d30f": true
"5ed7a3356fd0f759a4498fc6fed1dca7f62611eb14f782a2a9cda1b836c58db50f": true
"d5fe2c5e31958fe45a7f42b325375d5bd8916ef757f736a6faaa66a6b18bec780f": true
"1e116e81bc08b915d9df93dc35c202a75ead36c479327cdf49a15f3768ac58f80f": true
}
# For testing that caches are working properly. (Use a wrapper object instead
# of a simple counter because main.iced copies things.)
exports.debug =
unbox_count: 0
exports.ParsedKeys = ParsedKeys = class ParsedKeys
@parse : ({key_bundles}, cb) ->
# We only take key bundles from the server, either hex NaCl public keys, or
# ascii-armored PGP public key strings. We compute the KIDs and
# fingerprints ourselves, because we don't trust the server to do it for
# us.
esc = make_esc cb, "ParsedKeys.parse"
default_eldest_kid_for_testing = null
opts = { time_travel : true }
parsed_keys = new ParsedKeys
for bundle in key_bundles
await kbpgp.ukm.import_armored_public {armored: bundle, opts}, esc defer key_manager
await parsed_keys._add_key {key_manager}, esc defer()
default_eldest_kid_for_testing or= key_manager.get_ekid().toString "hex"
cb null, parsed_keys, default_eldest_kid_for_testing
constructor : ->
# Callers should use this class to get KeyManagers for KIDs they already
# have, but callers MUST NOT iterate over the set of KIDs here as though it
# were the valid set for a given user. The set of KIDs is *untrusted*
# because it comes from the server. We keep the map private to prevent that
# mistake.
@_kids_to_merged_pgp_key_managers = {}
@_kids_to_pgp_key_managers_by_hash = {}
@_kids_to_nacl_keys = {}
_add_key : ({key_manager}, cb) ->
esc = make_esc "ParsedKeys._add_key"
kid = key_manager.get_ekid()
kid_str = kid.toString "hex"
if key_manager.pgp?
if (existing = @_kids_to_merged_pgp_key_managers[kid_str])?
existing.merge_everything key_manager
else
@_kids_to_merged_pgp_key_managers[kid_str] = key_manager
await key_manager.pgp_full_hash {}, esc defer hash
(@_kids_to_pgp_key_managers_by_hash[kid_str] or= {})[hash] = key_manager
else
@_kids_to_nacl_keys[kid_str] = key_manager
cb()
# We may have multiple versions of a PGP key with the same KID/fingerprint.
# They could have different subkeys and userids, and an old subkey could have
# been used to sign an old link. We historically handled handle these cases
# by merging all versions of a PGP key together, but since it's valid to
# upload a new version of a PGP key specifically to revoke a subkey and
# prevent it from signing new chainlinks, we realized that it's necessary to
# track which version of the key is active. When a PGP key is signed in or
# updated, the hash of the ASCII-armored public key is now specified in the
# sigchain.
#
# get_merged_pgp_key_manager must only be used when a hash hasn't been
# specified (in, say, an old sigchain). When an eldest, sibkey, or pgp_update
# link specifies a hash, get_pgp_key_manager_with_hash must be used for all
# following links signed by that KID.
get_merged_pgp_key_manager : (kid) ->
@_kids_to_merged_pgp_key_managers[kid]
get_pgp_key_manager_with_hash : (kid, hash) ->
@_kids_to_pgp_key_managers_by_hash[kid]?[hash]
get_nacl_key_manager : (kid) ->
@_kids_to_nacl_keys[kid]
# KeyState tracks hashes that have been specified for PGP keys. As long as it's
# kept up to date as the sigchain is replayed, it can safely be used to get the
# correct KeyManager for a given KID.
class KeyState
constructor : ({@parsed_keys}) ->
@_kid_to_hash = {}
set_key_hash : ({kid, hash}, cb) ->
if not @parsed_keys.get_pgp_key_manager_with_hash(kid, hash)?
cb new E.NoKeyWithThisHashError "No PGP key with kid #{kid} and hash #{hash} exists"
return
@_kid_to_hash[kid] = hash
cb()
get_key_manager : (kid) ->
if (key = @parsed_keys.get_nacl_key_manager kid)?
return key
if (hash = @_kid_to_hash[kid])?
return @parsed_keys.get_pgp_key_manager_with_hash kid, hash
return @parsed_keys.get_merged_pgp_key_manager kid
class ChainLink
@parse : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink.parse"
# Unbox the signed payload. PGP key expiration is checked automatically
# during unbox, using the ctime of the chainlink.
await @_unbox_payload {sig_blob, key_state, sig_cache}, esc defer payload, sig_id, payload_hash
# Check internal details of the payload, like uid length.
await check_link_payload_format {payload}, esc defer()
# Make sure the KID from the server matches the payload, and that any
# payload PGP fingerprint also matches the KID.
await @_check_payload_against_server_kid {sig_blob, payload, key_state}, esc defer()
# Check any reverse signatures. For links where we skip this step, we will
# ignore their contents later.
if not known_buggy_reverse_sigs[sig_id]
await @_check_reverse_signatures {payload, key_state}, esc defer()
# The constructor takes care of all the payload parsing that isn't failable.
cb null, new ChainLink {kid: sig_blob.kid, sig_id, payload, payload_hash}
@_unbox_payload : ({sig_blob, key_state, sig_cache}, cb) ->
esc = make_esc cb, "ChainLink._unbox_payload"
# Get the signing KID directly from the server blob. We'll confirm later
# that this is the same as the KID listed in the payload.
kid = sig_blob.kid
# Get the key_manager and sig_eng we need from the ParsedKeys object.
key_manager = key_state.get_key_manager kid
if not key_manager?
await athrow (new E.NonexistentKidError "link signed by nonexistent kid #{kid}"), esc defer()
sig_eng = key_manager.make_sig_eng()
# We need the signing ctime to verify the signature, and that's actually in
# the signed payload. So we fully parse the payload *before* verifying, and
# do the actual (maybe cached) verification at the end.
await sig_eng.get_body_and_unverified_payload(
{armored: sig_blob.sig}, esc defer sig_body, unverified_buffer)
sig_id = kbpgp.hash.SHA256(sig_body).toString("hex") + SIG_ID_SUFFIX
payload_json = unverified_buffer.toString('utf8')
await a_json_parse payload_json, esc defer payload
ctime_seconds = payload.ctime
# Now that we have the ctime, get the verified payload.
if sig_cache?
await sig_cache.get {sig_id}, esc defer verified_buffer
if not verified_buffer?
exports.debug.unbox_count++
await key_manager.make_sig_eng().unbox(
sig_blob.sig,
defer(err, verified_buffer),
{now: ctime_seconds})
if err?
await athrow (new E.VerifyFailedError err.message), esc defer()
if sig_cache?
await sig_cache.put {sig_id, payload_buffer: verified_buffer}, esc defer()
# Check that what we verified matches the unverified payload we used above.
# Ideally it should be impossible for there to be a difference, but this
# protects us from bugs/attacks that might exploit multiple payloads,
# particularly in PGP.
await check_buffers_equal verified_buffer, unverified_buffer, esc defer()
# Success!
# See comment above about bad whitespace sigs from 15 Sep 2015
hash_input = if bad_whitespace_sig_ids[sig_id] then strip_final_newline verified_buffer
else verified_buffer
payload_hash = kbpgp.hash.SHA256(hash_input).toString("hex")
cb null, payload, sig_id, payload_hash
@_check_payload_against_server_kid : ({sig_blob, payload, key_state}, cb) ->
# Here's where we check the data we relied on in @_unbox_payload().
signing_kid = sig_blob.kid
signing_fingerprint = key_state.get_key_manager(signing_kid).get_pgp_fingerprint()?.toString('hex')
payload_kid = payload.body.key.kid
payload_fingerprint = payload.body.key.fingerprint
err = null
if payload_kid? and payload_kid isnt signing_kid
err = new E.KidMismatchError "signing kid (#{signing_kid}) and payload kid (#{payload_kid}) mismatch"
else if payload_fingerprint? and payload_fingerprint isnt signing_fingerprint
err = new E.FingerprintMismatchError "signing fingerprint (#{signing_fingerprint}) and payload fingerprint (#{payload_fingerprint}) mismatch"
cb err
@_check_reverse_signatures : ({payload, key_state}, cb) ->
esc = make_esc cb, "ChainLink._check_reverse_signatures"
if payload.body.sibkey?
kid = payload.body.sibkey.kid
full_hash = payload.body.sibkey.full_hash
sibkey_key_manager = if full_hash?
# key_state hasn't been updated with the new sibkey's full hash yet
key_state.parsed_keys.get_pgp_key_manager_with_hash kid, full_hash
else
key_state.get_key_manager kid
if not sibkey_key_manager?
await athrow (new E.NonexistentKidError "link reverse-signed by nonexistent kid #{kid}"), esc defer()
sibkey_proof = new proofs.Sibkey {}
await sibkey_proof.reverse_sig_check {json: payload, subkm: sibkey_key_manager}, defer err
if err?
await athrow (new E.ReverseSigVerifyFailedError err.message), esc defer()
if payload.body.subkey?
kid = payload.body.subkey.kid
subkey_key_manager = key_state.get_key_manager kid
if not subkey_key_manager?
await athrow (new E.NonexistentKidError "link delegates nonexistent subkey #{kid}"), esc defer()
cb null
constructor : ({@kid, @sig_id, @payload, @payload_hash}) ->
@uid = @payload.body.key.uid
@username = @payload.body.key.username
@seqno = @payload.seqno
@prev = @payload.prev
# @fingerprint is PGP-only.
@fingerprint = @payload.body.key.fingerprint
# Not all links have the "eldest_kid" field, but if they don't, then their
# signing KID is implicitly the eldest.
@eldest_kid = @payload.body.key.eldest_kid or @kid
@ctime_seconds = @payload.ctime
@etime_seconds = @ctime_seconds + @payload.expire_in
@type = @payload.body.type
# Only expected to be set in eldest links
@signing_key_hash = @payload.body.key.full_hash
@sibkey_delegation = @payload.body.sibkey?.kid
@sibkey_hash = @payload.body.sibkey?.full_hash
@subkey_delegation = @payload.body.subkey?.kid
@pgp_update_kid = @payload.body.pgp_update?.kid
@pgp_update_hash = @payload.body.pgp_update?.full_hash
@key_revocations = []
if @payload.body.revoke?.kids?
@key_revocations = @payload.body.revoke.kids
if @payload.body.revoke?.kid?
@key_revocations.push(@payload.body.revoke.kid)
@sig_revocations = []
if @payload.body.revoke?.sig_ids?
@sig_revocations = @payload.body.revoke.sig_ids
if @payload.body.revoke?.sig_id?
@sig_revocations.push(@payload.body.revoke.sig_id)
# Exported for testing.
exports.check_link_payload_format = check_link_payload_format = ({payload}, cb) ->
esc = make_esc cb, "check_link_payload_format"
uid = payload.body.key.uid
if uid.length != UID_LEN
await athrow (new E.BadLinkFormatError "UID wrong length: #{uid.length}"), esc defer()
cb()
# Also exported for testing. This check will never fail under normal
# circumstances, so we need a test to explicitly make it fail.
exports.check_buffers_equal = check_buffers_equal = (verified_buffer, unverified_buffer, cb) ->
err = null
if not bufeq_secure(verified_buffer,unverified_buffer)
msg = """Payload mismatch!
Verified:
#{verified_buffer.toString('hex')}
Unverified:
#{unverified_buffer.toString('hex')}"""
err = new E.VerifyFailedError msg
cb err
exports.SigChain = class SigChain
# The replay() method is the main interface for all callers. It checks all of
# the user's signatures and returns a SigChain object representing their
# current state.
#
# @param {[string]} sig_blobs The parsed JSON signatures list returned from
# the server's sig/get.json endpoint.
# @param {ParsedKeys} parsed_keys The unverified collection of all the user's
# public keys. This is usually obtained from the all_bundles list given
# by user/lookup.json, passed to ParsedKeys.parse(). NaCl public key
# material is contained entirely within the KID, so technically all this
# extra data is only needed for PGP, but we treat both types of keys the
# same way for simplicity.
# @param {object} sig_cache An object with two methods: get({sig_id}, cb) and
# put({sig_id, payload_buffer}, cb), which caches the payloads of
# previously verified signatures. This parameter can be null, in which
# case all signatures will be checked.
# @param {string} uid Used only to check that the sigchain belongs to the
# right user.
# @param {string} username As with uid, used for confirming ownership.
# @param {string} eldest_kid The full (i.e. with-prefix) KID of the user's
# current eldest key. This is used to determine the latest subchain.
# @param {object} log An object with logging methods (debug, info, warn,
# error). May be null.
@replay : ({sig_blobs, parsed_keys, sig_cache, uid, username, eldest_kid, log}, cb) ->
log = log or (() ->)
log "+ libkeybase: replay(username: #{username}, uid: #{uid}, eldest: #{eldest_kid})"
esc = make_esc cb, "SigChain.replay"
# Forgetting the eldest KID would silently give you an empty sigchain. Prevent this.
if not eldest_kid?
await athrow (new Error "eldest_kid parameter is required"), esc defer()
# Initialize the SigChain.
sigchain = new SigChain {uid, username, eldest_kid, parsed_keys}
# Build the chain link by link, checking consistency all the way through.
for sig_blob in sig_blobs
log "| libkeybase: replaying signature #{sig_blob.seqno}: #{sig_blob.sig_id}"
await sigchain._add_new_link {sig_blob, sig_cache, log}, esc defer()
# If the eldest kid of the current subchain doesn't match the eldest kid
# we're looking for, that means we're on a new zero-length subchain.
if eldest_kid isnt sigchain._current_subchain_eldest
sigchain._reset_subchain(eldest_kid)
# After the chain is finished, make sure we've proven ownership of the
# eldest key in some way.
await sigchain._enforce_eldest_key_ownership {}, esc defer()
log "- libkeybase: replay finished"
cb null, sigchain
# NOTE: Don't call the constructor directly. Use SigChain.replay().
constructor : ({uid, username, eldest_kid, parsed_keys}) ->
@_uid = uid
@_username = username
@_eldest_kid = eldest_kid
@_parsed_keys = parsed_keys
@_next_seqno = 1
@_next_payload_hash = null
@_reset_subchain(null)
_reset_subchain : (current_subchain_eldest) ->
@_current_subchain = []
@_current_subchain_eldest = current_subchain_eldest
@_key_state = new KeyState {parsed_keys: @_parsed_keys}
@_unrevoked_links = {}
@_valid_sibkeys = {}
@_valid_sibkeys[current_subchain_eldest] = true
@_sibkey_order = [current_subchain_eldest]
@_valid_subkeys = {}
@_subkey_order = []
@_kid_to_etime_seconds = {}
@_update_kid_pgp_etime { kid: current_subchain_eldest }
# Return the list of links in the current subchain which have not been
# revoked.
get_links : () ->
return (link for link in @_current_subchain when link.sig_id of @_unrevoked_links)
# Return the list of sibkey KIDs which aren't revoked or expired.
get_sibkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_sibkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_sibkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
# Return the list of subkey KIDs which aren't revoked or expired.
get_subkeys : ({now}) ->
now = now or current_time_seconds()
ret = []
for kid in @_subkey_order
etime = @_kid_to_etime_seconds[kid]
expired = (etime? and now > etime)
if @_valid_subkeys[kid] and not expired
ret.push @_key_state.get_key_manager kid
ret
_add_new_link : ({sig_blob, sig_cache, log}, cb) ->
esc = make_esc cb, "SigChain._add_new_link"
# This constructor checks that the link is internally consistent: its
# signature is valid and belongs to the key it claims, and the same for any
# reverse sigs.
await ChainLink.parse {sig_blob, key_state: @_key_state, sig_cache}, esc defer link
log "| libkeybase: chain link parsed, type '#{link.payload.body.type}'"
# Make sure the link belongs in this chain (right username and uid) and at
# this particular point in the chain (right seqno and prev hash).
await @_check_link_belongs_here {link}, esc defer()
# Now see if we've hit a sigchain reset. That can happen for one of two
# reasons:
# 1) The eldest kid reported by this link (either explicitly or
# implicitly; see ChainLink.eldest_kid) is different from the one that
# came before it.
# 2) This link is of the "eldest" type.
# We *don't* short-circuit here though. Verifying past subchains just like
# we verify the current one actually simplifies PGP full hash handling.
# (Otherwise we'd have to figure out how to maintain the KeyState, or else
# we wouldn't even be able to verify link signatures [correctly, without
# resorting to key merging].)
if (link.eldest_kid isnt @_current_subchain_eldest or
link.type is "eldest" or
hardcoded_resets[link.sig_id])
log "| libkeybase: starting new subchain"
@_reset_subchain(link.eldest_kid)
# Links with known bad reverse sigs still have to have valid payload hashes
# and seqnos, but their contents are ignored, and their signing keys might
# not be valid sibkeys (because the delegating links of those sibkeys might
# also have been bad). Short-circuit here for these links, after checking
# the link position but before checking the validity of the signing key.
if known_buggy_reverse_sigs[link.sig_id]
cb null
return
# Finally, make sure that the key that signed this link was actually valid
# at the time the link was signed.
await @_check_key_is_valid {link}, esc defer()
log "| libkeybase: signing key is valid (#{link.kid})"
# This link is valid and part of the current subchain. Update all the
# relevant metadata.
@_current_subchain.push(link)
@_unrevoked_links[link.sig_id] = link
await @_delegate_keys {link, log}, esc defer()
await @_revoke_keys_and_sigs {link, log}, esc defer()
cb null
_check_link_belongs_here : ({link}, cb) ->
err = null
if link.uid isnt @_uid
err = new E.WrongUidError(
"Link doesn't refer to the right uid,
expected: #{link.uid} got: #{@_uid}")
else if link.username.toLowerCase() isnt @_username.toLowerCase()
err = new E.WrongUsernameError(
"Link doesn't refer to the right username,
expected: #{link.username} got: #{@_username}")
else if link.seqno isnt @_next_seqno
err = new E.WrongSeqnoError(
"Link sequence number is wrong, expected:
#{@_next_seqno} got: #{link.seqno}")
else if @_next_payload_hash? and link.prev isnt @_next_payload_hash
err = new E.WrongPrevError(
"Previous payload hash doesn't match,
expected: #{@_next_payload_hash} got: #{link.prev}")
@_next_seqno++
@_next_payload_hash = link.payload_hash
cb err
_check_key_is_valid : ({link}, cb) ->
err = null
if link.kid not of @_valid_sibkeys
err = new E.InvalidSibkeyError("not a valid sibkey: #{link.kid}, valid sibkeys:
#{JSON.stringify(kid for kid of @_valid_sibkeys)}")
else if link.ctime_seconds > @_kid_to_etime_seconds[link.kid]
err = new E.ExpiredSibkeyError "expired sibkey: #{link.kid}"
cb err
_delegate_keys : ({link, log}, cb) ->
esc = make_esc cb, 'SigChain._delegate_keys'
# If this is the first link in the subchain, it implicitly delegates the
# eldest key.
if @_current_subchain.length == 1
log "| libkeybase: delegating eldest key #{link.kid}"
await @_delegate_sibkey {
kid: link.kid
etime_seconds: link.etime_seconds
full_hash: link.signing_key_hash
}, esc defer()
if link.sibkey_delegation?
log "| libkeybase: delegating sibkey #{link.sibkey_delegation}"
await @_delegate_sibkey {
kid: link.sibkey_delegation
etime_seconds: link.etime_seconds
full_hash: link.sibkey_hash
}, esc defer()
if link.subkey_delegation?
log "| libkeybase: delegating subkey #{link.subkey_delegation}"
await @_delegate_subkey {
kid: link.subkey_delegation
etime_seconds: link.etime_seconds
}, esc defer()
# Handle pgp_update links.
if link.pgp_update_kid? and link.pgp_update_hash? and @_valid_sibkeys[link.pgp_update_kid]?
await @_key_state.set_key_hash {kid: link.pgp_update_kid, hash: link.pgp_update_hash}, esc defer()
cb()
_delegate_sibkey : ({kid, etime_seconds, full_hash}, cb) ->
esc = make_esc cb, 'SigChain._delegate_sibkey'
@_valid_sibkeys[kid] = true
if kid not in @_sibkey_order
@_sibkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
@_update_kid_pgp_etime { kid }
if full_hash?
await @_key_state.set_key_hash {kid, hash: full_hash}, esc defer()
cb null
_delegate_subkey : ({kid, etime_seconds}, cb) ->
esc = make_esc cb, 'SigChain._delegate_subkey'
@_valid_subkeys[kid] = true
if kid not in @_subkey_order
@_subkey_order.push kid
@_update_kid_etime { kid, etime_seconds }
# Subkeys are always NaCl, never PGP. So no full hash or pgp_etime stuff.
cb null
_update_kid_pgp_etime : ({kid}) ->
# PGP keys have an internal etime, which could be sooner than their link
# etime. If so, that's what we'll use.
key_manager = @_key_state.get_key_manager kid
lifespan = key_manager?.primary?.lifespan
if lifespan?.expire_in?
etime_seconds = lifespan.generated + lifespan.expire_in
@_update_kid_etime {kid, etime_seconds}
_update_kid_etime : ({kid, etime_seconds}) ->
# PGP keys can have two different etimes: the expiration time of their
# delegating chain link and the internal expiration time recorded by PGP.
# We believe the more restrictive of the two.
if not @_kid_to_etime_seconds[kid]?
@_kid_to_etime_seconds[kid] = etime_seconds
else
@_kid_to_etime_seconds[kid] = Math.min(etime_seconds, @_kid_to_etime_seconds[kid])
_revoke_keys_and_sigs : ({link, log}, cb) ->
# Handle direct sibkey revocations.
for kid in link.key_revocations
if kid of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{kid}"
delete @_valid_sibkeys[kid]
if kid of @_valid_subkeys
delete @_valid_subkeys[kid]
# Handle revocations of an entire link.
for sig_id in link.sig_revocations
if sig_id of @_unrevoked_links
revoked_link = @_unrevoked_links[sig_id]
delete @_unrevoked_links[sig_id]
# Keys delegated by the revoked link are implicitly revoked as well.
revoked_sibkey = revoked_link.sibkey_delegation
if revoked_sibkey? and revoked_sibkey of @_valid_sibkeys
log "| libkeybase: revoking sibkey #{revoked_sibkey} from sig #{sig_id}"
delete @_valid_sibkeys[revoked_sibkey]
revoked_subkey = revoked_link.subkey_delegation
if revoked_subkey? and revoked_subkey of @_valid_subkeys
delete @_valid_subkeys[revoked_subkey]
cb()
_enforce_eldest_key_ownership : ({}, cb) ->
# It's important that users actually *prove* they own their eldest key,
# rather than just claiming someone else's key as their own. The server
# normally enforces this, and here we check the server's work. Proof can
# happen in one of two ways: either the eldest key signs a link in the
# sigchain (thereby referencing the username in the signature payload), or
# the eldest key is a PGP key that self-signs its own identity.
esc = make_esc cb, "SigChain._enforce_eldest_key_ownership"
if @_current_subchain.length > 0
# There was at least one chain link signed by the eldest key.
cb null
return
# No chain link signed by the eldest key. Check PGP self sig.
eldest_km = @_key_state.get_key_manager @_eldest_kid
if not eldest_km?
# Server-reported eldest key is simply missing.
await athrow (new E.NonexistentKidError "no key for eldest kid #{@_eldest_kid}"), esc defer()
userids = eldest_km.get_userids_mark_primary()
if not userids?
# Server-reported key doesn't self-sign any identities (probably because
# it's a NaCl key and not a PGP key).
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not self-signing"), esc defer()
expected_email = @_username + "@keybase.io"
for identity in userids
if identity.get_email() == expected_email
# Found a matching identity. This key is good.
cb null
return
# No matching identity found.
await athrow (new E.KeyOwnershipError "key #{@_eldest_kid} is not owned by #{expected_email}"), esc defer()
error_names = [
"BAD_LINK_FORMAT"
"EXPIRED_SIBKEY"
"FINGERPRINT_MISMATCH"
"INVALID_SIBKEY"
"KEY_OWNERSHIP"
"KID_MISMATCH"
"NO_KEY_WITH_THIS_HASH"
"NONEXISTENT_KID"
"NOT_LATEST_SUBCHAIN"
"REVERSE_SIG_VERIFY_FAILED"
"VERIFY_FAILED"
"WRONG_UID"
"WRONG_USERNAME"
"WRONG_SEQNO"
"WRONG_PREV"
]
# make_errors() needs its input to be a map
errors_map = {}
for name in error_names
errors_map[name] = ""
exports.E = E = ie.make_errors errors_map
current_time_seconds = () ->
Math.floor(new Date().getTime() / 1000)
# Stupid coverage hack. If this breaks just delete it please, and I'm so sorry.
__iced_k_noop()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero G",
"end": 27,
"score": 0.6288893222808838,
"start": 20,
"tag": "NAME",
"value": "Pty Ltd"
},
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999121427536011,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/artist-page.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 { Tracklist } from 'tracklist'
reactTurbolinks.registerPersistent 'artistTracklist', Tracklist, true, (el) ->
tracks: osu.parseJson el.dataset.src
| 198727 | # Copyright (c) ppy <NAME> <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { Tracklist } from 'tracklist'
reactTurbolinks.registerPersistent 'artistTracklist', Tracklist, true, (el) ->
tracks: osu.parseJson el.dataset.src
| true | # Copyright (c) ppy PI:NAME:<NAME>END_PI <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 { Tracklist } from 'tracklist'
reactTurbolinks.registerPersistent 'artistTracklist', Tracklist, true, (el) ->
tracks: osu.parseJson el.dataset.src
|
[
{
"context": " password) ->\n @setName(name)\n @setPassword(password)\n $('#login-submit-btn').click()\n browser.w",
"end": 378,
"score": 0.9727783203125,
"start": 370,
"tag": "PASSWORD",
"value": "password"
}
] | app/specs/e2e/pages/home.coffee | asartalo/axya | 0 | 'use strict'
class HomePage extends require('./base')
constructor: ->
@pagePath = '/'
setName: (name) ->
$('#inputUsername').sendKeys(name)
setPassword: (password) ->
$('#inputPassword').sendKeys(password)
goToSignUp: ->
$('#signup-link').click()
browser.waitForAngular()
login: (name, password) ->
@setName(name)
@setPassword(password)
$('#login-submit-btn').click()
browser.waitForAngular()
module.exports = HomePage
| 32105 | 'use strict'
class HomePage extends require('./base')
constructor: ->
@pagePath = '/'
setName: (name) ->
$('#inputUsername').sendKeys(name)
setPassword: (password) ->
$('#inputPassword').sendKeys(password)
goToSignUp: ->
$('#signup-link').click()
browser.waitForAngular()
login: (name, password) ->
@setName(name)
@setPassword(<PASSWORD>)
$('#login-submit-btn').click()
browser.waitForAngular()
module.exports = HomePage
| true | 'use strict'
class HomePage extends require('./base')
constructor: ->
@pagePath = '/'
setName: (name) ->
$('#inputUsername').sendKeys(name)
setPassword: (password) ->
$('#inputPassword').sendKeys(password)
goToSignUp: ->
$('#signup-link').click()
browser.waitForAngular()
login: (name, password) ->
@setName(name)
@setPassword(PI:PASSWORD:<PASSWORD>END_PI)
$('#login-submit-btn').click()
browser.waitForAngular()
module.exports = HomePage
|
[
{
"context": "###\n * grunt-choose\n * https://github.com/leny/grunt-choose\n *\n * Copyright (c) 2014 Leny\n * Lic",
"end": 46,
"score": 0.9995312690734863,
"start": 42,
"tag": "USERNAME",
"value": "leny"
},
{
"context": "hub.com/leny/grunt-choose\n *\n * Copyright (c) 2014 Leny\n * Licensed under the MIT license.\n###\n\n\"use stri",
"end": 89,
"score": 0.9985319375991821,
"start": 85,
"tag": "NAME",
"value": "Leny"
}
] | Gruntfile.coffee | gruntjs-updater/grunt-choose | 0 | ###
* grunt-choose
* https://github.com/leny/grunt-choose
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
###
"use strict"
module.exports = ( grunt ) ->
require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks
grunt.initConfig
coffeelint:
options:
arrow_spacing:
level: "error"
camel_case_classes:
level: "error"
duplicate_key:
level: "error"
indentation:
level: "ignore"
max_line_length:
level: "ignore"
no_backticks:
level: "error"
no_empty_param_list:
level: "error"
no_stand_alone_at:
level: "error"
no_tabs:
level: "error"
no_throwing_strings:
level: "error"
no_trailing_semicolons:
level: "error"
no_unnecessary_fat_arrows:
level: "error"
space_operators:
level: "error"
task:
files:
src: [ "src/*.coffee" ]
coffee:
task:
files:
"tasks/choose.js": "src/choose.coffee"
watch:
server:
files: [
"src/*.coffee"
]
options:
nospawn: yes
tasks: [
"clear"
"newer:coffeelint:server"
"newer:coffee:server"
]
choose:
default_options: {}
custom_options:
options:
message: "Please, choose a task:"
multiple: yes
choices:
"Show me a message !": "message:one"
"Show me another message !": "message:two"
"Show me another, different message !": [
"message:three"
"message:four"
]
grunt.loadTasks "tasks"
grunt.registerTask "message", "Display a message", ( arg ) ->
grunt.log.writeln switch( arg )
when "one" then "Hey ! This is task message:one !"
when "two" then "Hey ! This is task message:two !"
when "three" then "Hey ! This is task message:three !"
when "four" then "Hey ! This is task message:four !"
when "five" then "Hey ! This is task message:five !"
else "Hey ! This is task message:default !"
grunt.registerTask "default", [
"clear"
"coffeelint"
"coffee"
]
| 104774 | ###
* grunt-choose
* https://github.com/leny/grunt-choose
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
"use strict"
module.exports = ( grunt ) ->
require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks
grunt.initConfig
coffeelint:
options:
arrow_spacing:
level: "error"
camel_case_classes:
level: "error"
duplicate_key:
level: "error"
indentation:
level: "ignore"
max_line_length:
level: "ignore"
no_backticks:
level: "error"
no_empty_param_list:
level: "error"
no_stand_alone_at:
level: "error"
no_tabs:
level: "error"
no_throwing_strings:
level: "error"
no_trailing_semicolons:
level: "error"
no_unnecessary_fat_arrows:
level: "error"
space_operators:
level: "error"
task:
files:
src: [ "src/*.coffee" ]
coffee:
task:
files:
"tasks/choose.js": "src/choose.coffee"
watch:
server:
files: [
"src/*.coffee"
]
options:
nospawn: yes
tasks: [
"clear"
"newer:coffeelint:server"
"newer:coffee:server"
]
choose:
default_options: {}
custom_options:
options:
message: "Please, choose a task:"
multiple: yes
choices:
"Show me a message !": "message:one"
"Show me another message !": "message:two"
"Show me another, different message !": [
"message:three"
"message:four"
]
grunt.loadTasks "tasks"
grunt.registerTask "message", "Display a message", ( arg ) ->
grunt.log.writeln switch( arg )
when "one" then "Hey ! This is task message:one !"
when "two" then "Hey ! This is task message:two !"
when "three" then "Hey ! This is task message:three !"
when "four" then "Hey ! This is task message:four !"
when "five" then "Hey ! This is task message:five !"
else "Hey ! This is task message:default !"
grunt.registerTask "default", [
"clear"
"coffeelint"
"coffee"
]
| true | ###
* grunt-choose
* https://github.com/leny/grunt-choose
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
"use strict"
module.exports = ( grunt ) ->
require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks
grunt.initConfig
coffeelint:
options:
arrow_spacing:
level: "error"
camel_case_classes:
level: "error"
duplicate_key:
level: "error"
indentation:
level: "ignore"
max_line_length:
level: "ignore"
no_backticks:
level: "error"
no_empty_param_list:
level: "error"
no_stand_alone_at:
level: "error"
no_tabs:
level: "error"
no_throwing_strings:
level: "error"
no_trailing_semicolons:
level: "error"
no_unnecessary_fat_arrows:
level: "error"
space_operators:
level: "error"
task:
files:
src: [ "src/*.coffee" ]
coffee:
task:
files:
"tasks/choose.js": "src/choose.coffee"
watch:
server:
files: [
"src/*.coffee"
]
options:
nospawn: yes
tasks: [
"clear"
"newer:coffeelint:server"
"newer:coffee:server"
]
choose:
default_options: {}
custom_options:
options:
message: "Please, choose a task:"
multiple: yes
choices:
"Show me a message !": "message:one"
"Show me another message !": "message:two"
"Show me another, different message !": [
"message:three"
"message:four"
]
grunt.loadTasks "tasks"
grunt.registerTask "message", "Display a message", ( arg ) ->
grunt.log.writeln switch( arg )
when "one" then "Hey ! This is task message:one !"
when "two" then "Hey ! This is task message:two !"
when "three" then "Hey ! This is task message:three !"
when "four" then "Hey ! This is task message:four !"
when "five" then "Hey ! This is task message:five !"
else "Hey ! This is task message:default !"
grunt.registerTask "default", [
"clear"
"coffeelint"
"coffee"
]
|
[
{
"context": "s.twitter.consumerSecret\n access_token_key: tok\n access_token_secret: tokSec\n )\n\n# just",
"end": 657,
"score": 0.6528001427650452,
"start": 654,
"tag": "KEY",
"value": "tok"
},
{
"context": "access_token_key: tok\n access_token_secret: tokSec\n )\n\n# just to check if it works\nverifyCredenti",
"end": 693,
"score": 0.9147146344184875,
"start": 687,
"tag": "KEY",
"value": "tokSec"
}
] | src/lib/twitterAPI.coffee | sharismlab/social-brain-framework | 2 | # Here is stored all logic related to twitter API requests
# We use nTwitter module to fetch data from twitter
s = null
tok =null
tokSec=null
# create a ntwitter element
ntwitter = require 'ntwitter'
apikeys = require '../../config/apikeys'
# declare global vars
ntwit = null
#import seuron controller
# seurons_controller = require '../controllers/seurons_controller'
# use logged in user credentials to process requests
loginToTwitter = (tok, tokSec) ->
console.log tok, tokSec
ntwit = new ntwitter (
consumer_key: apikeys.twitter.consumerKey
consumer_secret: apikeys.twitter.consumerSecret
access_token_key: tok
access_token_secret: tokSec
)
# just to check if it works
verifyCredentials = () ->
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
ntwit.get url, null, (err,data) ->
console.log err if err
console.log(data);
return
#
getFollowers = (seuron, callback) ->
if( seuron.sns.twitter.hasFollowers.check == false || seuron.sns.twitter.hasFollowers.last_updated < Date.now+30000)
console.log "get followers !"
ntwit.getFollowersIds seuron.sns.twitter.id, (err, data) ->
console.log err if err
seuron.sns.twitter.followers = data
seuron.sns.twitter.hasFollowers.check = true
seuron.sns.twitter.hasFollowers.last_updated = new Date
seuron.save (d) ->
callback
getFriends = (seuron, callback) ->
if( seuron.sns.twitter.hasFriends.check == false || seuron.sns.twitter.hasFriends.last_updated < Date.now+30000)
ntwit.getFriendsIds seuron.sns.twitter.id, (err,data) ->
console.log err if err
console.log "get friends !"
seuron.sns.twitter.friends = data
seuron.sns.twitter.hasFriends.check = true
seuron.sns.twitter.hasFriends.last_updated = new Date
seuron.save (d) ->
callback
# Now let's get timeline and mentions
getTimeline = (callback) ->
console.log "(get twitter timeline)"
ntwit.getUserTimeline {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
getMentions = (callback) ->
console.log "(get twitter mentions)"
ntwit.get "/statuses/mentions_timeline.json", {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
lookupUsers = (ids, callback) ->
console.log "need some users dude?"
ntwit.lookupUsers ids, (err, data) ->
console.log err if err
console.log "you've got "+data.length+ "users..."
callback data
# export methods
module.exports =
ntwit : ntwit
loginToTwitter : loginToTwitter
verifyCredentials : verifyCredentials
getFriends : getFriends
getFollowers : getFollowers
getTimeline : getTimeline
getMentions : getMentions
lookupUsers : lookupUsers | 26023 | # Here is stored all logic related to twitter API requests
# We use nTwitter module to fetch data from twitter
s = null
tok =null
tokSec=null
# create a ntwitter element
ntwitter = require 'ntwitter'
apikeys = require '../../config/apikeys'
# declare global vars
ntwit = null
#import seuron controller
# seurons_controller = require '../controllers/seurons_controller'
# use logged in user credentials to process requests
loginToTwitter = (tok, tokSec) ->
console.log tok, tokSec
ntwit = new ntwitter (
consumer_key: apikeys.twitter.consumerKey
consumer_secret: apikeys.twitter.consumerSecret
access_token_key: <KEY>
access_token_secret: <KEY>
)
# just to check if it works
verifyCredentials = () ->
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
ntwit.get url, null, (err,data) ->
console.log err if err
console.log(data);
return
#
getFollowers = (seuron, callback) ->
if( seuron.sns.twitter.hasFollowers.check == false || seuron.sns.twitter.hasFollowers.last_updated < Date.now+30000)
console.log "get followers !"
ntwit.getFollowersIds seuron.sns.twitter.id, (err, data) ->
console.log err if err
seuron.sns.twitter.followers = data
seuron.sns.twitter.hasFollowers.check = true
seuron.sns.twitter.hasFollowers.last_updated = new Date
seuron.save (d) ->
callback
getFriends = (seuron, callback) ->
if( seuron.sns.twitter.hasFriends.check == false || seuron.sns.twitter.hasFriends.last_updated < Date.now+30000)
ntwit.getFriendsIds seuron.sns.twitter.id, (err,data) ->
console.log err if err
console.log "get friends !"
seuron.sns.twitter.friends = data
seuron.sns.twitter.hasFriends.check = true
seuron.sns.twitter.hasFriends.last_updated = new Date
seuron.save (d) ->
callback
# Now let's get timeline and mentions
getTimeline = (callback) ->
console.log "(get twitter timeline)"
ntwit.getUserTimeline {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
getMentions = (callback) ->
console.log "(get twitter mentions)"
ntwit.get "/statuses/mentions_timeline.json", {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
lookupUsers = (ids, callback) ->
console.log "need some users dude?"
ntwit.lookupUsers ids, (err, data) ->
console.log err if err
console.log "you've got "+data.length+ "users..."
callback data
# export methods
module.exports =
ntwit : ntwit
loginToTwitter : loginToTwitter
verifyCredentials : verifyCredentials
getFriends : getFriends
getFollowers : getFollowers
getTimeline : getTimeline
getMentions : getMentions
lookupUsers : lookupUsers | true | # Here is stored all logic related to twitter API requests
# We use nTwitter module to fetch data from twitter
s = null
tok =null
tokSec=null
# create a ntwitter element
ntwitter = require 'ntwitter'
apikeys = require '../../config/apikeys'
# declare global vars
ntwit = null
#import seuron controller
# seurons_controller = require '../controllers/seurons_controller'
# use logged in user credentials to process requests
loginToTwitter = (tok, tokSec) ->
console.log tok, tokSec
ntwit = new ntwitter (
consumer_key: apikeys.twitter.consumerKey
consumer_secret: apikeys.twitter.consumerSecret
access_token_key: PI:KEY:<KEY>END_PI
access_token_secret: PI:KEY:<KEY>END_PI
)
# just to check if it works
verifyCredentials = () ->
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
ntwit.get url, null, (err,data) ->
console.log err if err
console.log(data);
return
#
getFollowers = (seuron, callback) ->
if( seuron.sns.twitter.hasFollowers.check == false || seuron.sns.twitter.hasFollowers.last_updated < Date.now+30000)
console.log "get followers !"
ntwit.getFollowersIds seuron.sns.twitter.id, (err, data) ->
console.log err if err
seuron.sns.twitter.followers = data
seuron.sns.twitter.hasFollowers.check = true
seuron.sns.twitter.hasFollowers.last_updated = new Date
seuron.save (d) ->
callback
getFriends = (seuron, callback) ->
if( seuron.sns.twitter.hasFriends.check == false || seuron.sns.twitter.hasFriends.last_updated < Date.now+30000)
ntwit.getFriendsIds seuron.sns.twitter.id, (err,data) ->
console.log err if err
console.log "get friends !"
seuron.sns.twitter.friends = data
seuron.sns.twitter.hasFriends.check = true
seuron.sns.twitter.hasFriends.last_updated = new Date
seuron.save (d) ->
callback
# Now let's get timeline and mentions
getTimeline = (callback) ->
console.log "(get twitter timeline)"
ntwit.getUserTimeline {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
getMentions = (callback) ->
console.log "(get twitter mentions)"
ntwit.get "/statuses/mentions_timeline.json", {"include_rts": true,"include_entities" : true, "count":200 }, (err,data) ->
console.log err if err
# console.log data
callback(data)
lookupUsers = (ids, callback) ->
console.log "need some users dude?"
ntwit.lookupUsers ids, (err, data) ->
console.log err if err
console.log "you've got "+data.length+ "users..."
callback data
# export methods
module.exports =
ntwit : ntwit
loginToTwitter : loginToTwitter
verifyCredentials : verifyCredentials
getFriends : getFriends
getFollowers : getFollowers
getTimeline : getTimeline
getMentions : getMentions
lookupUsers : lookupUsers |
[
{
"context": "# parsing Python code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 59,
"score": 0.9998612999916077,
"start": 45,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "n code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 73,
"score": 0.8799600005149841,
"start": 65,
"tag": "USERNAME",
"value": "Outsider"
}
] | src/parser/python-parser.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # parsing Python code
#
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
jsParser = module.exports =
lang: 'py'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.imports line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def long_function_name(var_one):
# use tab for indentation
print(var_one)
"""
}
{
key: "space", display: "Space",
code: """
def long_function_name(var_one):
print(var_one)
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
imports: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.imports =
title: "Imports on separate lines"
column: [
{
key: "separated", display: "Imports on separate lines",
code: """
import os
import sys
"""
}
{
key: "noseparated", display: "Import on non-separate lines",
code: """
import sys, os
"""
}
]
separated: 0
noseparated: 0
commits: []
) unless convention.imports
separated = /^\s*\t*import\s+[\w.]+([^,]\s*|\s*#.*)$/
noseparated = /^\s*\t*import\s+\w+\s*,\s+\w+/
convention.imports.separated = convention.imports.separated + 1 if separated.test line
convention.imports.noseparated = convention.imports.noseparated + 1 if noseparated.test line
convention.imports.commits.push commitUrl if separated.test(line) or noseparated.test(line)
convention.imports.commits = _.uniq convention.imports.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace in Expressions and Statements"
column: [
{
key: "noextra", display: "Avoiding extraneous whitespace",
code: """
spam(ham[1], {eggs: 2})
if x == 4: print x, y; x, y = y, x
spam(1)
dict['key'] = list[index]
x = 1
y = 2
long_variable = 3
"""
}
{
key: "extra", display: "Using extraneous whitespace",
code: """
spam( ham[ 1 ], { eggs: 2 } )
if x == 4 : print x , y ; x , y = y , x
spam (1)
dict ['key'] = list [index]
x = 1
y = 2
long_variable = 3
"""
}
]
noextra: 0
extra: 0
commits: []
) unless convention.whitespace
noextra = /\S+[\(\)\[\],]\S+|\S+:\s|\S\s=\s/
extra = /\(\s+|\s+[\(\)\[\]]|\s+[:,]\s+|\s{2,}=|=\s{2,}/
if extra.test line
convention.whitespace.extra = convention.whitespace.extra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
else if noextra.test line
convention.whitespace.noextra = convention.whitespace.noextra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
| 109081 | # parsing Python code
#
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
jsParser = module.exports =
lang: 'py'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.imports line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def long_function_name(var_one):
# use tab for indentation
print(var_one)
"""
}
{
key: "space", display: "Space",
code: """
def long_function_name(var_one):
print(var_one)
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
imports: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.imports =
title: "Imports on separate lines"
column: [
{
key: "separated", display: "Imports on separate lines",
code: """
import os
import sys
"""
}
{
key: "noseparated", display: "Import on non-separate lines",
code: """
import sys, os
"""
}
]
separated: 0
noseparated: 0
commits: []
) unless convention.imports
separated = /^\s*\t*import\s+[\w.]+([^,]\s*|\s*#.*)$/
noseparated = /^\s*\t*import\s+\w+\s*,\s+\w+/
convention.imports.separated = convention.imports.separated + 1 if separated.test line
convention.imports.noseparated = convention.imports.noseparated + 1 if noseparated.test line
convention.imports.commits.push commitUrl if separated.test(line) or noseparated.test(line)
convention.imports.commits = _.uniq convention.imports.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace in Expressions and Statements"
column: [
{
key: "noextra", display: "Avoiding extraneous whitespace",
code: """
spam(ham[1], {eggs: 2})
if x == 4: print x, y; x, y = y, x
spam(1)
dict['key'] = list[index]
x = 1
y = 2
long_variable = 3
"""
}
{
key: "extra", display: "Using extraneous whitespace",
code: """
spam( ham[ 1 ], { eggs: 2 } )
if x == 4 : print x , y ; x , y = y , x
spam (1)
dict ['key'] = list [index]
x = 1
y = 2
long_variable = 3
"""
}
]
noextra: 0
extra: 0
commits: []
) unless convention.whitespace
noextra = /\S+[\(\)\[\],]\S+|\S+:\s|\S\s=\s/
extra = /\(\s+|\s+[\(\)\[\]]|\s+[:,]\s+|\s{2,}=|=\s{2,}/
if extra.test line
convention.whitespace.extra = convention.whitespace.extra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
else if noextra.test line
convention.whitespace.noextra = convention.whitespace.noextra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
| true | # parsing Python code
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
jsParser = module.exports =
lang: 'py'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.imports line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def long_function_name(var_one):
# use tab for indentation
print(var_one)
"""
}
{
key: "space", display: "Space",
code: """
def long_function_name(var_one):
print(var_one)
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
imports: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.imports =
title: "Imports on separate lines"
column: [
{
key: "separated", display: "Imports on separate lines",
code: """
import os
import sys
"""
}
{
key: "noseparated", display: "Import on non-separate lines",
code: """
import sys, os
"""
}
]
separated: 0
noseparated: 0
commits: []
) unless convention.imports
separated = /^\s*\t*import\s+[\w.]+([^,]\s*|\s*#.*)$/
noseparated = /^\s*\t*import\s+\w+\s*,\s+\w+/
convention.imports.separated = convention.imports.separated + 1 if separated.test line
convention.imports.noseparated = convention.imports.noseparated + 1 if noseparated.test line
convention.imports.commits.push commitUrl if separated.test(line) or noseparated.test(line)
convention.imports.commits = _.uniq convention.imports.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace in Expressions and Statements"
column: [
{
key: "noextra", display: "Avoiding extraneous whitespace",
code: """
spam(ham[1], {eggs: 2})
if x == 4: print x, y; x, y = y, x
spam(1)
dict['key'] = list[index]
x = 1
y = 2
long_variable = 3
"""
}
{
key: "extra", display: "Using extraneous whitespace",
code: """
spam( ham[ 1 ], { eggs: 2 } )
if x == 4 : print x , y ; x , y = y , x
spam (1)
dict ['key'] = list [index]
x = 1
y = 2
long_variable = 3
"""
}
]
noextra: 0
extra: 0
commits: []
) unless convention.whitespace
noextra = /\S+[\(\)\[\],]\S+|\S+:\s|\S\s=\s/
extra = /\(\s+|\s+[\(\)\[\]]|\s+[:,]\s+|\s{2,}=|=\s{2,}/
if extra.test line
convention.whitespace.extra = convention.whitespace.extra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
else if noextra.test line
convention.whitespace.noextra = convention.whitespace.noextra + 1
convention.whitespace.commits.push commitUrl
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
|
[
{
"context": " # get (callback)\n # Get metrics\n # - username: the user id\n # - callback: the callback function, callback(e",
"end": 87,
"score": 0.978050172328949,
"start": 76,
"tag": "USERNAME",
"value": "the user id"
},
{
"context": "estamp ] = data.key.split \":\"\n if username == dataUsername\n # push new object with id, timestamp and ",
"end": 422,
"score": 0.9937591552734375,
"start": 410,
"tag": "USERNAME",
"value": "dataUsername"
},
{
"context": "iven metrics\n # - id: metric's id\n # - username: the user id\n # - callback: the callback function, callback(e",
"end": 820,
"score": 0.9987647533416748,
"start": 809,
"tag": "USERNAME",
"value": "the user id"
},
{
"context": "esponding id\n if dataId == id and username == dataUsername\n # push new object with id, timestamp and ",
"end": 1227,
"score": 0.997913122177124,
"start": 1215,
"tag": "USERNAME",
"value": "dataUsername"
},
{
"context": ": an array of { timestamp, value }\n # - username: the user id\n # - callback: the callback function\n save: (id",
"end": 1679,
"score": 0.9992122054100037,
"start": 1668,
"tag": "USERNAME",
"value": "the user id"
},
{
"context": "ue } = metric\n ws.write \n key: \"metric:#{username}:#{id}:#{timestamp}\"\n value: valu",
"end": 1964,
"score": 0.6104467511177063,
"start": 1963,
"tag": "KEY",
"value": "#"
},
{
"context": "ic\n ws.write \n key: \"metric:#{username}:#{id}:#{timestamp}\"\n value: value\n ws.end",
"end": 1976,
"score": 0.5941014289855957,
"start": 1975,
"tag": "KEY",
"value": "#"
},
{
"context": " ws.write \n key: \"metric:#{username}:#{id}:#{timestamp}\"\n value: value\n ws.end()\n ",
"end": 1980,
"score": 0.6730425953865051,
"start": 1977,
"tag": "KEY",
"value": "id}"
},
{
"context": "Table == 'metric' and dataId == id and username == dataUsername\n # Add the key to the list of items to del",
"end": 2596,
"score": 0.9478644132614136,
"start": 2584,
"tag": "USERNAME",
"value": "dataUsername"
},
{
"context": "id}\"\n if keyTable == 'metric' and username == dataUsername\n # Add the key to the list of items to del",
"end": 3589,
"score": 0.9044389724731445,
"start": 3577,
"tag": "USERNAME",
"value": "dataUsername"
}
] | src/back/metrics.coffee | ThomasCharuel/ece_ast_project | 0 | module.exports = (db) ->
# get (callback)
# Get metrics
# - username: the user id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
if username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# getById (id, callback)
# Get given metrics
# - id: metric's id
# - username: the user id
# - callback: the callback function, callback(err, data)
getById: (id, username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data and if correct id, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
# if corresponding id
if dataId == id and username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# save (id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - username: the user id
# - callback: the callback function
save: (id, metrics, username, callback) ->
ws = db.createWriteStream()
ws.on 'error', (err) -> callback err
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metric:#{username}:#{id}:#{timestamp}"
value: value
ws.end()
# deleteById (id, callback)
# Delete given metrics
# - id: metric id
# - username: the user id
# - callback: the callback function
delete: (id, username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername, dataId ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and dataId == id and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
# deleteByUsername (username, callback)
# Delete given metrics
# - username: the user id
# - callback: the callback function
deleteByUsername: (username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
| 105054 | module.exports = (db) ->
# get (callback)
# Get metrics
# - username: the user id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
if username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# getById (id, callback)
# Get given metrics
# - id: metric's id
# - username: the user id
# - callback: the callback function, callback(err, data)
getById: (id, username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data and if correct id, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
# if corresponding id
if dataId == id and username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# save (id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - username: the user id
# - callback: the callback function
save: (id, metrics, username, callback) ->
ws = db.createWriteStream()
ws.on 'error', (err) -> callback err
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metric:<KEY>{username}:<KEY>{<KEY>:#{timestamp}"
value: value
ws.end()
# deleteById (id, callback)
# Delete given metrics
# - id: metric id
# - username: the user id
# - callback: the callback function
delete: (id, username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername, dataId ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and dataId == id and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
# deleteByUsername (username, callback)
# Delete given metrics
# - username: the user id
# - callback: the callback function
deleteByUsername: (username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
| true | module.exports = (db) ->
# get (callback)
# Get metrics
# - username: the user id
# - callback: the callback function, callback(err, data)
get: (username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
if username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# getById (id, callback)
# Get given metrics
# - id: metric's id
# - username: the user id
# - callback: the callback function, callback(err, data)
getById: (id, username, callback) ->
# result array
res = []
rs = db.createReadStream()
# on data and if correct id, add the data to the result array
rs.on 'data', (data) ->
[ ..., dataUsername, dataId, dataTimestamp ] = data.key.split ":"
# if corresponding id
if dataId == id and username == dataUsername
# push new object with id, timestamp and value properties
res.push
id: dataId
timestamp: dataTimestamp
value: data.value
rs.on 'error', (err) -> callback err
# on stream end, return the result
rs.on 'end', () ->
callback null, res
# save (id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - username: the user id
# - callback: the callback function
save: (id, metrics, username, callback) ->
ws = db.createWriteStream()
ws.on 'error', (err) -> callback err
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metric:PI:KEY:<KEY>END_PI{username}:PI:KEY:<KEY>END_PI{PI:KEY:<KEY>END_PI:#{timestamp}"
value: value
ws.end()
# deleteById (id, callback)
# Delete given metrics
# - id: metric id
# - username: the user id
# - callback: the callback function
delete: (id, username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername, dataId ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and dataId == id and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
# deleteByUsername (username, callback)
# Delete given metrics
# - username: the user id
# - callback: the callback function
deleteByUsername: (username, callback) ->
# array of keys for db items to delete
keys = []
rs = db.createKeyStream()
rs.on 'error', (err) -> callback err
rs.on 'data', (key) ->
# Split the key
[ keyTable, dataUsername ] = key.split ":"
# add the key to the key array if the key starts with "metric:{id}"
if keyTable == 'metric' and username == dataUsername
# Add the key to the list of items to delete
keys.push key
# When every key has been streamed
rs.on 'end', () ->
# Open new stream to delete items
ws = db.createWriteStream
type: 'del'
ws.on 'error', (err) -> callback err
ws.on 'close', callback
# For each key of items to delete
for key in keys
# Delete the item
ws.write
key: key
ws.end()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.