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": "# jquery.popLockIt\n# https://github.com/zamiang/jquery.popLockIt\n#\n# A jQuery plugin for 'locking",
"end": 47,
"score": 0.9995253682136536,
"start": 40,
"tag": "USERNAME",
"value": "zamiang"
},
{
"context": "ssay or series\n# of images.\n#\n# Copyright (c) 2013 Brenn... | src/poplockit.coffee | zamiang/jquery.poplockit | 19 | # jquery.popLockIt
# https://github.com/zamiang/jquery.popLockIt
#
# A jQuery plugin for 'locking' short content in place as the user
# scrolls by longer content. For example, it will lock metadata and
# share buttons in place as the user scrolls by a long essay or series
# of images.
#
# Copyright (c) 2013 Brennan Moore, Artsy
# Licensed under the MIT license.
#
# DOM STRUCTURE:
# Feed
# -- FeedItem
# ---- Column
# ---- Column
# ---- Column
# -- FeedItem
# ---- Column
# ...
(($, window, document) ->
pluginName = "popLockIt"
class Base
requires: []
constructor: (@$el, @settings) ->
for require in @requires
throw "You must pass #{require}" unless @settings[require]?
class Column extends Base
requires: ['height', 'marginTop', 'marginLeft', 'marginBottom']
cssProperties: ['position', 'top', 'bottom', 'left']
# defaults
marginTop: 0
marginBottom: 0
marginLeft: 0
parentHeight: 0
height: 0
top: 0
bottom: 0
left: 0
constructor: (@$el, @settings) ->
@
setMargins: (settings) ->
@parentHeight = settings.parentHeight if settings.parentHeight
@marginTop = settings.marginTop if settings.marginTop
@marginBottom = settings.marginBottom if settings.marginBottom
@marginLeft = settings.marginLeft if settings.marginLeft
setDimensions: ->
@height = Math.floor Number(@$el.css('height').replace('px',""))
@top = Math.floor(@$el.offset().top - @marginTop)
@left = Math.floor(@$el.offset().left)
@bottom = Math.floor(@top + @parentHeight - @height)
@top = 1 if @top < 1
setPosition: (pos = 'absolute', direction = 'north') ->
newState =
position : pos
left : Math.round(@getLeftForPosition(pos))
if pos == 'absolute'
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then @marginBottom else 'auto'
else
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then 0 else 'auto'
# first time around we have nothing to diff and want to apply the entire changeset
unless @oldState
@$el.css newState
return @oldState = newState
diff = {}
changed = false
for prop in @cssProperties
if newState[prop] != @oldState[prop]
diff[prop] = newState[prop]
changed = true
if changed
@$el.css diff
@oldState = newState
getLeftForPosition: (pos) ->
if pos == 'fixed'
@left
else if pos == 'static'
0
else
@left - @marginLeft
onScroll: (scrollTop, viewportHeight, preventFixed=false, scrollDirection) ->
if !preventFixed
if @height == viewportHeight
if (scrollTop < @top + @parentHeight - @height)
return @setPosition('fixed', 'north')
return @setPosition('absolute', 'south')
else if @height < viewportHeight
return @setPosition('fixed', 'north') if scrollTop >= @top and scrollTop < @top + @parentHeight - @height
return @setPosition('absolute', 'south')
return @setPosition('fixed', 'south') if @height > viewportHeight and @height < @parentHeight and (scrollTop + viewportHeight) >= (@top + @height) and (scrollTop + viewportHeight) < (@parentHeight + @top)
if @height >= viewportHeight
if scrollTop >= @top + @height
return @setPosition('absolute', 'south')
@setPosition('absolute', 'north')
# return to default state on destroy
destroy: -> @setPosition()
class FeedItem extends Base
requires: ['columnSelector']
active: false
columns: []
constructor: (@$el, @settings, @index, @parent) ->
super
@$columns = @$el.find @settings.columnSelector
if @hasColumns()
@setDimensions()
@createColumns()
@settings.additionalFeedItemInit(@$el, @index) if @settings.additionalFeedItemInit
@
createColumns: ->
@columns = @$columns.map -> new Column($(this))
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setDimensions: ->
# accomodate for when feed items have different padding
@marginTop = Number(@$el.css('padding-top').replace('px', ''))
@marginBottom = Number(@$el.css('padding-bottom').replace('px', ''))
@resetColumnPositioning()
@$el.css height: 'auto'
height = @$el.css('height')
@height = Number(height.replace('px',""))
@$el.css
height: height
@left = @$el.offset().left
@top = @$el.offset().top
@bottom = @top + @height
onScroll: (scrollTop, viewportHeight, forceOnScroll) ->
# only trigger onscroll for columns if the feeditem is visible in the viewport
if viewportHeight >= @height
@active = false
else if scrollTop >= @top and scrollTop < @bottom
@active = true
column.onScroll(scrollTop, viewportHeight, @parent.settings.preventFixed) for column in @columns
else if @active
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
@active = false
else if forceOnScroll
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
recompute: ->
@setDimensions()
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setColumnMargins: (column) ->
column.setMargins
parentHeight : @height
marginTop : @marginTop
marginBottom : @marginBottom
marginLeft : @left
recomputeColumn: (index) ->
return unless !@columns[index]
@setColumnMargins @columns[index]
resetColumnPositioning: -> column.setPosition('static') for column in @columns
destroy: -> column.destroy() for column in @columns
hasColumns: -> @$columns?.length > 1
class Feed extends Base
feedItems: []
requires: ['feedItems']
hasFocus: true
scrollSpeedThreshold: 500
defaults:
active: true
rendered: false
preventFixed: false
constructor: (@el, @settings) ->
@$el = $(@el)
throw "You must pass settings" unless @settings?
throw "PopLockIt must be called on one element" unless @$el?.length == 1
super(@$el, @settings)
@$window = $(window)
@settings = $.extend @defaults, @settings
@settings.active = true
@initRequestAnimationFrame()
@viewportHeight = @$window.outerHeight(true)
@$el.css
'box-sizing': 'border-box' # to make dimensions measurements consistent across different sites
overflow : 'hidden'
@addFeedItems @settings.feedItems
@requestAnimationFrame()
@
onScroll: ->
return unless @settings.active
scrollTop = @$window.scrollTop()
if scrollTop == @previousScrollTop
return @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
for item in @feedItems
# run onscroll for all feeditems if scrolltop is very different from prev scroll top (user scrolled very fast)
item.onScroll(scrollTop, @viewportHeight, Math.abs(scrollTop - @previousScrollTop) > @scrollSpeedThreshold)
@previousScrollTop = scrollTop
# run onscroll cont
@settings.onScroll(scrollTop) if @settings.onScroll?
@requestAnimationFrame()
# recomputes height / top / bottom etc of each feed item and its columns
recompute: ->
@settings.active = true
feedItem.recompute() for feedItem in @feedItems
scrollTop = @$window.scrollTop()
for item in @feedItems
item.onScroll scrollTop, @viewportHeight, false
recomputeItem: (index) ->
return unless @feedItems[index]
@feedItems[index].recompute()
recomputeItemColumn: (index, columnIndex) ->
return unless @feedItems[index]
@feedItems[index].recomputeColumn columnIndex
destroy: ->
@settings.rendered = false
@settings.active = false
$.data @$el, "plugin_#{pluginName}", false
if feedItems?.length
item.destroy() for item in @feedItems
@feedItems = []
stop: ->
@settings.active = false
window.cancelAnimationFrame @requestedAnimationFrame
start: ->
@settings.active = true
window.cancelAnimationFrame @requestedAnimationFrame
@requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
addFeedItems: ($feedItems) ->
throw "You must pass $feedItems" unless $feedItems? and $feedItems.length
# jQuery map - returns a $(array) instead of a real array
$feedItems.map (index, el) =>
@feedItems.push(new FeedItem $(el), @settings, index, @)
requestAnimationFrame: -> @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# requestAnimationFrame polyfill by Erik Moller
# fixes from Paul Irish and Tino Zijdel
initRequestAnimationFrame: ->
return if window.requestAnimationFrame
lastTime = 0
vendors = ['ms', 'moz', 'webkit', 'o']
for vendor in vendors when not window.requestAnimationFrame
window.requestAnimationFrame = window["#{vendor}RequestAnimationFrame"]
window.cancelAnimationFrame = window["{vendor}CancelAnimationFrame"] or window["{vendors}CancelRequestAnimationFrame"]
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) -> clearTimeout(id)
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new Feed(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.popLockIt"
)(jQuery, window, document)
| 201951 | # jquery.popLockIt
# https://github.com/zamiang/jquery.popLockIt
#
# A jQuery plugin for 'locking' short content in place as the user
# scrolls by longer content. For example, it will lock metadata and
# share buttons in place as the user scrolls by a long essay or series
# of images.
#
# Copyright (c) 2013 <NAME>, Artsy
# Licensed under the MIT license.
#
# DOM STRUCTURE:
# Feed
# -- FeedItem
# ---- Column
# ---- Column
# ---- Column
# -- FeedItem
# ---- Column
# ...
(($, window, document) ->
pluginName = "popLockIt"
class Base
requires: []
constructor: (@$el, @settings) ->
for require in @requires
throw "You must pass #{require}" unless @settings[require]?
class Column extends Base
requires: ['height', 'marginTop', 'marginLeft', 'marginBottom']
cssProperties: ['position', 'top', 'bottom', 'left']
# defaults
marginTop: 0
marginBottom: 0
marginLeft: 0
parentHeight: 0
height: 0
top: 0
bottom: 0
left: 0
constructor: (@$el, @settings) ->
@
setMargins: (settings) ->
@parentHeight = settings.parentHeight if settings.parentHeight
@marginTop = settings.marginTop if settings.marginTop
@marginBottom = settings.marginBottom if settings.marginBottom
@marginLeft = settings.marginLeft if settings.marginLeft
setDimensions: ->
@height = Math.floor Number(@$el.css('height').replace('px',""))
@top = Math.floor(@$el.offset().top - @marginTop)
@left = Math.floor(@$el.offset().left)
@bottom = Math.floor(@top + @parentHeight - @height)
@top = 1 if @top < 1
setPosition: (pos = 'absolute', direction = 'north') ->
newState =
position : pos
left : Math.round(@getLeftForPosition(pos))
if pos == 'absolute'
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then @marginBottom else 'auto'
else
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then 0 else 'auto'
# first time around we have nothing to diff and want to apply the entire changeset
unless @oldState
@$el.css newState
return @oldState = newState
diff = {}
changed = false
for prop in @cssProperties
if newState[prop] != @oldState[prop]
diff[prop] = newState[prop]
changed = true
if changed
@$el.css diff
@oldState = newState
getLeftForPosition: (pos) ->
if pos == 'fixed'
@left
else if pos == 'static'
0
else
@left - @marginLeft
onScroll: (scrollTop, viewportHeight, preventFixed=false, scrollDirection) ->
if !preventFixed
if @height == viewportHeight
if (scrollTop < @top + @parentHeight - @height)
return @setPosition('fixed', 'north')
return @setPosition('absolute', 'south')
else if @height < viewportHeight
return @setPosition('fixed', 'north') if scrollTop >= @top and scrollTop < @top + @parentHeight - @height
return @setPosition('absolute', 'south')
return @setPosition('fixed', 'south') if @height > viewportHeight and @height < @parentHeight and (scrollTop + viewportHeight) >= (@top + @height) and (scrollTop + viewportHeight) < (@parentHeight + @top)
if @height >= viewportHeight
if scrollTop >= @top + @height
return @setPosition('absolute', 'south')
@setPosition('absolute', 'north')
# return to default state on destroy
destroy: -> @setPosition()
class FeedItem extends Base
requires: ['columnSelector']
active: false
columns: []
constructor: (@$el, @settings, @index, @parent) ->
super
@$columns = @$el.find @settings.columnSelector
if @hasColumns()
@setDimensions()
@createColumns()
@settings.additionalFeedItemInit(@$el, @index) if @settings.additionalFeedItemInit
@
createColumns: ->
@columns = @$columns.map -> new Column($(this))
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setDimensions: ->
# accomodate for when feed items have different padding
@marginTop = Number(@$el.css('padding-top').replace('px', ''))
@marginBottom = Number(@$el.css('padding-bottom').replace('px', ''))
@resetColumnPositioning()
@$el.css height: 'auto'
height = @$el.css('height')
@height = Number(height.replace('px',""))
@$el.css
height: height
@left = @$el.offset().left
@top = @$el.offset().top
@bottom = @top + @height
onScroll: (scrollTop, viewportHeight, forceOnScroll) ->
# only trigger onscroll for columns if the feeditem is visible in the viewport
if viewportHeight >= @height
@active = false
else if scrollTop >= @top and scrollTop < @bottom
@active = true
column.onScroll(scrollTop, viewportHeight, @parent.settings.preventFixed) for column in @columns
else if @active
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
@active = false
else if forceOnScroll
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
recompute: ->
@setDimensions()
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setColumnMargins: (column) ->
column.setMargins
parentHeight : @height
marginTop : @marginTop
marginBottom : @marginBottom
marginLeft : @left
recomputeColumn: (index) ->
return unless !@columns[index]
@setColumnMargins @columns[index]
resetColumnPositioning: -> column.setPosition('static') for column in @columns
destroy: -> column.destroy() for column in @columns
hasColumns: -> @$columns?.length > 1
class Feed extends Base
feedItems: []
requires: ['feedItems']
hasFocus: true
scrollSpeedThreshold: 500
defaults:
active: true
rendered: false
preventFixed: false
constructor: (@el, @settings) ->
@$el = $(@el)
throw "You must pass settings" unless @settings?
throw "PopLockIt must be called on one element" unless @$el?.length == 1
super(@$el, @settings)
@$window = $(window)
@settings = $.extend @defaults, @settings
@settings.active = true
@initRequestAnimationFrame()
@viewportHeight = @$window.outerHeight(true)
@$el.css
'box-sizing': 'border-box' # to make dimensions measurements consistent across different sites
overflow : 'hidden'
@addFeedItems @settings.feedItems
@requestAnimationFrame()
@
onScroll: ->
return unless @settings.active
scrollTop = @$window.scrollTop()
if scrollTop == @previousScrollTop
return @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
for item in @feedItems
# run onscroll for all feeditems if scrolltop is very different from prev scroll top (user scrolled very fast)
item.onScroll(scrollTop, @viewportHeight, Math.abs(scrollTop - @previousScrollTop) > @scrollSpeedThreshold)
@previousScrollTop = scrollTop
# run onscroll cont
@settings.onScroll(scrollTop) if @settings.onScroll?
@requestAnimationFrame()
# recomputes height / top / bottom etc of each feed item and its columns
recompute: ->
@settings.active = true
feedItem.recompute() for feedItem in @feedItems
scrollTop = @$window.scrollTop()
for item in @feedItems
item.onScroll scrollTop, @viewportHeight, false
recomputeItem: (index) ->
return unless @feedItems[index]
@feedItems[index].recompute()
recomputeItemColumn: (index, columnIndex) ->
return unless @feedItems[index]
@feedItems[index].recomputeColumn columnIndex
destroy: ->
@settings.rendered = false
@settings.active = false
$.data @$el, "plugin_#{pluginName}", false
if feedItems?.length
item.destroy() for item in @feedItems
@feedItems = []
stop: ->
@settings.active = false
window.cancelAnimationFrame @requestedAnimationFrame
start: ->
@settings.active = true
window.cancelAnimationFrame @requestedAnimationFrame
@requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
addFeedItems: ($feedItems) ->
throw "You must pass $feedItems" unless $feedItems? and $feedItems.length
# jQuery map - returns a $(array) instead of a real array
$feedItems.map (index, el) =>
@feedItems.push(new FeedItem $(el), @settings, index, @)
requestAnimationFrame: -> @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# requestAnimationFrame polyfill by <NAME>
# fixes from <NAME> and <NAME>
initRequestAnimationFrame: ->
return if window.requestAnimationFrame
lastTime = 0
vendors = ['ms', 'moz', 'webkit', 'o']
for vendor in vendors when not window.requestAnimationFrame
window.requestAnimationFrame = window["#{vendor}RequestAnimationFrame"]
window.cancelAnimationFrame = window["{vendor}CancelAnimationFrame"] or window["{vendors}CancelRequestAnimationFrame"]
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) -> clearTimeout(id)
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new Feed(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.popLockIt"
)(jQuery, window, document)
| true | # jquery.popLockIt
# https://github.com/zamiang/jquery.popLockIt
#
# A jQuery plugin for 'locking' short content in place as the user
# scrolls by longer content. For example, it will lock metadata and
# share buttons in place as the user scrolls by a long essay or series
# of images.
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI, Artsy
# Licensed under the MIT license.
#
# DOM STRUCTURE:
# Feed
# -- FeedItem
# ---- Column
# ---- Column
# ---- Column
# -- FeedItem
# ---- Column
# ...
(($, window, document) ->
pluginName = "popLockIt"
class Base
requires: []
constructor: (@$el, @settings) ->
for require in @requires
throw "You must pass #{require}" unless @settings[require]?
class Column extends Base
requires: ['height', 'marginTop', 'marginLeft', 'marginBottom']
cssProperties: ['position', 'top', 'bottom', 'left']
# defaults
marginTop: 0
marginBottom: 0
marginLeft: 0
parentHeight: 0
height: 0
top: 0
bottom: 0
left: 0
constructor: (@$el, @settings) ->
@
setMargins: (settings) ->
@parentHeight = settings.parentHeight if settings.parentHeight
@marginTop = settings.marginTop if settings.marginTop
@marginBottom = settings.marginBottom if settings.marginBottom
@marginLeft = settings.marginLeft if settings.marginLeft
setDimensions: ->
@height = Math.floor Number(@$el.css('height').replace('px',""))
@top = Math.floor(@$el.offset().top - @marginTop)
@left = Math.floor(@$el.offset().left)
@bottom = Math.floor(@top + @parentHeight - @height)
@top = 1 if @top < 1
setPosition: (pos = 'absolute', direction = 'north') ->
newState =
position : pos
left : Math.round(@getLeftForPosition(pos))
if pos == 'absolute'
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then @marginBottom else 'auto'
else
newState.top = if direction == 'north' then @marginTop else 'auto'
newState.bottom = if direction == 'south' then 0 else 'auto'
# first time around we have nothing to diff and want to apply the entire changeset
unless @oldState
@$el.css newState
return @oldState = newState
diff = {}
changed = false
for prop in @cssProperties
if newState[prop] != @oldState[prop]
diff[prop] = newState[prop]
changed = true
if changed
@$el.css diff
@oldState = newState
getLeftForPosition: (pos) ->
if pos == 'fixed'
@left
else if pos == 'static'
0
else
@left - @marginLeft
onScroll: (scrollTop, viewportHeight, preventFixed=false, scrollDirection) ->
if !preventFixed
if @height == viewportHeight
if (scrollTop < @top + @parentHeight - @height)
return @setPosition('fixed', 'north')
return @setPosition('absolute', 'south')
else if @height < viewportHeight
return @setPosition('fixed', 'north') if scrollTop >= @top and scrollTop < @top + @parentHeight - @height
return @setPosition('absolute', 'south')
return @setPosition('fixed', 'south') if @height > viewportHeight and @height < @parentHeight and (scrollTop + viewportHeight) >= (@top + @height) and (scrollTop + viewportHeight) < (@parentHeight + @top)
if @height >= viewportHeight
if scrollTop >= @top + @height
return @setPosition('absolute', 'south')
@setPosition('absolute', 'north')
# return to default state on destroy
destroy: -> @setPosition()
class FeedItem extends Base
requires: ['columnSelector']
active: false
columns: []
constructor: (@$el, @settings, @index, @parent) ->
super
@$columns = @$el.find @settings.columnSelector
if @hasColumns()
@setDimensions()
@createColumns()
@settings.additionalFeedItemInit(@$el, @index) if @settings.additionalFeedItemInit
@
createColumns: ->
@columns = @$columns.map -> new Column($(this))
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setDimensions: ->
# accomodate for when feed items have different padding
@marginTop = Number(@$el.css('padding-top').replace('px', ''))
@marginBottom = Number(@$el.css('padding-bottom').replace('px', ''))
@resetColumnPositioning()
@$el.css height: 'auto'
height = @$el.css('height')
@height = Number(height.replace('px',""))
@$el.css
height: height
@left = @$el.offset().left
@top = @$el.offset().top
@bottom = @top + @height
onScroll: (scrollTop, viewportHeight, forceOnScroll) ->
# only trigger onscroll for columns if the feeditem is visible in the viewport
if viewportHeight >= @height
@active = false
else if scrollTop >= @top and scrollTop < @bottom
@active = true
column.onScroll(scrollTop, viewportHeight, @parent.settings.preventFixed) for column in @columns
else if @active
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
@active = false
else if forceOnScroll
column.onScroll(scrollTop, viewportHeight, true) for column in @columns
recompute: ->
@setDimensions()
@setColumnMargins(column) for column in @columns
column.setDimensions() for column in @columns
setColumnMargins: (column) ->
column.setMargins
parentHeight : @height
marginTop : @marginTop
marginBottom : @marginBottom
marginLeft : @left
recomputeColumn: (index) ->
return unless !@columns[index]
@setColumnMargins @columns[index]
resetColumnPositioning: -> column.setPosition('static') for column in @columns
destroy: -> column.destroy() for column in @columns
hasColumns: -> @$columns?.length > 1
class Feed extends Base
feedItems: []
requires: ['feedItems']
hasFocus: true
scrollSpeedThreshold: 500
defaults:
active: true
rendered: false
preventFixed: false
constructor: (@el, @settings) ->
@$el = $(@el)
throw "You must pass settings" unless @settings?
throw "PopLockIt must be called on one element" unless @$el?.length == 1
super(@$el, @settings)
@$window = $(window)
@settings = $.extend @defaults, @settings
@settings.active = true
@initRequestAnimationFrame()
@viewportHeight = @$window.outerHeight(true)
@$el.css
'box-sizing': 'border-box' # to make dimensions measurements consistent across different sites
overflow : 'hidden'
@addFeedItems @settings.feedItems
@requestAnimationFrame()
@
onScroll: ->
return unless @settings.active
scrollTop = @$window.scrollTop()
if scrollTop == @previousScrollTop
return @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
for item in @feedItems
# run onscroll for all feeditems if scrolltop is very different from prev scroll top (user scrolled very fast)
item.onScroll(scrollTop, @viewportHeight, Math.abs(scrollTop - @previousScrollTop) > @scrollSpeedThreshold)
@previousScrollTop = scrollTop
# run onscroll cont
@settings.onScroll(scrollTop) if @settings.onScroll?
@requestAnimationFrame()
# recomputes height / top / bottom etc of each feed item and its columns
recompute: ->
@settings.active = true
feedItem.recompute() for feedItem in @feedItems
scrollTop = @$window.scrollTop()
for item in @feedItems
item.onScroll scrollTop, @viewportHeight, false
recomputeItem: (index) ->
return unless @feedItems[index]
@feedItems[index].recompute()
recomputeItemColumn: (index, columnIndex) ->
return unless @feedItems[index]
@feedItems[index].recomputeColumn columnIndex
destroy: ->
@settings.rendered = false
@settings.active = false
$.data @$el, "plugin_#{pluginName}", false
if feedItems?.length
item.destroy() for item in @feedItems
@feedItems = []
stop: ->
@settings.active = false
window.cancelAnimationFrame @requestedAnimationFrame
start: ->
@settings.active = true
window.cancelAnimationFrame @requestedAnimationFrame
@requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
addFeedItems: ($feedItems) ->
throw "You must pass $feedItems" unless $feedItems? and $feedItems.length
# jQuery map - returns a $(array) instead of a real array
$feedItems.map (index, el) =>
@feedItems.push(new FeedItem $(el), @settings, index, @)
requestAnimationFrame: -> @requestedAnimationFrame = window.requestAnimationFrame (=> @onScroll())
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# requestAnimationFrame polyfill by PI:NAME:<NAME>END_PI
# fixes from PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
initRequestAnimationFrame: ->
return if window.requestAnimationFrame
lastTime = 0
vendors = ['ms', 'moz', 'webkit', 'o']
for vendor in vendors when not window.requestAnimationFrame
window.requestAnimationFrame = window["#{vendor}RequestAnimationFrame"]
window.cancelAnimationFrame = window["{vendor}CancelAnimationFrame"] or window["{vendors}CancelRequestAnimationFrame"]
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) -> clearTimeout(id)
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new Feed(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.popLockIt"
)(jQuery, window, document)
|
[
{
"context": "c/*.js\"\n options:\n host: \"http://127.0.0.1:8900/\"\n specs: \"test/spec/*Spec.js\"\n ",
"end": 2447,
"score": 0.8000218868255615,
"start": 2439,
"tag": "IP_ADDRESS",
"value": "27.0.0.1"
}
] | Gruntfile.coffee | glassesfactory/kazitori.js | 17 | module.exports = (grunt) ->
"use strict"
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n'
# coffeelintOptions:
# max_line_length:
# value: 120
# level: "warn"
# coffeelint:
# product: ["src/coffee/*.coffee"]
coffee:
product:
options:
bare: true
expand: true
cwd: 'src/coffee/'
src: '*.coffee'
dest: 'src/js/'
ext: '.js'
example:
expand: true
options:
bare: true
cwd: 'example/coffee/'
src: '*.coffee'
dest: 'example/assets/js/'
ext: '.js'
test:
expand: true
options:
bare: true
cwd: 'test/spec/'
src: '*.coffee'
dest: 'test/spec/'
ext: '.js'
uglify:
product:
options:
banner: "<%= banner %>"
files:
"src/js/kazitori.min.js": "src/js/kazitori.js"
"src/js/kai.min.js": "src/js/kai.js"
connect:
jasmine:
options:
port: 8900
test:
options:
keepalive: true
port: 8901
base: "test/"
example:
options:
keepalive: true
port: 8902
base: "example/"
livereload:
port: 8910
watch:
product:
files: ["src/coffee/*.coffee"]
tasks: ["coffee:product", "uglify:product", "test"]
# tasks: ["coffee:product", "uglify:product", "livereload", "test"]
example:
files: ["example/coffee/*.coffee"]
tasks: ["coffee:example"]
# tasks: ["coffee:example", "livereload"]
test:
files: ["test/spec/*.coffee"]
tasks: ["coffee:test", "test"]
# tasks: ["coffee:test", "livereload", "test"]
# docco:
# kazitori:
# src: ["src/coffee/kazitori.coffee"]
# dest: "docs/"
# kai:
# src: ["src/coffee/kai.coffee"]
# dest: "docs/"
jasmine:
product:
src: "test/src/*.js"
options:
host: "http://127.0.0.1:8900/"
specs: "test/spec/*Spec.js"
helpers: "test/spec/*Helper.js"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.loadNpmTasks "grunt-contrib-watch"
grunt.loadNpmTasks "grunt-contrib-jasmine"
grunt.loadNpmTasks "grunt-contrib-livereload"
grunt.loadNpmTasks "grunt-contrib-connect"
grunt.loadNpmTasks "grunt-notify"
grunt.registerTask "default", ["livereload-start", "coffee", "uglify", "test"]
grunt.registerTask "test", ["connect:jasmine", "jasmine:product"]
grunt.registerTask "ci", ["coffee", "test"]
| 88353 | module.exports = (grunt) ->
"use strict"
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n'
# coffeelintOptions:
# max_line_length:
# value: 120
# level: "warn"
# coffeelint:
# product: ["src/coffee/*.coffee"]
coffee:
product:
options:
bare: true
expand: true
cwd: 'src/coffee/'
src: '*.coffee'
dest: 'src/js/'
ext: '.js'
example:
expand: true
options:
bare: true
cwd: 'example/coffee/'
src: '*.coffee'
dest: 'example/assets/js/'
ext: '.js'
test:
expand: true
options:
bare: true
cwd: 'test/spec/'
src: '*.coffee'
dest: 'test/spec/'
ext: '.js'
uglify:
product:
options:
banner: "<%= banner %>"
files:
"src/js/kazitori.min.js": "src/js/kazitori.js"
"src/js/kai.min.js": "src/js/kai.js"
connect:
jasmine:
options:
port: 8900
test:
options:
keepalive: true
port: 8901
base: "test/"
example:
options:
keepalive: true
port: 8902
base: "example/"
livereload:
port: 8910
watch:
product:
files: ["src/coffee/*.coffee"]
tasks: ["coffee:product", "uglify:product", "test"]
# tasks: ["coffee:product", "uglify:product", "livereload", "test"]
example:
files: ["example/coffee/*.coffee"]
tasks: ["coffee:example"]
# tasks: ["coffee:example", "livereload"]
test:
files: ["test/spec/*.coffee"]
tasks: ["coffee:test", "test"]
# tasks: ["coffee:test", "livereload", "test"]
# docco:
# kazitori:
# src: ["src/coffee/kazitori.coffee"]
# dest: "docs/"
# kai:
# src: ["src/coffee/kai.coffee"]
# dest: "docs/"
jasmine:
product:
src: "test/src/*.js"
options:
host: "http://1172.16.17.32:8900/"
specs: "test/spec/*Spec.js"
helpers: "test/spec/*Helper.js"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.loadNpmTasks "grunt-contrib-watch"
grunt.loadNpmTasks "grunt-contrib-jasmine"
grunt.loadNpmTasks "grunt-contrib-livereload"
grunt.loadNpmTasks "grunt-contrib-connect"
grunt.loadNpmTasks "grunt-notify"
grunt.registerTask "default", ["livereload-start", "coffee", "uglify", "test"]
grunt.registerTask "test", ["connect:jasmine", "jasmine:product"]
grunt.registerTask "ci", ["coffee", "test"]
| true | module.exports = (grunt) ->
"use strict"
grunt.initConfig
pkg: grunt.file.readJSON("package.json")
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n'
# coffeelintOptions:
# max_line_length:
# value: 120
# level: "warn"
# coffeelint:
# product: ["src/coffee/*.coffee"]
coffee:
product:
options:
bare: true
expand: true
cwd: 'src/coffee/'
src: '*.coffee'
dest: 'src/js/'
ext: '.js'
example:
expand: true
options:
bare: true
cwd: 'example/coffee/'
src: '*.coffee'
dest: 'example/assets/js/'
ext: '.js'
test:
expand: true
options:
bare: true
cwd: 'test/spec/'
src: '*.coffee'
dest: 'test/spec/'
ext: '.js'
uglify:
product:
options:
banner: "<%= banner %>"
files:
"src/js/kazitori.min.js": "src/js/kazitori.js"
"src/js/kai.min.js": "src/js/kai.js"
connect:
jasmine:
options:
port: 8900
test:
options:
keepalive: true
port: 8901
base: "test/"
example:
options:
keepalive: true
port: 8902
base: "example/"
livereload:
port: 8910
watch:
product:
files: ["src/coffee/*.coffee"]
tasks: ["coffee:product", "uglify:product", "test"]
# tasks: ["coffee:product", "uglify:product", "livereload", "test"]
example:
files: ["example/coffee/*.coffee"]
tasks: ["coffee:example"]
# tasks: ["coffee:example", "livereload"]
test:
files: ["test/spec/*.coffee"]
tasks: ["coffee:test", "test"]
# tasks: ["coffee:test", "livereload", "test"]
# docco:
# kazitori:
# src: ["src/coffee/kazitori.coffee"]
# dest: "docs/"
# kai:
# src: ["src/coffee/kai.coffee"]
# dest: "docs/"
jasmine:
product:
src: "test/src/*.js"
options:
host: "http://1PI:IP_ADDRESS:172.16.17.32END_PI:8900/"
specs: "test/spec/*Spec.js"
helpers: "test/spec/*Helper.js"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.loadNpmTasks "grunt-contrib-watch"
grunt.loadNpmTasks "grunt-contrib-jasmine"
grunt.loadNpmTasks "grunt-contrib-livereload"
grunt.loadNpmTasks "grunt-contrib-connect"
grunt.loadNpmTasks "grunt-notify"
grunt.registerTask "default", ["livereload-start", "coffee", "uglify", "test"]
grunt.registerTask "test", ["connect:jasmine", "jasmine:product"]
grunt.registerTask "ci", ["coffee", "test"]
|
[
{
"context": "ew TextLayer\n\tparent:playbackBarContainer\n\ttext: \"Gulliver's Travels\"\n\tfontFamily:'sans-serif, fsme-light', ",
"end": 2648,
"score": 0.9673454165458679,
"start": 2640,
"tag": "NAME",
"value": "Gulliver"
}
] | prototypes/hours-minutes/app.coffee | Skinny-Malinky/Skinny-Malinky.github.io | 0 | # Setup Variables
document.body.style.cursor = "auto"
Screen.backgroundColor = '#000'
Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
youviewBlue = '#00a6ff'
youviewBlue2 = '#0F5391'
youviewBlue3 = '#032230'
youviewGrey1 = '#b6b9bf'
youviewGrey2 = '#83858a'
darkGrey3 = '#505359'
black = '#000'
white = '#ebebeb'
veryDarkGrey4 = '#171717'
veryDarkGrey5 = '#0D0D0D'
#Playback Bar Layers
playbackBarContainer = new Layer
width:1280, height:720
backgroundColor:'transparent'
topGradient = new Layer
parent:playbackBarContainer
width:1280
height:109
image:'images/top-gradient.png'
index:0
gradient = new Layer
parent:playbackBarContainer
y: Align.bottom
width:1280, height:390
image:'images/playback-bar-bg.png'
opacity:1
index:0
playbackLine = new Layer
parent:playbackBarContainer
width:798, height:4
x:274, y:617
bufferLine = new Layer
parent:playbackLine
height:4, width:797
backgroundColor: '#0f5391'
playedLine = new Layer
parent:bufferLine
height:4, width:700
backgroundColor:'#00a6ff'
playheadLine = new Layer
parent:playedLine
height:10, width:4
y:-3, x:Align.right
backgroundColor:'#00a6ff'
startTime = new TextLayer
parent:playbackBarContainer
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
color:youviewBlue
maxY:playbackLine.maxY+4, x:209
endTime = new TextLayer
parent:playbackBarContainer
autoWidth:true
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8
patchBack = new Layer
parent:playbackBarContainer
image:'images/patch-highlight.png'
backgroundColor:'rgba(0,0,0,0.95)'
height:129
width:130
y:510, x:64
index:0
patchIconContainer = new Layer
parent:playbackBarContainer
midX:patchBack.midX
y:patchBack.y + 24
height:50, width:50
clip:true
backgroundColor: 'transparent'
patchIcon = new Layer
parent:patchIconContainer
image:'images/playback-sprites.png'
height:750, width:50
x:-1,y:-22
backgroundColor: 'transparent'
patchRCNInput = new TextLayer
parent:patchBack
width:120, height:36, y:30
fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12
color:'#ebebeb'
text:''
patchText = new TextLayer
parent:playbackBarContainer
text:'Play'
midX:patchBack.midX
y:startTime.y
fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center'
height:16, width:128
clip:true
backgroundColor: 'transparent'
title = new TextLayer
parent:playbackBarContainer
text: "Gulliver's Travels"
fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb'
width:848, height:36
x:startTime.x, y:550
# Instructions
instBackground = new Layer
width: 500
height: 220
backgroundColor: '#1f1f1f'
borderStyle: 'dotted'
borderRadius: 20
borderWidth: 2
borderColor: 'white'
x: 20, y: 20
instTitle = new TextLayer
parent: instBackground
text: 'Instructions'
x: 30, y: 15, color: white
instDesc = new TextLayer
parent: instBackground
html: '
<p style="margin-bottom:5px;">0-9 – number input</p>
<p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20
x: 30, y: 75, color: white
# Clock
today = new Date
hour = today.getHours()
minute = today.getMinutes()
Utils.interval 60, ->
refreshTime()
currentTime = new TextLayer
parent:topGradient
text:hour + ':' + minute
maxX:1216
y:36
fontFamily:'sans-serif, fsme'
fontSize:30
color:'#ebebeb'
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
refreshTime = () ->
today = new Date
hour = today.getHours()
minute = today.getMinutes()
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
currentTime.maxX = 1216
refreshTime()
#Video Content and Management
background = new BackgroundLayer
backgroundColor: '#000'
recording = new VideoLayer
parent:background
video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4'
width:1280, height:800
backgroundColor: '#000'
recording.center()
recording.player.autoplay = true
# recording.player.controls = true
recording.ignoreEvents = false
playTime = recording
recording.player.addEventListener "timeupdate", ->
# Calculate progress bar position
newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime
playheadLine.x = newPos
playedLine.width = newPos
if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1
startTime.text = '0:' + timeParser(recording.player.currentTime)
else
startTime.text = timeParser(recording.player.currentTime)
endTime.text = timeParser(recording.player.duration)
skipTo = (time) ->
recording.player.currentTime = time
timeParser = (time) ->
rationalTime = Math.round(time)
if rationalTime < 60 and rationalTime < 10
return '00:0' + rationalTime
else if rationalTime < 60 and rationalTime > 9
return '00:' + rationalTime
else if rationalTime >= 60
if rationalTime >= 570
if getMinutesOf(rationalTime) < 10
minutes = '0' + getMinutesOf(rationalTime)
else minutes = getMinutesOf(rationalTime)
else
minutes = '0' + getMinutesOf(rationalTime)
seconds = getSecondsOf(rationalTime)
if seconds < 10
singleDigit = seconds
seconds = '0' + singleDigit
if rationalTime >= 3600
hours = getHoursOf(rationalTime)
return hours + ':' + minutes + ':' + seconds
return minutes + ':' + seconds
getHoursOf = (rationalTime) ->
minutes = rationalTime / 60
hours = Math.floor( minutes / 60 )
return hours
getMinutesOf = (rationalTime) ->
totalMinutes = rationalTime / 60
minutes = Math.floor( totalMinutes % 60 )
return minutes
getSecondsOf = (rationalTime) ->
seconds = Math.floor( rationalTime % 60 )
return seconds
# Keys
del = 8
guide = 9
ok = 13
record = 17
sub = 18
ad = 20
close = 27
pUp = 33
pDown = 34
mainMenu = 36
left = 37
up = 38
right = 39
down = 40
back = 46
zero = 48
one = 49
two = 50
three = 51
four = 52
five = 53
six = 54
seven = 55
eight = 56
nine = 57
info = 73
record = 82
stop = 111
help = 112
myTV = 115
red = 116
green = 117
yellow = 118
blue = 119
pause = 186
rewind = 188
fastForward = 190
stop = 191
mute = 220
play = 222
text = 120
power = 124
search = 192
skipBackward = 219
skipForward = 221
# Key Listener
stopKeyInput = () ->
document.removeEventListener 'keydown', (event) ->
startKeyInput = () ->
document.addEventListener 'keydown', (event) ->
keyCode = event.which
eventHandler(keyCode)
event.preventDefault()
startKeyInput()
barTimeOut = 0
timeOut = 0
eventHandler = Utils.throttle 0.1, (keyCode) ->
barTimeOut = 0
playbackBarContainer.animate
opacity:1
y:0
options:
curve:'ease-in-out'
time:0.5
switch keyCode
when one
timeJump(1)
when two
timeJump(2)
when three
timeJump(3)
when four
timeJump(4)
when five
timeJump(5)
when six
timeJump(6)
when seven
timeJump(7)
when eight
timeJump(8)
when nine
timeJump(9)
when zero
timeJump(0)
when ok
jumpToTime( patchRCNInput.text )
timeOut = 5
when red
changeVideo()
changeVideo = () ->
if recording.video == 'video/taboo.mp4'
title.text = 'Guardians of the Galaxy'
recording.video = 'video/Guardians of the Galaxy_downscale.mp4'
recording.player.currentTime = 0
recording.player.play()
else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4'
recording.video = 'video/taboo.mp4'
title.text = 'Taboo'
recording.player.currentTime = 0
recording.player.play()
clearTimeInput = () ->
patchRCNInput.text = ''
patchRCNInput.color = white
patchIcon.visible = true
patchText.text = 'Play'
Utils.interval 0.5, ->
if barTimeOut == 13
playbackBarContainer.animate
opacity:0
y:playbackBarContainer.y+20
options:
curve:'ease-in-out'
time:0.5
barTimeOut++
if timeOut == 5
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7
switch patchRCNInput.text.length
when 2
patchRCNInput.text+='00:00'
when 3
patchRCNInput.text+='0:00'
when 5
patchRCNInput.text+='00'
when 6
patchRCNInput.text+='0'
if maxInput == 5
switch patchRCNInput.text.length
when 1
minute = patchRCNInput.text
patchRCNInput.text = '0' + minute + ':00'
when 3
patchRCNInput.text += '00'
when 4
patchRCNInput.text+='0'
jumpToTime( patchRCNInput.text )
timeOut++
timeJump = ( input ) ->
timeOut = 0
patchIcon.visible = false
patchText.text = 'Jump To'
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7 and patchRCNInput.text.length != maxInput+1
# If it's longer than an hour
if getHoursOf(recording.player.duration) >= 1
# If it's the first key input
if patchRCNInput.text.length < 1
# If the input is less than the hour length of the recording.
if input <= getHoursOf(recording.player.duration)
patchRCNInput.text = input + ':'
else
patchRCNInput.text = '0:' + input
# If it's after first input
else if patchRCNInput.text.length >= 1
if patchRCNInput.text.length == 0 or patchRCNInput.text.length == 3
patchRCNInput.text += input + ':'
else
patchRCNInput.text += input
else if maxInput == 5 and patchRCNInput.text.length != maxInput+1
if patchRCNInput.text.length == 1
patchRCNInput.text += input + ':'
else if patchRCNInput.text.length == 2
patchRCNInput.text += input
else if patchRCNInput.text.length < maxInput
patchRCNInput.text += input
if patchRCNInput.text.length == maxInput then jumpToTime( patchRCNInput.text )
jumpToTime = ( timeString, maxInput ) ->
stopKeyInput()
newTimes = timeString.split(':')
if newTimes.length == 2
irrationalTime = (60 * parseInt(newTimes[0])) + parseInt(newTimes[1])
else if newTimes.length == 3
irrationalTime = (Math.pow(60, 2) * parseInt(newTimes[0]) + (parseInt(newTimes[1]) * 60) + parseInt(newTimes[2]))
else if newTimes.length == 1
irrationalTime = (parseInt(newTimes[0]) * 60) + parseInt(newTimes[1])
if irrationalTime < recording.player.duration
skipTo(irrationalTime)
patchRCNInput.color = youviewBlue
Utils.delay 1, ->
clearTimeInput()
startKeyInput()
patchRCNInput.visible = true | 14295 | # Setup Variables
document.body.style.cursor = "auto"
Screen.backgroundColor = '#000'
Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
youviewBlue = '#00a6ff'
youviewBlue2 = '#0F5391'
youviewBlue3 = '#032230'
youviewGrey1 = '#b6b9bf'
youviewGrey2 = '#83858a'
darkGrey3 = '#505359'
black = '#000'
white = '#ebebeb'
veryDarkGrey4 = '#171717'
veryDarkGrey5 = '#0D0D0D'
#Playback Bar Layers
playbackBarContainer = new Layer
width:1280, height:720
backgroundColor:'transparent'
topGradient = new Layer
parent:playbackBarContainer
width:1280
height:109
image:'images/top-gradient.png'
index:0
gradient = new Layer
parent:playbackBarContainer
y: Align.bottom
width:1280, height:390
image:'images/playback-bar-bg.png'
opacity:1
index:0
playbackLine = new Layer
parent:playbackBarContainer
width:798, height:4
x:274, y:617
bufferLine = new Layer
parent:playbackLine
height:4, width:797
backgroundColor: '#0f5391'
playedLine = new Layer
parent:bufferLine
height:4, width:700
backgroundColor:'#00a6ff'
playheadLine = new Layer
parent:playedLine
height:10, width:4
y:-3, x:Align.right
backgroundColor:'#00a6ff'
startTime = new TextLayer
parent:playbackBarContainer
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
color:youviewBlue
maxY:playbackLine.maxY+4, x:209
endTime = new TextLayer
parent:playbackBarContainer
autoWidth:true
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8
patchBack = new Layer
parent:playbackBarContainer
image:'images/patch-highlight.png'
backgroundColor:'rgba(0,0,0,0.95)'
height:129
width:130
y:510, x:64
index:0
patchIconContainer = new Layer
parent:playbackBarContainer
midX:patchBack.midX
y:patchBack.y + 24
height:50, width:50
clip:true
backgroundColor: 'transparent'
patchIcon = new Layer
parent:patchIconContainer
image:'images/playback-sprites.png'
height:750, width:50
x:-1,y:-22
backgroundColor: 'transparent'
patchRCNInput = new TextLayer
parent:patchBack
width:120, height:36, y:30
fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12
color:'#ebebeb'
text:''
patchText = new TextLayer
parent:playbackBarContainer
text:'Play'
midX:patchBack.midX
y:startTime.y
fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center'
height:16, width:128
clip:true
backgroundColor: 'transparent'
title = new TextLayer
parent:playbackBarContainer
text: "<NAME>'s Travels"
fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb'
width:848, height:36
x:startTime.x, y:550
# Instructions
instBackground = new Layer
width: 500
height: 220
backgroundColor: '#1f1f1f'
borderStyle: 'dotted'
borderRadius: 20
borderWidth: 2
borderColor: 'white'
x: 20, y: 20
instTitle = new TextLayer
parent: instBackground
text: 'Instructions'
x: 30, y: 15, color: white
instDesc = new TextLayer
parent: instBackground
html: '
<p style="margin-bottom:5px;">0-9 – number input</p>
<p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20
x: 30, y: 75, color: white
# Clock
today = new Date
hour = today.getHours()
minute = today.getMinutes()
Utils.interval 60, ->
refreshTime()
currentTime = new TextLayer
parent:topGradient
text:hour + ':' + minute
maxX:1216
y:36
fontFamily:'sans-serif, fsme'
fontSize:30
color:'#ebebeb'
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
refreshTime = () ->
today = new Date
hour = today.getHours()
minute = today.getMinutes()
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
currentTime.maxX = 1216
refreshTime()
#Video Content and Management
background = new BackgroundLayer
backgroundColor: '#000'
recording = new VideoLayer
parent:background
video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4'
width:1280, height:800
backgroundColor: '#000'
recording.center()
recording.player.autoplay = true
# recording.player.controls = true
recording.ignoreEvents = false
playTime = recording
recording.player.addEventListener "timeupdate", ->
# Calculate progress bar position
newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime
playheadLine.x = newPos
playedLine.width = newPos
if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1
startTime.text = '0:' + timeParser(recording.player.currentTime)
else
startTime.text = timeParser(recording.player.currentTime)
endTime.text = timeParser(recording.player.duration)
skipTo = (time) ->
recording.player.currentTime = time
timeParser = (time) ->
rationalTime = Math.round(time)
if rationalTime < 60 and rationalTime < 10
return '00:0' + rationalTime
else if rationalTime < 60 and rationalTime > 9
return '00:' + rationalTime
else if rationalTime >= 60
if rationalTime >= 570
if getMinutesOf(rationalTime) < 10
minutes = '0' + getMinutesOf(rationalTime)
else minutes = getMinutesOf(rationalTime)
else
minutes = '0' + getMinutesOf(rationalTime)
seconds = getSecondsOf(rationalTime)
if seconds < 10
singleDigit = seconds
seconds = '0' + singleDigit
if rationalTime >= 3600
hours = getHoursOf(rationalTime)
return hours + ':' + minutes + ':' + seconds
return minutes + ':' + seconds
getHoursOf = (rationalTime) ->
minutes = rationalTime / 60
hours = Math.floor( minutes / 60 )
return hours
getMinutesOf = (rationalTime) ->
totalMinutes = rationalTime / 60
minutes = Math.floor( totalMinutes % 60 )
return minutes
getSecondsOf = (rationalTime) ->
seconds = Math.floor( rationalTime % 60 )
return seconds
# Keys
del = 8
guide = 9
ok = 13
record = 17
sub = 18
ad = 20
close = 27
pUp = 33
pDown = 34
mainMenu = 36
left = 37
up = 38
right = 39
down = 40
back = 46
zero = 48
one = 49
two = 50
three = 51
four = 52
five = 53
six = 54
seven = 55
eight = 56
nine = 57
info = 73
record = 82
stop = 111
help = 112
myTV = 115
red = 116
green = 117
yellow = 118
blue = 119
pause = 186
rewind = 188
fastForward = 190
stop = 191
mute = 220
play = 222
text = 120
power = 124
search = 192
skipBackward = 219
skipForward = 221
# Key Listener
stopKeyInput = () ->
document.removeEventListener 'keydown', (event) ->
startKeyInput = () ->
document.addEventListener 'keydown', (event) ->
keyCode = event.which
eventHandler(keyCode)
event.preventDefault()
startKeyInput()
barTimeOut = 0
timeOut = 0
eventHandler = Utils.throttle 0.1, (keyCode) ->
barTimeOut = 0
playbackBarContainer.animate
opacity:1
y:0
options:
curve:'ease-in-out'
time:0.5
switch keyCode
when one
timeJump(1)
when two
timeJump(2)
when three
timeJump(3)
when four
timeJump(4)
when five
timeJump(5)
when six
timeJump(6)
when seven
timeJump(7)
when eight
timeJump(8)
when nine
timeJump(9)
when zero
timeJump(0)
when ok
jumpToTime( patchRCNInput.text )
timeOut = 5
when red
changeVideo()
changeVideo = () ->
if recording.video == 'video/taboo.mp4'
title.text = 'Guardians of the Galaxy'
recording.video = 'video/Guardians of the Galaxy_downscale.mp4'
recording.player.currentTime = 0
recording.player.play()
else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4'
recording.video = 'video/taboo.mp4'
title.text = 'Taboo'
recording.player.currentTime = 0
recording.player.play()
clearTimeInput = () ->
patchRCNInput.text = ''
patchRCNInput.color = white
patchIcon.visible = true
patchText.text = 'Play'
Utils.interval 0.5, ->
if barTimeOut == 13
playbackBarContainer.animate
opacity:0
y:playbackBarContainer.y+20
options:
curve:'ease-in-out'
time:0.5
barTimeOut++
if timeOut == 5
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7
switch patchRCNInput.text.length
when 2
patchRCNInput.text+='00:00'
when 3
patchRCNInput.text+='0:00'
when 5
patchRCNInput.text+='00'
when 6
patchRCNInput.text+='0'
if maxInput == 5
switch patchRCNInput.text.length
when 1
minute = patchRCNInput.text
patchRCNInput.text = '0' + minute + ':00'
when 3
patchRCNInput.text += '00'
when 4
patchRCNInput.text+='0'
jumpToTime( patchRCNInput.text )
timeOut++
timeJump = ( input ) ->
timeOut = 0
patchIcon.visible = false
patchText.text = 'Jump To'
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7 and patchRCNInput.text.length != maxInput+1
# If it's longer than an hour
if getHoursOf(recording.player.duration) >= 1
# If it's the first key input
if patchRCNInput.text.length < 1
# If the input is less than the hour length of the recording.
if input <= getHoursOf(recording.player.duration)
patchRCNInput.text = input + ':'
else
patchRCNInput.text = '0:' + input
# If it's after first input
else if patchRCNInput.text.length >= 1
if patchRCNInput.text.length == 0 or patchRCNInput.text.length == 3
patchRCNInput.text += input + ':'
else
patchRCNInput.text += input
else if maxInput == 5 and patchRCNInput.text.length != maxInput+1
if patchRCNInput.text.length == 1
patchRCNInput.text += input + ':'
else if patchRCNInput.text.length == 2
patchRCNInput.text += input
else if patchRCNInput.text.length < maxInput
patchRCNInput.text += input
if patchRCNInput.text.length == maxInput then jumpToTime( patchRCNInput.text )
jumpToTime = ( timeString, maxInput ) ->
stopKeyInput()
newTimes = timeString.split(':')
if newTimes.length == 2
irrationalTime = (60 * parseInt(newTimes[0])) + parseInt(newTimes[1])
else if newTimes.length == 3
irrationalTime = (Math.pow(60, 2) * parseInt(newTimes[0]) + (parseInt(newTimes[1]) * 60) + parseInt(newTimes[2]))
else if newTimes.length == 1
irrationalTime = (parseInt(newTimes[0]) * 60) + parseInt(newTimes[1])
if irrationalTime < recording.player.duration
skipTo(irrationalTime)
patchRCNInput.color = youviewBlue
Utils.delay 1, ->
clearTimeInput()
startKeyInput()
patchRCNInput.visible = true | true | # Setup Variables
document.body.style.cursor = "auto"
Screen.backgroundColor = '#000'
Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
youviewBlue = '#00a6ff'
youviewBlue2 = '#0F5391'
youviewBlue3 = '#032230'
youviewGrey1 = '#b6b9bf'
youviewGrey2 = '#83858a'
darkGrey3 = '#505359'
black = '#000'
white = '#ebebeb'
veryDarkGrey4 = '#171717'
veryDarkGrey5 = '#0D0D0D'
#Playback Bar Layers
playbackBarContainer = new Layer
width:1280, height:720
backgroundColor:'transparent'
topGradient = new Layer
parent:playbackBarContainer
width:1280
height:109
image:'images/top-gradient.png'
index:0
gradient = new Layer
parent:playbackBarContainer
y: Align.bottom
width:1280, height:390
image:'images/playback-bar-bg.png'
opacity:1
index:0
playbackLine = new Layer
parent:playbackBarContainer
width:798, height:4
x:274, y:617
bufferLine = new Layer
parent:playbackLine
height:4, width:797
backgroundColor: '#0f5391'
playedLine = new Layer
parent:bufferLine
height:4, width:700
backgroundColor:'#00a6ff'
playheadLine = new Layer
parent:playedLine
height:10, width:4
y:-3, x:Align.right
backgroundColor:'#00a6ff'
startTime = new TextLayer
parent:playbackBarContainer
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
color:youviewBlue
maxY:playbackLine.maxY+4, x:209
endTime = new TextLayer
parent:playbackBarContainer
autoWidth:true
text:''
width:50, height:16
fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5'
maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8
patchBack = new Layer
parent:playbackBarContainer
image:'images/patch-highlight.png'
backgroundColor:'rgba(0,0,0,0.95)'
height:129
width:130
y:510, x:64
index:0
patchIconContainer = new Layer
parent:playbackBarContainer
midX:patchBack.midX
y:patchBack.y + 24
height:50, width:50
clip:true
backgroundColor: 'transparent'
patchIcon = new Layer
parent:patchIconContainer
image:'images/playback-sprites.png'
height:750, width:50
x:-1,y:-22
backgroundColor: 'transparent'
patchRCNInput = new TextLayer
parent:patchBack
width:120, height:36, y:30
fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12
color:'#ebebeb'
text:''
patchText = new TextLayer
parent:playbackBarContainer
text:'Play'
midX:patchBack.midX
y:startTime.y
fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center'
height:16, width:128
clip:true
backgroundColor: 'transparent'
title = new TextLayer
parent:playbackBarContainer
text: "PI:NAME:<NAME>END_PI's Travels"
fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb'
width:848, height:36
x:startTime.x, y:550
# Instructions
instBackground = new Layer
width: 500
height: 220
backgroundColor: '#1f1f1f'
borderStyle: 'dotted'
borderRadius: 20
borderWidth: 2
borderColor: 'white'
x: 20, y: 20
instTitle = new TextLayer
parent: instBackground
text: 'Instructions'
x: 30, y: 15, color: white
instDesc = new TextLayer
parent: instBackground
html: '
<p style="margin-bottom:5px;">0-9 – number input</p>
<p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20
x: 30, y: 75, color: white
# Clock
today = new Date
hour = today.getHours()
minute = today.getMinutes()
Utils.interval 60, ->
refreshTime()
currentTime = new TextLayer
parent:topGradient
text:hour + ':' + minute
maxX:1216
y:36
fontFamily:'sans-serif, fsme'
fontSize:30
color:'#ebebeb'
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
refreshTime = () ->
today = new Date
hour = today.getHours()
minute = today.getMinutes()
if minute < 10
currentTime.text = hour+':0'+minute
else
currentTime.text = hour+':'+minute
currentTime.maxX = 1216
refreshTime()
#Video Content and Management
background = new BackgroundLayer
backgroundColor: '#000'
recording = new VideoLayer
parent:background
video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4'
width:1280, height:800
backgroundColor: '#000'
recording.center()
recording.player.autoplay = true
# recording.player.controls = true
recording.ignoreEvents = false
playTime = recording
recording.player.addEventListener "timeupdate", ->
# Calculate progress bar position
newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime
playheadLine.x = newPos
playedLine.width = newPos
if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1
startTime.text = '0:' + timeParser(recording.player.currentTime)
else
startTime.text = timeParser(recording.player.currentTime)
endTime.text = timeParser(recording.player.duration)
skipTo = (time) ->
recording.player.currentTime = time
timeParser = (time) ->
rationalTime = Math.round(time)
if rationalTime < 60 and rationalTime < 10
return '00:0' + rationalTime
else if rationalTime < 60 and rationalTime > 9
return '00:' + rationalTime
else if rationalTime >= 60
if rationalTime >= 570
if getMinutesOf(rationalTime) < 10
minutes = '0' + getMinutesOf(rationalTime)
else minutes = getMinutesOf(rationalTime)
else
minutes = '0' + getMinutesOf(rationalTime)
seconds = getSecondsOf(rationalTime)
if seconds < 10
singleDigit = seconds
seconds = '0' + singleDigit
if rationalTime >= 3600
hours = getHoursOf(rationalTime)
return hours + ':' + minutes + ':' + seconds
return minutes + ':' + seconds
getHoursOf = (rationalTime) ->
minutes = rationalTime / 60
hours = Math.floor( minutes / 60 )
return hours
getMinutesOf = (rationalTime) ->
totalMinutes = rationalTime / 60
minutes = Math.floor( totalMinutes % 60 )
return minutes
getSecondsOf = (rationalTime) ->
seconds = Math.floor( rationalTime % 60 )
return seconds
# Keys
del = 8
guide = 9
ok = 13
record = 17
sub = 18
ad = 20
close = 27
pUp = 33
pDown = 34
mainMenu = 36
left = 37
up = 38
right = 39
down = 40
back = 46
zero = 48
one = 49
two = 50
three = 51
four = 52
five = 53
six = 54
seven = 55
eight = 56
nine = 57
info = 73
record = 82
stop = 111
help = 112
myTV = 115
red = 116
green = 117
yellow = 118
blue = 119
pause = 186
rewind = 188
fastForward = 190
stop = 191
mute = 220
play = 222
text = 120
power = 124
search = 192
skipBackward = 219
skipForward = 221
# Key Listener
stopKeyInput = () ->
document.removeEventListener 'keydown', (event) ->
startKeyInput = () ->
document.addEventListener 'keydown', (event) ->
keyCode = event.which
eventHandler(keyCode)
event.preventDefault()
startKeyInput()
barTimeOut = 0
timeOut = 0
eventHandler = Utils.throttle 0.1, (keyCode) ->
barTimeOut = 0
playbackBarContainer.animate
opacity:1
y:0
options:
curve:'ease-in-out'
time:0.5
switch keyCode
when one
timeJump(1)
when two
timeJump(2)
when three
timeJump(3)
when four
timeJump(4)
when five
timeJump(5)
when six
timeJump(6)
when seven
timeJump(7)
when eight
timeJump(8)
when nine
timeJump(9)
when zero
timeJump(0)
when ok
jumpToTime( patchRCNInput.text )
timeOut = 5
when red
changeVideo()
changeVideo = () ->
if recording.video == 'video/taboo.mp4'
title.text = 'Guardians of the Galaxy'
recording.video = 'video/Guardians of the Galaxy_downscale.mp4'
recording.player.currentTime = 0
recording.player.play()
else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4'
recording.video = 'video/taboo.mp4'
title.text = 'Taboo'
recording.player.currentTime = 0
recording.player.play()
clearTimeInput = () ->
patchRCNInput.text = ''
patchRCNInput.color = white
patchIcon.visible = true
patchText.text = 'Play'
Utils.interval 0.5, ->
if barTimeOut == 13
playbackBarContainer.animate
opacity:0
y:playbackBarContainer.y+20
options:
curve:'ease-in-out'
time:0.5
barTimeOut++
if timeOut == 5
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7
switch patchRCNInput.text.length
when 2
patchRCNInput.text+='00:00'
when 3
patchRCNInput.text+='0:00'
when 5
patchRCNInput.text+='00'
when 6
patchRCNInput.text+='0'
if maxInput == 5
switch patchRCNInput.text.length
when 1
minute = patchRCNInput.text
patchRCNInput.text = '0' + minute + ':00'
when 3
patchRCNInput.text += '00'
when 4
patchRCNInput.text+='0'
jumpToTime( patchRCNInput.text )
timeOut++
timeJump = ( input ) ->
timeOut = 0
patchIcon.visible = false
patchText.text = 'Jump To'
if getHoursOf(recording.player.duration) >= 1 then maxInput = 7 else maxInput = 5
if maxInput == 7 and patchRCNInput.text.length != maxInput+1
# If it's longer than an hour
if getHoursOf(recording.player.duration) >= 1
# If it's the first key input
if patchRCNInput.text.length < 1
# If the input is less than the hour length of the recording.
if input <= getHoursOf(recording.player.duration)
patchRCNInput.text = input + ':'
else
patchRCNInput.text = '0:' + input
# If it's after first input
else if patchRCNInput.text.length >= 1
if patchRCNInput.text.length == 0 or patchRCNInput.text.length == 3
patchRCNInput.text += input + ':'
else
patchRCNInput.text += input
else if maxInput == 5 and patchRCNInput.text.length != maxInput+1
if patchRCNInput.text.length == 1
patchRCNInput.text += input + ':'
else if patchRCNInput.text.length == 2
patchRCNInput.text += input
else if patchRCNInput.text.length < maxInput
patchRCNInput.text += input
if patchRCNInput.text.length == maxInput then jumpToTime( patchRCNInput.text )
jumpToTime = ( timeString, maxInput ) ->
stopKeyInput()
newTimes = timeString.split(':')
if newTimes.length == 2
irrationalTime = (60 * parseInt(newTimes[0])) + parseInt(newTimes[1])
else if newTimes.length == 3
irrationalTime = (Math.pow(60, 2) * parseInt(newTimes[0]) + (parseInt(newTimes[1]) * 60) + parseInt(newTimes[2]))
else if newTimes.length == 1
irrationalTime = (parseInt(newTimes[0]) * 60) + parseInt(newTimes[1])
if irrationalTime < recording.player.duration
skipTo(irrationalTime)
patchRCNInput.color = youviewBlue
Utils.delay 1, ->
clearTimeInput()
startKeyInput()
patchRCNInput.visible = true |
[
{
"context": "n toolProps.details\n detailTask._key ?= Math.random()\n TaskComponent = tasks[detailTask.ty",
"end": 2048,
"score": 0.9621133804321289,
"start": 2037,
"tag": "KEY",
"value": "Math.random"
}
] | app/classifier/drawing-tools/root.cjsx | alexbfree/Panoptes-Front-End | 0 | React = require 'react'
StickyModalForm = require 'modal-form/sticky'
STROKE_WIDTH = 1.5
SELECTED_STROKE_WIDTH = 2.5
SEMI_MODAL_FORM_STYLE =
pointerEvents: 'all'
SEMI_MODAL_UNDERLAY_STYLE =
pointerEvents: 'none'
backgroundColor: 'rgba(0, 0, 0, 0)'
module.exports = React.createClass
displayName: 'DrawingToolRoot'
statics:
distance: (x1, y1, x2, y2) ->
Math.sqrt Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)
getDefaultProps: ->
tool: null
getInitialState: ->
destroying: false
render: ->
toolProps = @props.tool.props
rootProps =
'data-disabled': toolProps.disabled or null
'data-selected': toolProps.selected or null
'data-destroying': @props.tool.state?.destroying or null
style: color: toolProps.color
scale = (toolProps.scale.horizontal + toolProps.scale.vertical) / 2
mainStyle =
fill: 'transparent'
stroke: 'currentColor'
strokeWidth: if toolProps.selected
SELECTED_STROKE_WIDTH / scale
else
STROKE_WIDTH / scale
unless toolProps.disabled
startHandler = toolProps.onSelect
<g className="drawing-tool" {...rootProps} {...@props}>
<g className="drawing-tool-main" {...mainStyle} onMouseDown={startHandler} onTouchStart={startHandler}>
{@props.children}
</g>
{if toolProps.selected and not toolProps.mark._inProgress and toolProps.details? and toolProps.details.length isnt 0
tasks = require '../tasks'
detailsAreComplete = toolProps.details.every (detailTask, i) =>
TaskComponent = tasks[detailTask.type]
if TaskComponent.isAnnotationComplete?
TaskComponent.isAnnotationComplete detailTask, toolProps.mark.details[i]
else
true
<StickyModalForm ref="detailsForm" style={SEMI_MODAL_FORM_STYLE} underlayStyle={SEMI_MODAL_UNDERLAY_STYLE} onSubmit={@handleDetailsFormClose} onCancel={@handleDetailsFormClose}>
{for detailTask, i in toolProps.details
detailTask._key ?= Math.random()
TaskComponent = tasks[detailTask.type]
<TaskComponent autoFocus={i is 0} key={detailTask._key} task={detailTask} annotation={toolProps.mark.details[i]} onChange={@handleDetailsChange.bind this, i} />}
<hr />
<p style={textAlign: 'center'}>
<button type="submit" className="standard-button" disabled={not detailsAreComplete}>OK</button>
</p>
</StickyModalForm>}
</g>
componentDidUpdate: ->
this.refs.detailsForm?.reposition()
handleDetailsChange: (detailIndex, annotation) ->
@props.tool.props.mark.details[detailIndex] = annotation
@props.tool.props.onChange @props.tool.props.mark
handleDetailsFormClose: ->
# TODO: Check if the details tasks are complete.
@props.tool.props.onDeselect?()
| 13857 | React = require 'react'
StickyModalForm = require 'modal-form/sticky'
STROKE_WIDTH = 1.5
SELECTED_STROKE_WIDTH = 2.5
SEMI_MODAL_FORM_STYLE =
pointerEvents: 'all'
SEMI_MODAL_UNDERLAY_STYLE =
pointerEvents: 'none'
backgroundColor: 'rgba(0, 0, 0, 0)'
module.exports = React.createClass
displayName: 'DrawingToolRoot'
statics:
distance: (x1, y1, x2, y2) ->
Math.sqrt Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)
getDefaultProps: ->
tool: null
getInitialState: ->
destroying: false
render: ->
toolProps = @props.tool.props
rootProps =
'data-disabled': toolProps.disabled or null
'data-selected': toolProps.selected or null
'data-destroying': @props.tool.state?.destroying or null
style: color: toolProps.color
scale = (toolProps.scale.horizontal + toolProps.scale.vertical) / 2
mainStyle =
fill: 'transparent'
stroke: 'currentColor'
strokeWidth: if toolProps.selected
SELECTED_STROKE_WIDTH / scale
else
STROKE_WIDTH / scale
unless toolProps.disabled
startHandler = toolProps.onSelect
<g className="drawing-tool" {...rootProps} {...@props}>
<g className="drawing-tool-main" {...mainStyle} onMouseDown={startHandler} onTouchStart={startHandler}>
{@props.children}
</g>
{if toolProps.selected and not toolProps.mark._inProgress and toolProps.details? and toolProps.details.length isnt 0
tasks = require '../tasks'
detailsAreComplete = toolProps.details.every (detailTask, i) =>
TaskComponent = tasks[detailTask.type]
if TaskComponent.isAnnotationComplete?
TaskComponent.isAnnotationComplete detailTask, toolProps.mark.details[i]
else
true
<StickyModalForm ref="detailsForm" style={SEMI_MODAL_FORM_STYLE} underlayStyle={SEMI_MODAL_UNDERLAY_STYLE} onSubmit={@handleDetailsFormClose} onCancel={@handleDetailsFormClose}>
{for detailTask, i in toolProps.details
detailTask._key ?= <KEY>()
TaskComponent = tasks[detailTask.type]
<TaskComponent autoFocus={i is 0} key={detailTask._key} task={detailTask} annotation={toolProps.mark.details[i]} onChange={@handleDetailsChange.bind this, i} />}
<hr />
<p style={textAlign: 'center'}>
<button type="submit" className="standard-button" disabled={not detailsAreComplete}>OK</button>
</p>
</StickyModalForm>}
</g>
componentDidUpdate: ->
this.refs.detailsForm?.reposition()
handleDetailsChange: (detailIndex, annotation) ->
@props.tool.props.mark.details[detailIndex] = annotation
@props.tool.props.onChange @props.tool.props.mark
handleDetailsFormClose: ->
# TODO: Check if the details tasks are complete.
@props.tool.props.onDeselect?()
| true | React = require 'react'
StickyModalForm = require 'modal-form/sticky'
STROKE_WIDTH = 1.5
SELECTED_STROKE_WIDTH = 2.5
SEMI_MODAL_FORM_STYLE =
pointerEvents: 'all'
SEMI_MODAL_UNDERLAY_STYLE =
pointerEvents: 'none'
backgroundColor: 'rgba(0, 0, 0, 0)'
module.exports = React.createClass
displayName: 'DrawingToolRoot'
statics:
distance: (x1, y1, x2, y2) ->
Math.sqrt Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)
getDefaultProps: ->
tool: null
getInitialState: ->
destroying: false
render: ->
toolProps = @props.tool.props
rootProps =
'data-disabled': toolProps.disabled or null
'data-selected': toolProps.selected or null
'data-destroying': @props.tool.state?.destroying or null
style: color: toolProps.color
scale = (toolProps.scale.horizontal + toolProps.scale.vertical) / 2
mainStyle =
fill: 'transparent'
stroke: 'currentColor'
strokeWidth: if toolProps.selected
SELECTED_STROKE_WIDTH / scale
else
STROKE_WIDTH / scale
unless toolProps.disabled
startHandler = toolProps.onSelect
<g className="drawing-tool" {...rootProps} {...@props}>
<g className="drawing-tool-main" {...mainStyle} onMouseDown={startHandler} onTouchStart={startHandler}>
{@props.children}
</g>
{if toolProps.selected and not toolProps.mark._inProgress and toolProps.details? and toolProps.details.length isnt 0
tasks = require '../tasks'
detailsAreComplete = toolProps.details.every (detailTask, i) =>
TaskComponent = tasks[detailTask.type]
if TaskComponent.isAnnotationComplete?
TaskComponent.isAnnotationComplete detailTask, toolProps.mark.details[i]
else
true
<StickyModalForm ref="detailsForm" style={SEMI_MODAL_FORM_STYLE} underlayStyle={SEMI_MODAL_UNDERLAY_STYLE} onSubmit={@handleDetailsFormClose} onCancel={@handleDetailsFormClose}>
{for detailTask, i in toolProps.details
detailTask._key ?= PI:KEY:<KEY>END_PI()
TaskComponent = tasks[detailTask.type]
<TaskComponent autoFocus={i is 0} key={detailTask._key} task={detailTask} annotation={toolProps.mark.details[i]} onChange={@handleDetailsChange.bind this, i} />}
<hr />
<p style={textAlign: 'center'}>
<button type="submit" className="standard-button" disabled={not detailsAreComplete}>OK</button>
</p>
</StickyModalForm>}
</g>
componentDidUpdate: ->
this.refs.detailsForm?.reposition()
handleDetailsChange: (detailIndex, annotation) ->
@props.tool.props.mark.details[detailIndex] = annotation
@props.tool.props.onChange @props.tool.props.mark
handleDetailsFormClose: ->
# TODO: Check if the details tasks are complete.
@props.tool.props.onDeselect?()
|
[
{
"context": "#original design by Jonathan Sorensen https://github.com/se5a \n\nclass ThumbWheel extend",
"end": 37,
"score": 0.9999019503593445,
"start": 20,
"tag": "NAME",
"value": "Jonathan Sorensen"
},
{
"context": "al design by Jonathan Sorensen https://github.com/se5a \n\nclass... | examples/applied/ThumbWheel/ThumbWheel.coffee | tstone/CoffeeSCad | 1 | #original design by Jonathan Sorensen https://github.com/se5a
class ThumbWheel extends Part
constructor:(options)->
@defaults = {total_radius : 30, base_height : 4, knobbles_num : 5,
knobbles_radius : 5, knobbles_height : 5, centerhole_radius : 1.55,
centerhex_radus : 3.1, centerhex_height : 2, centerhub_height : 4, centerhub_radius : 4}
options = @injectOptions(options, @defaults)
super options
distance_to_knobbles = @total_radius - @knobbles_radius
angleA = 360 / @knobbles_num
angleARadians = angleA * (3.14159265359 / 180)
# this function calculates the third side of a triangle from two sides(a,b) and an angle(A)
get_sideC = (side_a, side_b, angle_A) -> Math.sqrt (Math.pow(side_a, 2) + Math.pow(side_b, 2) - 2 * side_a * side_b * Math.cos(angle_A))
#the center hub:
hub = new Cylinder
h: @centerhub_height
r: @centerhub_radius
center: [0, 0, @centerhub_height / 2]
#the nut-trap:
hex = new Cylinder
h: @centerhex_height
r: @centerhex_radus
center: [0, 0, @centerhub_height - @centerhex_height / 2]
$fn: 6 # This sets the number of sides to six.
nuttrap = new Cylinder
h: @centerhub_height
r: @centerhole_radius
center: [0, 0, @centerhub_height / 2]
nuttrap = nuttrap.union(hex)
#the base
base = new Cylinder
h: @base_height
r: distance_to_knobbles
center: [0, 0, @base_height / 2]
#the little.... knobs.
knobble = new Cylinder
h: @knobbles_height
r: @knobbles_radius
center: [0, distance_to_knobbles, @knobbles_height / 2]
#distance between the nobbles:
knobble_seperation = get_sideC(distance_to_knobbles, distance_to_knobbles, angleARadians)
#the scooped out section between the nobbles:
scallop = new Cylinder
h: @base_height
r: (knobble_seperation - @knobbles_radius) / 2
center: [0, distance_to_knobbles, @base_height / 2]
scallop = scallop.rotate [0, 0, angleA / 2]
#carving the object
base.union(hub)
base.subtract(nuttrap)
#cutting out the scallops: (using while loop)
i = 0
while i < @knobbles_num
base.subtract(scallop.clone().rotate [0 ,0 , angleA * i])
i++
#adding the knobs: (using for loop)
for i in [0..@knobbles_num]
base.union(knobble.clone().rotate [0 , 0, angleA * i])
@union(base).color([0.7,0.2,0.1])
thumbWheel = new ThumbWheel()
assembly.add(thumbWheel)
| 21743 | #original design by <NAME> https://github.com/se5a
class ThumbWheel extends Part
constructor:(options)->
@defaults = {total_radius : 30, base_height : 4, knobbles_num : 5,
knobbles_radius : 5, knobbles_height : 5, centerhole_radius : 1.55,
centerhex_radus : 3.1, centerhex_height : 2, centerhub_height : 4, centerhub_radius : 4}
options = @injectOptions(options, @defaults)
super options
distance_to_knobbles = @total_radius - @knobbles_radius
angleA = 360 / @knobbles_num
angleARadians = angleA * (3.14159265359 / 180)
# this function calculates the third side of a triangle from two sides(a,b) and an angle(A)
get_sideC = (side_a, side_b, angle_A) -> Math.sqrt (Math.pow(side_a, 2) + Math.pow(side_b, 2) - 2 * side_a * side_b * Math.cos(angle_A))
#the center hub:
hub = new Cylinder
h: @centerhub_height
r: @centerhub_radius
center: [0, 0, @centerhub_height / 2]
#the nut-trap:
hex = new Cylinder
h: @centerhex_height
r: @centerhex_radus
center: [0, 0, @centerhub_height - @centerhex_height / 2]
$fn: 6 # This sets the number of sides to six.
nuttrap = new Cylinder
h: @centerhub_height
r: @centerhole_radius
center: [0, 0, @centerhub_height / 2]
nuttrap = nuttrap.union(hex)
#the base
base = new Cylinder
h: @base_height
r: distance_to_knobbles
center: [0, 0, @base_height / 2]
#the little.... knobs.
knobble = new Cylinder
h: @knobbles_height
r: @knobbles_radius
center: [0, distance_to_knobbles, @knobbles_height / 2]
#distance between the nobbles:
knobble_seperation = get_sideC(distance_to_knobbles, distance_to_knobbles, angleARadians)
#the scooped out section between the nobbles:
scallop = new Cylinder
h: @base_height
r: (knobble_seperation - @knobbles_radius) / 2
center: [0, distance_to_knobbles, @base_height / 2]
scallop = scallop.rotate [0, 0, angleA / 2]
#carving the object
base.union(hub)
base.subtract(nuttrap)
#cutting out the scallops: (using while loop)
i = 0
while i < @knobbles_num
base.subtract(scallop.clone().rotate [0 ,0 , angleA * i])
i++
#adding the knobs: (using for loop)
for i in [0..@knobbles_num]
base.union(knobble.clone().rotate [0 , 0, angleA * i])
@union(base).color([0.7,0.2,0.1])
thumbWheel = new ThumbWheel()
assembly.add(thumbWheel)
| true | #original design by PI:NAME:<NAME>END_PI https://github.com/se5a
class ThumbWheel extends Part
constructor:(options)->
@defaults = {total_radius : 30, base_height : 4, knobbles_num : 5,
knobbles_radius : 5, knobbles_height : 5, centerhole_radius : 1.55,
centerhex_radus : 3.1, centerhex_height : 2, centerhub_height : 4, centerhub_radius : 4}
options = @injectOptions(options, @defaults)
super options
distance_to_knobbles = @total_radius - @knobbles_radius
angleA = 360 / @knobbles_num
angleARadians = angleA * (3.14159265359 / 180)
# this function calculates the third side of a triangle from two sides(a,b) and an angle(A)
get_sideC = (side_a, side_b, angle_A) -> Math.sqrt (Math.pow(side_a, 2) + Math.pow(side_b, 2) - 2 * side_a * side_b * Math.cos(angle_A))
#the center hub:
hub = new Cylinder
h: @centerhub_height
r: @centerhub_radius
center: [0, 0, @centerhub_height / 2]
#the nut-trap:
hex = new Cylinder
h: @centerhex_height
r: @centerhex_radus
center: [0, 0, @centerhub_height - @centerhex_height / 2]
$fn: 6 # This sets the number of sides to six.
nuttrap = new Cylinder
h: @centerhub_height
r: @centerhole_radius
center: [0, 0, @centerhub_height / 2]
nuttrap = nuttrap.union(hex)
#the base
base = new Cylinder
h: @base_height
r: distance_to_knobbles
center: [0, 0, @base_height / 2]
#the little.... knobs.
knobble = new Cylinder
h: @knobbles_height
r: @knobbles_radius
center: [0, distance_to_knobbles, @knobbles_height / 2]
#distance between the nobbles:
knobble_seperation = get_sideC(distance_to_knobbles, distance_to_knobbles, angleARadians)
#the scooped out section between the nobbles:
scallop = new Cylinder
h: @base_height
r: (knobble_seperation - @knobbles_radius) / 2
center: [0, distance_to_knobbles, @base_height / 2]
scallop = scallop.rotate [0, 0, angleA / 2]
#carving the object
base.union(hub)
base.subtract(nuttrap)
#cutting out the scallops: (using while loop)
i = 0
while i < @knobbles_num
base.subtract(scallop.clone().rotate [0 ,0 , angleA * i])
i++
#adding the knobs: (using for loop)
for i in [0..@knobbles_num]
base.union(knobble.clone().rotate [0 , 0, angleA * i])
@union(base).color([0.7,0.2,0.1])
thumbWheel = new ThumbWheel()
assembly.add(thumbWheel)
|
[
{
"context": "sername: @options.username\n password: @options.password\n @client = new Client clientOptions\n\n g",
"end": 1143,
"score": 0.8437350392341614,
"start": 1127,
"tag": "PASSWORD",
"value": "options.password"
}
] | src/amazon.coffee | snd/amazon-associate | 42 | _ = require 'underscore'
moment = require 'moment'
Client = require './client'
ItemParser = require './item-parser'
ReportParser = require './report-parser'
parseResponse = (res, parser, cb) ->
parser.on 'error', (err) -> cb err
parser.on 'end', (result) -> cb null, result
res.on 'error', (err) -> cb err
res.on 'data', (data) -> parser.write data
res.on 'end', -> parser.close()
module.exports = class
debug: (args...) -> console.error 'amazon-associate:', args... if @options.debug
constructor: (@options) ->
throw new Error 'missing associateId option' if not @options.associateId?
throw new Error 'missing password option' if not @options.password?
_.defaults @options,
host: 'assoc-datafeeds-eu.amazon.com'
reportPath: '/datafeed/listReports'
username: @options.associateId
debug: false
clientOptions =
debug: @options.debug
credentials: {}
clientOptions.credentials[@options.host] =
type: 'digest'
username: @options.username
password: @options.password
@client = new Client clientOptions
getReportUrl: (date, type) ->
datestring = moment(date).format 'YYYYMMDD'
filename = "#{@options.associateId}-#{type}-report-#{datestring}.xml.gz"
"/datafeed/getReport?filename=#{filename}"
_getItems: (date, type, cb) ->
@client.request {
https: true
host: @options.host
path: @getReportUrl date, type
unzip: true
}, (err, res) ->
return cb err if err?
datestring = moment(date).format 'YYYY-MM-DD'
if res.headers['content-length'] is '0'
return cb new Error "no #{type} for date #{datestring}"
parser = new ItemParser
parseResponse res, parser, cb
getOrders: (date, cb) -> @_getItems date, 'orders', cb
getEarnings: (date, cb) -> @_getItems date, 'earnings', cb
getReports: (cb) ->
@client.request {
https: true
host: @options.host
path: @options.reportPath
unzip: false
}, (err, res) ->
return cb err if err?
parser = new ReportParser
parseResponse res, parser, cb
| 133085 | _ = require 'underscore'
moment = require 'moment'
Client = require './client'
ItemParser = require './item-parser'
ReportParser = require './report-parser'
parseResponse = (res, parser, cb) ->
parser.on 'error', (err) -> cb err
parser.on 'end', (result) -> cb null, result
res.on 'error', (err) -> cb err
res.on 'data', (data) -> parser.write data
res.on 'end', -> parser.close()
module.exports = class
debug: (args...) -> console.error 'amazon-associate:', args... if @options.debug
constructor: (@options) ->
throw new Error 'missing associateId option' if not @options.associateId?
throw new Error 'missing password option' if not @options.password?
_.defaults @options,
host: 'assoc-datafeeds-eu.amazon.com'
reportPath: '/datafeed/listReports'
username: @options.associateId
debug: false
clientOptions =
debug: @options.debug
credentials: {}
clientOptions.credentials[@options.host] =
type: 'digest'
username: @options.username
password: @<PASSWORD>
@client = new Client clientOptions
getReportUrl: (date, type) ->
datestring = moment(date).format 'YYYYMMDD'
filename = "#{@options.associateId}-#{type}-report-#{datestring}.xml.gz"
"/datafeed/getReport?filename=#{filename}"
_getItems: (date, type, cb) ->
@client.request {
https: true
host: @options.host
path: @getReportUrl date, type
unzip: true
}, (err, res) ->
return cb err if err?
datestring = moment(date).format 'YYYY-MM-DD'
if res.headers['content-length'] is '0'
return cb new Error "no #{type} for date #{datestring}"
parser = new ItemParser
parseResponse res, parser, cb
getOrders: (date, cb) -> @_getItems date, 'orders', cb
getEarnings: (date, cb) -> @_getItems date, 'earnings', cb
getReports: (cb) ->
@client.request {
https: true
host: @options.host
path: @options.reportPath
unzip: false
}, (err, res) ->
return cb err if err?
parser = new ReportParser
parseResponse res, parser, cb
| true | _ = require 'underscore'
moment = require 'moment'
Client = require './client'
ItemParser = require './item-parser'
ReportParser = require './report-parser'
parseResponse = (res, parser, cb) ->
parser.on 'error', (err) -> cb err
parser.on 'end', (result) -> cb null, result
res.on 'error', (err) -> cb err
res.on 'data', (data) -> parser.write data
res.on 'end', -> parser.close()
module.exports = class
debug: (args...) -> console.error 'amazon-associate:', args... if @options.debug
constructor: (@options) ->
throw new Error 'missing associateId option' if not @options.associateId?
throw new Error 'missing password option' if not @options.password?
_.defaults @options,
host: 'assoc-datafeeds-eu.amazon.com'
reportPath: '/datafeed/listReports'
username: @options.associateId
debug: false
clientOptions =
debug: @options.debug
credentials: {}
clientOptions.credentials[@options.host] =
type: 'digest'
username: @options.username
password: @PI:PASSWORD:<PASSWORD>END_PI
@client = new Client clientOptions
getReportUrl: (date, type) ->
datestring = moment(date).format 'YYYYMMDD'
filename = "#{@options.associateId}-#{type}-report-#{datestring}.xml.gz"
"/datafeed/getReport?filename=#{filename}"
_getItems: (date, type, cb) ->
@client.request {
https: true
host: @options.host
path: @getReportUrl date, type
unzip: true
}, (err, res) ->
return cb err if err?
datestring = moment(date).format 'YYYY-MM-DD'
if res.headers['content-length'] is '0'
return cb new Error "no #{type} for date #{datestring}"
parser = new ItemParser
parseResponse res, parser, cb
getOrders: (date, cb) -> @_getItems date, 'orders', cb
getEarnings: (date, cb) -> @_getItems date, 'earnings', cb
getReports: (cb) ->
@client.request {
https: true
host: @options.host
path: @options.reportPath
unzip: false
}, (err, res) ->
return cb err if err?
parser = new ReportParser
parseResponse res, parser, cb
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999130368232727,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/store-supporter-tag-price.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.
class @StoreSupporterTagPrice
@durationToPrice: (duration) ->
duration = +duration
switch
when duration >= 12 then Math.ceil(duration / 12.0 * 26)
when duration == 10 then 24
when duration == 9 then 22
when duration == 8 then 20
when duration == 6 then 16
when duration == 4 then 12
when duration == 2 then 8
when duration == 1 then 4
constructor: (price) ->
@_price = price
price: ->
@_price
duration: ->
@_duration ?= switch
when @_price >= 26 then Math.floor(@_price / 26.0 * 12)
when @_price >= 24 then 10
when @_price >= 22 then 9
when @_price >= 20 then 8
when @_price >= 16 then 6
when @_price >= 12 then 4
when @_price >= 8 then 2
when @_price >= 4 then 1
else 0
pricePerMonth: ->
osu.formatNumber(@_price / @duration(), 2)
discount: ->
if @duration() >= 12
46
else
raw = ((1 - (@_price / @duration()) / 4) * 100)
Math.max(0, Math.round(raw, 0))
discountText: ->
osu.trans('store.discount', percent: @discount())
durationInYears: ->
years: Math.floor(@duration() / 12)
months: Math.floor(@duration() % 12)
durationText: ->
# don't forget to update SupporterTag::getDurationText() in php
duration = @durationInYears()
texts = []
if duration.years > 0
texts.push osu.transChoice('common.count.years', duration.years)
if duration.months > 0
texts.push osu.transChoice('common.count.months', duration.months)
texts.join(', ')
| 12405 | # 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.
class @StoreSupporterTagPrice
@durationToPrice: (duration) ->
duration = +duration
switch
when duration >= 12 then Math.ceil(duration / 12.0 * 26)
when duration == 10 then 24
when duration == 9 then 22
when duration == 8 then 20
when duration == 6 then 16
when duration == 4 then 12
when duration == 2 then 8
when duration == 1 then 4
constructor: (price) ->
@_price = price
price: ->
@_price
duration: ->
@_duration ?= switch
when @_price >= 26 then Math.floor(@_price / 26.0 * 12)
when @_price >= 24 then 10
when @_price >= 22 then 9
when @_price >= 20 then 8
when @_price >= 16 then 6
when @_price >= 12 then 4
when @_price >= 8 then 2
when @_price >= 4 then 1
else 0
pricePerMonth: ->
osu.formatNumber(@_price / @duration(), 2)
discount: ->
if @duration() >= 12
46
else
raw = ((1 - (@_price / @duration()) / 4) * 100)
Math.max(0, Math.round(raw, 0))
discountText: ->
osu.trans('store.discount', percent: @discount())
durationInYears: ->
years: Math.floor(@duration() / 12)
months: Math.floor(@duration() % 12)
durationText: ->
# don't forget to update SupporterTag::getDurationText() in php
duration = @durationInYears()
texts = []
if duration.years > 0
texts.push osu.transChoice('common.count.years', duration.years)
if duration.months > 0
texts.push osu.transChoice('common.count.months', duration.months)
texts.join(', ')
| 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.
class @StoreSupporterTagPrice
@durationToPrice: (duration) ->
duration = +duration
switch
when duration >= 12 then Math.ceil(duration / 12.0 * 26)
when duration == 10 then 24
when duration == 9 then 22
when duration == 8 then 20
when duration == 6 then 16
when duration == 4 then 12
when duration == 2 then 8
when duration == 1 then 4
constructor: (price) ->
@_price = price
price: ->
@_price
duration: ->
@_duration ?= switch
when @_price >= 26 then Math.floor(@_price / 26.0 * 12)
when @_price >= 24 then 10
when @_price >= 22 then 9
when @_price >= 20 then 8
when @_price >= 16 then 6
when @_price >= 12 then 4
when @_price >= 8 then 2
when @_price >= 4 then 1
else 0
pricePerMonth: ->
osu.formatNumber(@_price / @duration(), 2)
discount: ->
if @duration() >= 12
46
else
raw = ((1 - (@_price / @duration()) / 4) * 100)
Math.max(0, Math.round(raw, 0))
discountText: ->
osu.trans('store.discount', percent: @discount())
durationInYears: ->
years: Math.floor(@duration() / 12)
months: Math.floor(@duration() % 12)
durationText: ->
# don't forget to update SupporterTag::getDurationText() in php
duration = @durationInYears()
texts = []
if duration.years > 0
texts.push osu.transChoice('common.count.years', duration.years)
if duration.months > 0
texts.push osu.transChoice('common.count.months', duration.months)
texts.join(', ')
|
[
{
"context": "nt controller\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hype",
"end": 72,
"score": 0.9994404315948486,
"start": 66,
"tag": "USERNAME",
"value": "nodize"
},
{
"context": "://github.com/nodize/nodizecms\n#\n# Copyright 2... | modules/backend/controllers/ctrl_user.coffee | nodize/nodizecms | 32 | # Users management controller
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Displaying USERS EDITION PAGE
#
@get '/:lang/admin/users' : ->
loadGroups = ->
User_group.findAll({order:"level"})
.on 'success', (user_groups) ->
renderPage( user_groups )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user_groups) =>
@render "backend_users",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user_groups : user_groups
loadGroups()
#
# Displaying USER LIST
#
@post '/:lang/admin/users/users_list' : ->
groups = {}
loadGroups =->
User_group.findAll()
.on 'success', (user_groups) ->
groups[group.id_group] = group.group_name for group in user_groups
loadUsers()
.on 'failure', (err) ->
console.log 'database error ', err
loadUsers = ->
User.findAll({order:"username"})
.on 'success', (users) ->
renderPage( users )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (users) =>
@render "backend_userList",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
users : users
groups : groups
loadGroups()
#
# CREATE a new USER
#
@post '/:lang/admin/users/save' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if values.password is values.password2
userSave()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
userSave = ->
user = User.build()
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
user.join_date = new Date()
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user creation', err
.on 'failure', (err) ->
console.log 'database error on user creation', err
#
# Start process
#
checkPassword()
#
# UPDATE USER
#
@post '/:lang/admin/users/update' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if (values.password is values.password2) or (values.password is "" and values.password2 is "")
loadUser()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
loadUser = ->
User.find({where:{id_user:values.user_PK}})
.on 'success', (user) ->
userSave(user)
.on 'failure', (err) ->
console.log 'database error ', err
userSave = (user) ->
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
if (values.password isnt "")
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user update', err
.on 'failure', (err) ->
console.log 'database error on user update', err
#
# Start process
#
checkPassword()
#
# EDIT USER
#
@post '/:lang/admin/users/edit/:id_user' : (req) ->
groups = null
loadGroups = ->
User_group.findAll()
.on 'success', (user_groups) ->
#groups[group.id_group] = group.group_name for group in user_groups
groups = user_groups
loadUser( )
.on 'failure', (err) ->
console.log 'database error ', err
loadUser = ->
User.find({where:{id_user:req.params.id_user}})
.on 'success', (user) ->
renderPage(user)
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user) =>
@render "backend_user",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user : user
groups : groups
#
# Start process
#
loadGroups()
#
# DELETE an USER
#
@post '/:lang/admin/users/delete/:id_user' : (req, resy) ->
findUser = =>
User.find({where:{id_user:@params.id_user}})
.on 'success', (user) ->
removeUser( user )
.on 'failure', (err) ->
console.log 'database error ', err
removeUser = (user) ->
user.destroy()
.on 'success', (user) ->
message =
message_type:"success"
message:"User deleted"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
id:user.id_user
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
#
# Start process
#
findUser()
| 12095 | # Users management controller
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Displaying USERS EDITION PAGE
#
@get '/:lang/admin/users' : ->
loadGroups = ->
User_group.findAll({order:"level"})
.on 'success', (user_groups) ->
renderPage( user_groups )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user_groups) =>
@render "backend_users",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user_groups : user_groups
loadGroups()
#
# Displaying USER LIST
#
@post '/:lang/admin/users/users_list' : ->
groups = {}
loadGroups =->
User_group.findAll()
.on 'success', (user_groups) ->
groups[group.id_group] = group.group_name for group in user_groups
loadUsers()
.on 'failure', (err) ->
console.log 'database error ', err
loadUsers = ->
User.findAll({order:"username"})
.on 'success', (users) ->
renderPage( users )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (users) =>
@render "backend_userList",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
users : users
groups : groups
loadGroups()
#
# CREATE a new USER
#
@post '/:lang/admin/users/save' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if values.password is values.<PASSWORD>
userSave()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
userSave = ->
user = User.build()
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
user.join_date = new Date()
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user creation', err
.on 'failure', (err) ->
console.log 'database error on user creation', err
#
# Start process
#
checkPassword()
#
# UPDATE USER
#
@post '/:lang/admin/users/update' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if (values.password is values.password2) or (values.password is "" and values.password2 is "")
loadUser()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
loadUser = ->
User.find({where:{id_user:values.user_PK}})
.on 'success', (user) ->
userSave(user)
.on 'failure', (err) ->
console.log 'database error ', err
userSave = (user) ->
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
if (values.password isnt "")
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user update', err
.on 'failure', (err) ->
console.log 'database error on user update', err
#
# Start process
#
checkPassword()
#
# EDIT USER
#
@post '/:lang/admin/users/edit/:id_user' : (req) ->
groups = null
loadGroups = ->
User_group.findAll()
.on 'success', (user_groups) ->
#groups[group.id_group] = group.group_name for group in user_groups
groups = user_groups
loadUser( )
.on 'failure', (err) ->
console.log 'database error ', err
loadUser = ->
User.find({where:{id_user:req.params.id_user}})
.on 'success', (user) ->
renderPage(user)
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user) =>
@render "backend_user",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user : user
groups : groups
#
# Start process
#
loadGroups()
#
# DELETE an USER
#
@post '/:lang/admin/users/delete/:id_user' : (req, resy) ->
findUser = =>
User.find({where:{id_user:@params.id_user}})
.on 'success', (user) ->
removeUser( user )
.on 'failure', (err) ->
console.log 'database error ', err
removeUser = (user) ->
user.destroy()
.on 'success', (user) ->
message =
message_type:"success"
message:"User deleted"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
id:user.id_user
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
#
# Start process
#
findUser()
| true | # Users management controller
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Displaying USERS EDITION PAGE
#
@get '/:lang/admin/users' : ->
loadGroups = ->
User_group.findAll({order:"level"})
.on 'success', (user_groups) ->
renderPage( user_groups )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user_groups) =>
@render "backend_users",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user_groups : user_groups
loadGroups()
#
# Displaying USER LIST
#
@post '/:lang/admin/users/users_list' : ->
groups = {}
loadGroups =->
User_group.findAll()
.on 'success', (user_groups) ->
groups[group.id_group] = group.group_name for group in user_groups
loadUsers()
.on 'failure', (err) ->
console.log 'database error ', err
loadUsers = ->
User.findAll({order:"username"})
.on 'success', (users) ->
renderPage( users )
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (users) =>
@render "backend_userList",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
users : users
groups : groups
loadGroups()
#
# CREATE a new USER
#
@post '/:lang/admin/users/save' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if values.password is values.PI:PASSWORD:<PASSWORD>END_PI
userSave()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
userSave = ->
user = User.build()
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
user.join_date = new Date()
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user creation', err
.on 'failure', (err) ->
console.log 'database error on user creation', err
#
# Start process
#
checkPassword()
#
# UPDATE USER
#
@post '/:lang/admin/users/update' : (req, res) ->
values = req.body
checkPassword = =>
#
# Checking if passwords are matching
#
if (values.password is values.password2) or (values.password is "" and values.password2 is "")
loadUser()
else
message =
message_type:"error"
message:"Passwords must match"
update:[]
callback:null
@send message
loadUser = ->
User.find({where:{id_user:values.user_PK}})
.on 'success', (user) ->
userSave(user)
.on 'failure', (err) ->
console.log 'database error ', err
userSave = (user) ->
user.username = values.username
user.screen_name = values.screen_name
user.id_group = values.id_group
user.email = values.email
if (values.password isnt "")
#
# Building a password hash
#
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
hash = hmac.update values.password
user.password = hash.digest(encoding="base64")
user.save()
.on 'success', (user) ->
user.id = user.id_user
user.save()
.on 'success', (user) ->
message =
message_type:"success"
message:"User saved"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
res.send message
.on 'failure', (err) ->
console.log 'database error on user update', err
.on 'failure', (err) ->
console.log 'database error on user update', err
#
# Start process
#
checkPassword()
#
# EDIT USER
#
@post '/:lang/admin/users/edit/:id_user' : (req) ->
groups = null
loadGroups = ->
User_group.findAll()
.on 'success', (user_groups) ->
#groups[group.id_group] = group.group_name for group in user_groups
groups = user_groups
loadUser( )
.on 'failure', (err) ->
console.log 'database error ', err
loadUser = ->
User.find({where:{id_user:req.params.id_user}})
.on 'success', (user) ->
renderPage(user)
.on 'failure', (err) ->
console.log 'database error ', err
renderPage = (user) =>
@render "backend_user",
layout : no
hardcode : @helpers
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
user : user
groups : groups
#
# Start process
#
loadGroups()
#
# DELETE an USER
#
@post '/:lang/admin/users/delete/:id_user' : (req, resy) ->
findUser = =>
User.find({where:{id_user:@params.id_user}})
.on 'success', (user) ->
removeUser( user )
.on 'failure', (err) ->
console.log 'database error ', err
removeUser = (user) ->
user.destroy()
.on 'success', (user) ->
message =
message_type:"success"
message:"User deleted"
update:[
element:"mainPanel"
url: "\/admin\/users"
]
callback:null
id:user.id_user
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
#
# Start process
#
findUser()
|
[
{
"context": "eamScore.sessionID]\n topPlayers.push {name: playerName, userID: userID, sessionID: teamScore.session",
"end": 21307,
"score": 0.9995098114013672,
"start": 21301,
"tag": "NAME",
"value": "player"
},
{
"context": "e.sessionID]\n topPlayers.push {name: playe... | scripts/tournaments/download-tournament-results.coffee | JurianLock/codecombat | 2 | filePrefix = 'https://s3.amazonaws.com/ace-of-coders-simulation-results/'
files = [
'1445213331501451880.json'
'1445213333962624756.json'
'1445213336952262072.json'
'1445213340108350108.json'
'1445213343518140279.json'
'1445213347272483737.json'
'1445213351108262273.json'
'1445213354532639917.json'
'1445213357911513320.json'
'1445213361197631052.json'
'1445213364294940845.json'
'1445213368224989716.json'
'1445213372340479451.json'
'1445213375994169440.json'
'1445213379655103566.json'
'1445213383878314932.json'
'1445213387576330718.json'
'1445213391319951764.json'
'1445213395297284000.json'
'1445213398793484459.json'
'1445213403418993676.json'
'1445213407644707083.json'
'1445213410735647885.json'
'1445213414261150207.json'
'1445213417601033684.json'
'1445213421225330915.json'
'1445213425505538665.json'
'1445213429189103401.json'
'1445213433364370512.json'
'1445213436961513794.json'
'1445213439998252285.json'
'1445213445045520520.json'
'1445213449514608844.json'
'1445213453116282525.json'
'1445213457095637020.json'
'1445213460704753277.json'
'1445213464286547013.json'
'1445213468520080180.json'
'1445213472106072387.json'
'1445213475820365779.json'
'1445213480580483030.json'
'1445213483578157536.json'
'1445213487510887752.json'
'1445213491558872807.json'
'1445213499351461770.json'
'1445213502056807146.json'
'1445213505127336236.json'
'1445213508557502702.json'
'1445213511896396212.json'
'1445213515853887904.json'
'1445213519294758676.json'
'1445213523374005620.json'
'1445213527496735584.json'
'1445213531143063123.json'
'1445213535511651949.json'
'1445213539690176930.json'
'1445213543065367025.json'
'1445213546810986010.json'
'1445213550501273173.json'
'1445213554189924874.json'
'1445213565085119935.json'
'1445213568793830161.json'
'1445213572104047422.json'
'1445213577145506271.json'
'1445213581528093563.json'
'1445213584895451031.json'
'1445213588650931726.json'
'1445213592177781823.json'
'1445213594397225133.json'
'1445221277361358834.json'
'1445221279698497496.json'
'1445221282315153388.json'
'1445221285394137604.json'
'1445221288550371312.json'
'1445221291830712255.json'
'1445221295617755173.json'
'1445221299055851329.json'
'1445221302667030249.json'
'1445221306924823599.json'
'1445221310544601607.json'
'1445221314153960734.json'
'1445221317487106931.json'
'1445221320530978932.json'
'1445221324301371325.json'
'1445221327649700997.json'
'1445221331374603621.json'
'1445221335264382014.json'
'1445221338855628920.json'
'1445221342321774765.json'
'1445221346170926762.json'
'1445221349294564500.json'
'1445221352675532474.json'
'1445221356123574608.json'
'1445221359799314313.json'
'1445221363414713316.json'
'1445221367642102253.json'
'1445221371845170779.json'
'1445221375641841704.json'
'1445221379533766000.json'
'1445221383130035077.json'
'1445221386448295330.json'
'1445221390256020947.json'
'1445221393909487800.json'
'1445221397412673003.json'
'1445221401217854685.json'
'1445221404679522730.json'
'1445221408191448392.json'
'1445221411888158269.json'
'1445221415264332233.json'
'1445221419271950364.json'
'1445221423107421701.json'
'1445221454202101214.json'
'1445221474185597968.json'
'1445230073430754517.json'
'1445230075829988193.json'
'1445230078380093476.json'
'1445230080916882830.json'
'1445230084070294552.json'
'1445230087655859195.json'
'1445230091230254125.json'
'1445230094958575254.json'
'1445230102042734819.json'
'1445230105583567102.json'
'1445230110098843063.json'
'1445230113969801967.json'
'1445230117841812597.json'
'1445230122016639650.json'
'1445230126024689010.json'
'1445230129401404124.json'
'1445230132995295000.json'
'1445230136363195000.json'
'1445230139829326559.json'
'1445230143133819179.json'
'1445230146494641982.json'
'1445230149891696294.json'
'1445230153496417929.json'
'1445230157420298551.json'
'1445230161146744249.json'
'1445230164540033734.json'
'1445230168998013060.json'
'1445230172276532046.json'
'1445230175968137164.json'
'1445230179403344385.json'
'1445230182841026516.json'
'1445230186681159479.json'
'1445230190432845401.json'
'1445230194900203984.json'
'1445230198345037383.json'
'1445230202459027705.json'
'1445230205900628657.json'
'1445230209224723942.json'
'1445230213367015311.json'
'1445230220444856604.json'
'1445230223646143199.json'
'1445230227051947244.json'
'1445230230605632712.json'
'1445230234132435840.json'
'1445230237966858392.json'
'1445230241997606689.json'
'1445230245378549461.json'
'1445230248791558064.json'
'1445230252242695234.json'
'1445230255924413167.json'
'1445230259930682818.json'
'1445230263564875800.json'
'1445230267601339066.json'
'1445230271397215053.json'
'1445230275230599755.json'
'1445230278557392386.json'
'1445230282300585592.json'
'1445230285806493395.json'
'1445230289296758798.json'
'1445230292932839638.json'
'1445230296834477367.json'
'1445230300429749446.json'
'1445230304505276137.json'
'1445230307932189005.json'
'1445230311810878110.json'
'1445230315521992848.json'
'1445230318874365773.json'
'1445230322501494654.json'
'1445230326357408114.json'
'1445230330375479959.json'
'1445230334162974388.json'
'1445230337876792548.json'
'1445230341199978481.json'
'1445230344790949698.json'
'1445230348202193367.json'
'1445230351464998190.json'
'1445230355501490291.json'
'1445230359281495971.json'
'1445230363228852324.json'
'1445230366952366378.json'
'1445230370639190487.json'
'1445230374325745381.json'
'1445230377345716000.json'
'1445230380547954192.json'
'1445230384009635808.json'
'1445230387619920999.json'
'1445230391249215619.json'
'1445230395050707005.json'
'1445230398729998271.json'
'1445230402574142636.json'
'1445230406134099482.json'
'1445230409763088472.json'
'1445230413980744826.json'
'1445230427755574837.json'
'1445230430530442943.json'
'1445230433698560888.json'
'1445230437098330832.json'
'1445230440508211654.json'
'1445230444603413823.json'
'1445230448464331046.json'
'1445230451905017875.json'
'1445230455330580775.json'
'1445230459159341642.json'
'1445230463274827425.json'
'1445230467631616726.json'
'1445230471380124991.json'
'1445230475001827687.json'
'1445230478421377779.json'
'1445230482501165731.json'
'1445230489169162067.json'
'1445230492655384286.json'
'1445230496133865127.json'
'1445230499740257000.json'
'1445230503651978021.json'
'1445230507713678144.json'
'1445230511095700007.json'
'1445230513519495119.json'
'1445268620016907631.json'
'1445268622122827559.json'
'1445268624140776755.json'
'1445268626246517429.json'
'1445268628577795578.json'
'1445268630768718013.json'
'1445268632895287713.json'
'1445268635070637388.json'
'1445268637363693700.json'
'1445268639421901763.json'
'1445268641731929243.json'
'1445268644190182245.json'
'1445268646249862525.json'
'1445268648428272556.json'
'1445268650914877177.json'
'1445268653098586788.json'
'1445268655348101903.json'
'1445268657510578000.json'
'1445268659754499998.json'
'1445268662045588316.json'
'1445268664277727860.json'
'1445268666452725794.json'
'1445268668805764606.json'
'1445268670997451288.json'
'1445268673114680160.json'
'1445268675329202192.json'
'1445268677513490711.json'
'1445268679783287172.json'
'1445268682036031414.json'
'1445268684129371531.json'
'1445268686425970598.json'
'1445268688720167258.json'
'1445268691192558105.json'
'1445268693591401980.json'
'1445268695781357250.json'
'1445268698045096075.json'
'1445268700150717503.json'
'1445268702398420842.json'
'1445268704720775279.json'
'1445268707063564355.json'
'1445268709338713945.json'
'1445268711632755548.json'
'1445268713768604227.json'
'1445268716174246278.json'
'1445268718396569875.json'
'1445268720560126457.json'
'1445268722729210983.json'
'1445268724924585705.json'
'1445268727102603087.json'
'1445268729116745670.json'
'1445268731363535604.json'
'1445268733669265741.json'
'1445268735955645041.json'
'1445268738219628792.json'
'1445268740422156492.json'
'1445268742575678088.json'
'1445268744783311234.json'
'1445268746965546913.json'
'1445268749160417454.json'
'1445268751560320842.json'
'1445268753823934772.json'
'1445268756018962812.json'
'1445268758417436266.json'
'1445268760592037000.json'
'1445268762650074634.json'
'1445268764724292438.json'
'1445268766920232465.json'
'1445268769106959357.json'
'1445268771359267849.json'
'1445268773629836795.json'
'1445268775790855329.json'
'1445268777998775005.json'
'1445268780377269826.json'
'1445268782636835024.json'
'1445268785105088940.json'
'1445268787394903774.json'
'1445268789625324163.json'
'1445268791928562868.json'
'1445268794097570133.json'
'1445268796336624399.json'
'1445268798631516823.json'
'1445268801543146203.json'
'1445268803720916221.json'
'1445268806117659719.json'
'1445268808328143702.json'
'1445268810583045236.json'
'1445268812868210294.json'
'1445268815044910115.json'
'1445268817371573566.json'
'1445268819837082598.json'
'1445268822186030265.json'
'1445268824529238254.json'
'1445268826698333397.json'
'1445268829048336564.json'
'1445268831119849897.json'
'1445268833179695745.json'
'1445268835355203152.json'
'1445268837405461490.json'
'1445268839507117921.json'
'1445268841769599236.json'
'1445268843884382755.json'
'1445268846071503011.json'
'1445268848349572818.json'
'1445268850524364412.json'
'1445268852776213937.json'
'1445268854920734373.json'
'1445268857126237087.json'
'1445268859310201176.json'
'1445268861561857965.json'
'1445268864105148024.json'
'1445268866197882910.json'
'1445268868353326182.json'
'1445268870516655449.json'
'1445268872673508915.json'
'1445268874762479150.json'
'1445268877164751364.json'
'1445268879286935114.json'
'1445268881328685986.json'
'1445268883445195315.json'
'1445268885647373744.json'
'1445268887906137602.json'
'1445268890210873534.json'
'1445268892285821181.json'
'1445268894477987144.json'
'1445268896586339497.json'
'1445268898783556149.json'
'1445268901026137511.json'
'1445268903288629511.json'
'1445268905632999958.json'
'1445268907769137075.json'
'1445268910210199749.json'
'1445268912487917439.json'
'1445268914699519986.json'
'1445268916872093395.json'
'1445268919162358705.json'
'1445268921364723116.json'
'1445268923529045633.json'
'1445268925634767250.json'
'1445268927773354402.json'
'1445268930024845244.json'
'1445268932347541598.json'
'1445268934554593819.json'
'1445268936774699728.json'
'1445268939055730840.json'
'1445268941103213627.json'
'1445268943288510342.json'
'1445268945472849529.json'
'1445268947571262875.json'
'1445268949842113619.json'
'1445268953053002587.json'
'1445268955705618031.json'
'1445268957931907119.json'
'1445268960079462662.json'
'1445268962482269944.json'
'1445268964595501883.json'
'1445268966774301554.json'
'1445268969043544169.json'
'1445268971228990112.json'
'1445268973718788263.json'
'1445268975915972005.json'
'1445268978092369714.json'
'1445268980221048405.json'
'1445268982462277288.json'
'1445268984704104467.json'
'1445268986851463154.json'
'1445268988870702929.json'
'1445268991174718359.json'
'1445268993166842169.json'
'1445268995482530004.json'
'1445268997698069030.json'
'1445268999856627198.json'
'1445269001963981298.json'
'1445269005128881832.json'
'1445269007631174328.json'
'1445269010567701718.json'
'1445269012840178714.json'
'1445269015063741658.json'
'1445269017242828233.json'
'1445269019421232891.json'
'1445269021824220288.json'
'1445269023938605981.json'
'1445269026409208695.json'
'1445269028509058790.json'
'1445269030524896000.json'
'1445269032756824238.json'
'1445269035159289304.json'
'1445269037366243450.json'
'1445269039465047380.json'
'1445269041701586560.json'
'1445269043788403673.json'
'1445269046045728613.json'
'1445269048151202850.json'
'1445269050459992316.json'
'1445269053004557688.json'
'1445269055349225134.json'
'1445269057525643140.json'
'1445269059934835285.json'
'1445269062110045209.json'
'1445269064274679000.json'
'1445269066451272607.json'
'1445269068728772237.json'
'1445269070877790585.json'
'1445269073109715995.json'
'1445269075306781702.json'
'1445269077338016409.json'
'1445269079599082477.json'
'1445269081901931619.json'
'1445269083937350893.json'
'1445269086606168066.json'
'1445269089749719526.json'
'1445269092912378322.json'
'1445269095068300466.json'
'1445269097105610715.json'
'1445269099340915790.json'
'1445269101634711008.json'
'1445269103883171321.json'
'1445269105915454000.json'
'1445269108167686595.json'
'1445269110361203248.json'
'1445269112791210489.json'
'1445269119000963903.json'
'1445269122719487762.json'
'1445269125411006548.json'
'1445269127762964020.json'
'1445269129836155861.json'
'1445269132111575135.json'
'1445269134217570416.json'
'1445269136543021559.json'
'1445269138695139898.json'
'1445269140914567682.json'
'1445269142942098025.json'
'1445269145044930788.json'
'1445269147248686797.json'
'1445269149522984507.json'
'1445269152161285087.json'
'1445269155322986789.json'
'1445269157818898906.json'
'1445269160044484047.json'
'1445269162266085471.json'
'1445269164442888373.json'
'1445269166529441082.json'
'1445269168855231051.json'
'1445269171132400258.json'
'1445269173209510973.json'
'1445269175360974881.json'
'1445269177391806404.json'
'1445269179564059457.json'
'1445269181918334941.json'
'1445269184183064047.json'
'1445269186482660799.json'
'1445269188582405643.json'
'1445269190635432324.json'
'1445269192856263789.json'
'1445269195038404565.json'
'1445269197102021853.json'
'1445269199482726135.json'
'1445269201660257229.json'
'1445269203942103478.json'
'1445269206237893322.json'
'1445269208456870810.json'
'1445269210788885279.json'
'1445269213239724034.json'
'1445269215451086036.json'
'1445269217647945453.json'
'1445269220046288284.json'
'1445269222236265440.json'
'1445269224505994866.json'
'1445269226825172010.json'
'1445269229116949026.json'
'1445269231489543733.json'
'1445269233755357471.json'
'1445269235911648747.json'
'1445269237999553699.json'
'1445269240508365024.json'
'1445269242722009927.json'
'1445269244934195076.json'
'1445269247162195032.json'
'1445269249236953713.json'
'1445269251458578943.json'
'1445269253487689604.json'
'1445269255696323064.json'
'1445269257949099645.json'
'1445269260191632330.json'
'1445269262355329886.json'
'1445269264566769605.json'
'1445269266964329940.json'
'1445269269227593807.json'
'1445269271514201936.json'
'1445269273612398920.json'
'1445269275884684268.json'
'1445269278076892764.json'
'1445269280310865878.json'
'1445269282424623299.json'
'1445269284715336825.json'
'1445269286688556553.json'
'1445269288887242319.json'
'1445269291073998385.json'
'1445269293108399667.json'
'1445269295212448901.json'
'1445269297426394018.json'
'1445269299599447234.json'
'1445269301729933144.json'
'1445269303996496226.json'
'1445269306270930877.json'
'1445269308476918049.json'
'1445269310582680614.json'
'1445269312690229962.json'
'1445269314892409324.json'
'1445269316980608523.json'
'1445269319006449029.json'
'1445269321185755416.json'
'1445269323341804973.json'
'1445269325664755068.json'
'1445269327834759470.json'
'1445269330069526259.json'
'1445269332287771312.json'
'1445269334385516439.json'
'1445269336657750533.json'
'1445269338838256481.json'
'1445269340977045479.json'
'1445269343278893069.json'
'1445269345423148790.json'
'1445269347428235854.json'
'1445269349635316570.json'
'1445269351688263000.json'
'1445269354011647956.json'
'1445269356113719565.json'
'1445269358229515145.json'
'1445269360612105490.json'
'1445269362922818774.json'
'1445269365222636184.json'
'1445269367513280151.json'
'1445269370028699953.json'
'1445269372414990361.json'
'1445269374641788750.json'
'1445269377029996590.json'
'1445269379312073874.json'
'1445269381603113183.json'
'1445269383813588267.json'
'1445269386078574000.json'
'1445269388353640395.json'
'1445269390574915000.json'
'1445269392800924652.json'
'1445269395085481942.json'
'1445269397341246657.json'
'1445269399473830151.json'
'1445269401846739679.json'
'1445269404175824085.json'
'1445269406294316012.json'
'1445269408513123706.json'
'1445269410750656000.json'
'1445269413028587778.json'
'1445269415145683723.json'
'1445269417477899634.json'
'1445269419689952826.json'
'1445269421916883311.json'
'1445269424069113886.json'
'1445269426389494628.json'
'1445269427373333034.json'
'1445269898973248759.json'
'1445269901101787379.json'
'1445269902613155311.json'
]
request = require '../../node_modules/request'
allSessionIDs = {}
usernamesBySessionID = {}
userIDsBySessionID = {}
codeLanguagesByUserID = {}
teamNames = ['humans', 'ogres']
matchesByTeam = {humans: {}, ogres: {}}
# Each object's first keys are first team session IDs, second are alternate teams' session IDs.
# values are 1 for win, 0 for loss for first team.
# We do this so that if there are duplicates in the results, we don't double-count them.
done = 0
getFile = (file) ->
request filePrefix + file, (err, resp, body) ->
if err
console.log '\nGot err downloading', file, err, '-- retrying...'
return getFile file
else
process.stdout.write "#{resp.statusCode}: downloaded #{file}, #{done + 1} / #{files.length}\r"
try
matches = JSON.parse body
catch err
console.log '\nGot err parsing', file, err, '-- retrying...'
return getFile file
for match in matches
for team in teamNames
session = match[{humans: 'HumansSession', ogres: 'OgresSession'}[team]]
otherSession = match[{humans: 'OgresSession', ogres: 'HumansSession'}[team]]
allSessionIDs[session] = session
allSessionIDs[otherSession] = otherSession
matchesByTeam[team][session] ?= {}
matchesByTeam[team][session][otherSession] = if match.Winner is session then 1 else 0
if ++done is files.length
console.log ""
getNames()
for file in files
getFile file
[sessionsDone, needed] = [0, 0]
getName = (sessionID) ->
++needed
request "http://localhost:3000/db/level.session/#{sessionID}?project=creatorName,creator,submittedCodeLanguage", (err, resp, body) ->
if err
console.log '\nGot err fetching session', sessionID, err, '-- retrying...'
--needed
return getName sessionID
else
process.stdout.write "#{resp.statusCode}: fetched session #{sessionID}, #{sessionsDone + 1} / #{needed}\r"
try
session = JSON.parse(body)
catch err
console.log '\nGot err parsing', session, err, '-- retrying...'
return getName sessionID
usernamesBySessionID[sessionID] = session.creatorName or session.creator
userIDsBySessionID[sessionID] = session.creator
codeLanguagesByUserID[session.creator] = session.submittedCodeLanguage
if ++sessionsDone is needed
console.log ""
finish()
getNames = ->
for sessionID of allSessionIDs
getName sessionID
finish = ->
findLosses = ['55df8c9207d920b7e4262f33', '55e1d23686c019bc47b640fe', '55fa69c0d1754b86056db36e', '55fa68056e01178605aff259', '55f9d3ffd1754b86056d5faa', '55f9d40066d6808505035c4a']
teamRankings = {}
for team in teamNames
teamRankings[team] = {}
for session, matches of matchesByTeam[team]
for otherSession, result of matches
sessionCreatorName = usernamesBySessionID[session]
otherSessionCreatorName = usernamesBySessionID[otherSession]
continue if sessionCreatorName is otherSessionCreatorName
teamRankings[team][sessionCreatorName] ?= {wins: 0, losses: 0, sessionID: session}
if result is 1
++teamRankings[team][sessionCreatorName].wins
else
if session in findLosses
sessionOne = if team is 'humans' then session else otherSession
sessionTwo = if team is 'humans' then otherSession else session
console.log "#{sessionCreatorName} #{team} lost to #{otherSessionCreatorName}: http://codecombat.com/play/spectate/ace-of-coders?session-one=#{sessionOne}&session-two=#{sessionTwo}"
++teamRankings[team][sessionCreatorName].losses
#console.log teamRankings
fs = require 'fs'
topPlayers = []
playersSeenOnlyOnce = {}
for team, players of teamRankings
for playerName, teamScore of players
player = playersSeenOnlyOnce[playerName]
if player
player.wins += teamScore.wins
player.losses += teamScore.losses
delete playersSeenOnlyOnce[playerName]
else
userID = userIDsBySessionID[teamScore.sessionID]
topPlayers.push {name: playerName, userID: userID, sessionID: teamScore.sessionID, wins: teamScore.wins, losses: teamScore.losses, codeLanguage: codeLanguagesByUserID[userID], team: team}
playersSeenOnlyOnce[playerName] = topPlayers[topPlayers.length - 1]
teamCounts = humans: Object.keys(teamRankings.humans).length, ogres: Object.keys(teamRankings.ogres).length
console.log '\nPlayers per team:', teamCounts.humans, 'humans,', teamCounts.ogres, 'ogres'
topPlayers.sort (a, b) ->
aScore = 1000 * a.wins - a.losses
bScore = 1000 * b.wins - b.losses
aScore *= 0.999 + (if a.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if a.name of playersSeenOnlyOnce
bScore *= 0.999 + (if b.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if b.name of playersSeenOnlyOnce
return bScore - aScore
topPlayers = (JSON.stringify(p, null, 0) for p in topPlayers)
#console.log "Players seen only once:", playersSeenOnlyOnce
fs.writeFile 'tournament_results.tsv', topPlayers.join('\n') + '\n', {flags: 'w'}, (err) ->
console.log 'Error writing tournament results:', err if err
console.log '\nWrote tournament results!' unless err
process.exit()
| 166247 | filePrefix = 'https://s3.amazonaws.com/ace-of-coders-simulation-results/'
files = [
'1445213331501451880.json'
'1445213333962624756.json'
'1445213336952262072.json'
'1445213340108350108.json'
'1445213343518140279.json'
'1445213347272483737.json'
'1445213351108262273.json'
'1445213354532639917.json'
'1445213357911513320.json'
'1445213361197631052.json'
'1445213364294940845.json'
'1445213368224989716.json'
'1445213372340479451.json'
'1445213375994169440.json'
'1445213379655103566.json'
'1445213383878314932.json'
'1445213387576330718.json'
'1445213391319951764.json'
'1445213395297284000.json'
'1445213398793484459.json'
'1445213403418993676.json'
'1445213407644707083.json'
'1445213410735647885.json'
'1445213414261150207.json'
'1445213417601033684.json'
'1445213421225330915.json'
'1445213425505538665.json'
'1445213429189103401.json'
'1445213433364370512.json'
'1445213436961513794.json'
'1445213439998252285.json'
'1445213445045520520.json'
'1445213449514608844.json'
'1445213453116282525.json'
'1445213457095637020.json'
'1445213460704753277.json'
'1445213464286547013.json'
'1445213468520080180.json'
'1445213472106072387.json'
'1445213475820365779.json'
'1445213480580483030.json'
'1445213483578157536.json'
'1445213487510887752.json'
'1445213491558872807.json'
'1445213499351461770.json'
'1445213502056807146.json'
'1445213505127336236.json'
'1445213508557502702.json'
'1445213511896396212.json'
'1445213515853887904.json'
'1445213519294758676.json'
'1445213523374005620.json'
'1445213527496735584.json'
'1445213531143063123.json'
'1445213535511651949.json'
'1445213539690176930.json'
'1445213543065367025.json'
'1445213546810986010.json'
'1445213550501273173.json'
'1445213554189924874.json'
'1445213565085119935.json'
'1445213568793830161.json'
'1445213572104047422.json'
'1445213577145506271.json'
'1445213581528093563.json'
'1445213584895451031.json'
'1445213588650931726.json'
'1445213592177781823.json'
'1445213594397225133.json'
'1445221277361358834.json'
'1445221279698497496.json'
'1445221282315153388.json'
'1445221285394137604.json'
'1445221288550371312.json'
'1445221291830712255.json'
'1445221295617755173.json'
'1445221299055851329.json'
'1445221302667030249.json'
'1445221306924823599.json'
'1445221310544601607.json'
'1445221314153960734.json'
'1445221317487106931.json'
'1445221320530978932.json'
'1445221324301371325.json'
'1445221327649700997.json'
'1445221331374603621.json'
'1445221335264382014.json'
'1445221338855628920.json'
'1445221342321774765.json'
'1445221346170926762.json'
'1445221349294564500.json'
'1445221352675532474.json'
'1445221356123574608.json'
'1445221359799314313.json'
'1445221363414713316.json'
'1445221367642102253.json'
'1445221371845170779.json'
'1445221375641841704.json'
'1445221379533766000.json'
'1445221383130035077.json'
'1445221386448295330.json'
'1445221390256020947.json'
'1445221393909487800.json'
'1445221397412673003.json'
'1445221401217854685.json'
'1445221404679522730.json'
'1445221408191448392.json'
'1445221411888158269.json'
'1445221415264332233.json'
'1445221419271950364.json'
'1445221423107421701.json'
'1445221454202101214.json'
'1445221474185597968.json'
'1445230073430754517.json'
'1445230075829988193.json'
'1445230078380093476.json'
'1445230080916882830.json'
'1445230084070294552.json'
'1445230087655859195.json'
'1445230091230254125.json'
'1445230094958575254.json'
'1445230102042734819.json'
'1445230105583567102.json'
'1445230110098843063.json'
'1445230113969801967.json'
'1445230117841812597.json'
'1445230122016639650.json'
'1445230126024689010.json'
'1445230129401404124.json'
'1445230132995295000.json'
'1445230136363195000.json'
'1445230139829326559.json'
'1445230143133819179.json'
'1445230146494641982.json'
'1445230149891696294.json'
'1445230153496417929.json'
'1445230157420298551.json'
'1445230161146744249.json'
'1445230164540033734.json'
'1445230168998013060.json'
'1445230172276532046.json'
'1445230175968137164.json'
'1445230179403344385.json'
'1445230182841026516.json'
'1445230186681159479.json'
'1445230190432845401.json'
'1445230194900203984.json'
'1445230198345037383.json'
'1445230202459027705.json'
'1445230205900628657.json'
'1445230209224723942.json'
'1445230213367015311.json'
'1445230220444856604.json'
'1445230223646143199.json'
'1445230227051947244.json'
'1445230230605632712.json'
'1445230234132435840.json'
'1445230237966858392.json'
'1445230241997606689.json'
'1445230245378549461.json'
'1445230248791558064.json'
'1445230252242695234.json'
'1445230255924413167.json'
'1445230259930682818.json'
'1445230263564875800.json'
'1445230267601339066.json'
'1445230271397215053.json'
'1445230275230599755.json'
'1445230278557392386.json'
'1445230282300585592.json'
'1445230285806493395.json'
'1445230289296758798.json'
'1445230292932839638.json'
'1445230296834477367.json'
'1445230300429749446.json'
'1445230304505276137.json'
'1445230307932189005.json'
'1445230311810878110.json'
'1445230315521992848.json'
'1445230318874365773.json'
'1445230322501494654.json'
'1445230326357408114.json'
'1445230330375479959.json'
'1445230334162974388.json'
'1445230337876792548.json'
'1445230341199978481.json'
'1445230344790949698.json'
'1445230348202193367.json'
'1445230351464998190.json'
'1445230355501490291.json'
'1445230359281495971.json'
'1445230363228852324.json'
'1445230366952366378.json'
'1445230370639190487.json'
'1445230374325745381.json'
'1445230377345716000.json'
'1445230380547954192.json'
'1445230384009635808.json'
'1445230387619920999.json'
'1445230391249215619.json'
'1445230395050707005.json'
'1445230398729998271.json'
'1445230402574142636.json'
'1445230406134099482.json'
'1445230409763088472.json'
'1445230413980744826.json'
'1445230427755574837.json'
'1445230430530442943.json'
'1445230433698560888.json'
'1445230437098330832.json'
'1445230440508211654.json'
'1445230444603413823.json'
'1445230448464331046.json'
'1445230451905017875.json'
'1445230455330580775.json'
'1445230459159341642.json'
'1445230463274827425.json'
'1445230467631616726.json'
'1445230471380124991.json'
'1445230475001827687.json'
'1445230478421377779.json'
'1445230482501165731.json'
'1445230489169162067.json'
'1445230492655384286.json'
'1445230496133865127.json'
'1445230499740257000.json'
'1445230503651978021.json'
'1445230507713678144.json'
'1445230511095700007.json'
'1445230513519495119.json'
'1445268620016907631.json'
'1445268622122827559.json'
'1445268624140776755.json'
'1445268626246517429.json'
'1445268628577795578.json'
'1445268630768718013.json'
'1445268632895287713.json'
'1445268635070637388.json'
'1445268637363693700.json'
'1445268639421901763.json'
'1445268641731929243.json'
'1445268644190182245.json'
'1445268646249862525.json'
'1445268648428272556.json'
'1445268650914877177.json'
'1445268653098586788.json'
'1445268655348101903.json'
'1445268657510578000.json'
'1445268659754499998.json'
'1445268662045588316.json'
'1445268664277727860.json'
'1445268666452725794.json'
'1445268668805764606.json'
'1445268670997451288.json'
'1445268673114680160.json'
'1445268675329202192.json'
'1445268677513490711.json'
'1445268679783287172.json'
'1445268682036031414.json'
'1445268684129371531.json'
'1445268686425970598.json'
'1445268688720167258.json'
'1445268691192558105.json'
'1445268693591401980.json'
'1445268695781357250.json'
'1445268698045096075.json'
'1445268700150717503.json'
'1445268702398420842.json'
'1445268704720775279.json'
'1445268707063564355.json'
'1445268709338713945.json'
'1445268711632755548.json'
'1445268713768604227.json'
'1445268716174246278.json'
'1445268718396569875.json'
'1445268720560126457.json'
'1445268722729210983.json'
'1445268724924585705.json'
'1445268727102603087.json'
'1445268729116745670.json'
'1445268731363535604.json'
'1445268733669265741.json'
'1445268735955645041.json'
'1445268738219628792.json'
'1445268740422156492.json'
'1445268742575678088.json'
'1445268744783311234.json'
'1445268746965546913.json'
'1445268749160417454.json'
'1445268751560320842.json'
'1445268753823934772.json'
'1445268756018962812.json'
'1445268758417436266.json'
'1445268760592037000.json'
'1445268762650074634.json'
'1445268764724292438.json'
'1445268766920232465.json'
'1445268769106959357.json'
'1445268771359267849.json'
'1445268773629836795.json'
'1445268775790855329.json'
'1445268777998775005.json'
'1445268780377269826.json'
'1445268782636835024.json'
'1445268785105088940.json'
'1445268787394903774.json'
'1445268789625324163.json'
'1445268791928562868.json'
'1445268794097570133.json'
'1445268796336624399.json'
'1445268798631516823.json'
'1445268801543146203.json'
'1445268803720916221.json'
'1445268806117659719.json'
'1445268808328143702.json'
'1445268810583045236.json'
'1445268812868210294.json'
'1445268815044910115.json'
'1445268817371573566.json'
'1445268819837082598.json'
'1445268822186030265.json'
'1445268824529238254.json'
'1445268826698333397.json'
'1445268829048336564.json'
'1445268831119849897.json'
'1445268833179695745.json'
'1445268835355203152.json'
'1445268837405461490.json'
'1445268839507117921.json'
'1445268841769599236.json'
'1445268843884382755.json'
'1445268846071503011.json'
'1445268848349572818.json'
'1445268850524364412.json'
'1445268852776213937.json'
'1445268854920734373.json'
'1445268857126237087.json'
'1445268859310201176.json'
'1445268861561857965.json'
'1445268864105148024.json'
'1445268866197882910.json'
'1445268868353326182.json'
'1445268870516655449.json'
'1445268872673508915.json'
'1445268874762479150.json'
'1445268877164751364.json'
'1445268879286935114.json'
'1445268881328685986.json'
'1445268883445195315.json'
'1445268885647373744.json'
'1445268887906137602.json'
'1445268890210873534.json'
'1445268892285821181.json'
'1445268894477987144.json'
'1445268896586339497.json'
'1445268898783556149.json'
'1445268901026137511.json'
'1445268903288629511.json'
'1445268905632999958.json'
'1445268907769137075.json'
'1445268910210199749.json'
'1445268912487917439.json'
'1445268914699519986.json'
'1445268916872093395.json'
'1445268919162358705.json'
'1445268921364723116.json'
'1445268923529045633.json'
'1445268925634767250.json'
'1445268927773354402.json'
'1445268930024845244.json'
'1445268932347541598.json'
'1445268934554593819.json'
'1445268936774699728.json'
'1445268939055730840.json'
'1445268941103213627.json'
'1445268943288510342.json'
'1445268945472849529.json'
'1445268947571262875.json'
'1445268949842113619.json'
'1445268953053002587.json'
'1445268955705618031.json'
'1445268957931907119.json'
'1445268960079462662.json'
'1445268962482269944.json'
'1445268964595501883.json'
'1445268966774301554.json'
'1445268969043544169.json'
'1445268971228990112.json'
'1445268973718788263.json'
'1445268975915972005.json'
'1445268978092369714.json'
'1445268980221048405.json'
'1445268982462277288.json'
'1445268984704104467.json'
'1445268986851463154.json'
'1445268988870702929.json'
'1445268991174718359.json'
'1445268993166842169.json'
'1445268995482530004.json'
'1445268997698069030.json'
'1445268999856627198.json'
'1445269001963981298.json'
'1445269005128881832.json'
'1445269007631174328.json'
'1445269010567701718.json'
'1445269012840178714.json'
'1445269015063741658.json'
'1445269017242828233.json'
'1445269019421232891.json'
'1445269021824220288.json'
'1445269023938605981.json'
'1445269026409208695.json'
'1445269028509058790.json'
'1445269030524896000.json'
'1445269032756824238.json'
'1445269035159289304.json'
'1445269037366243450.json'
'1445269039465047380.json'
'1445269041701586560.json'
'1445269043788403673.json'
'1445269046045728613.json'
'1445269048151202850.json'
'1445269050459992316.json'
'1445269053004557688.json'
'1445269055349225134.json'
'1445269057525643140.json'
'1445269059934835285.json'
'1445269062110045209.json'
'1445269064274679000.json'
'1445269066451272607.json'
'1445269068728772237.json'
'1445269070877790585.json'
'1445269073109715995.json'
'1445269075306781702.json'
'1445269077338016409.json'
'1445269079599082477.json'
'1445269081901931619.json'
'1445269083937350893.json'
'1445269086606168066.json'
'1445269089749719526.json'
'1445269092912378322.json'
'1445269095068300466.json'
'1445269097105610715.json'
'1445269099340915790.json'
'1445269101634711008.json'
'1445269103883171321.json'
'1445269105915454000.json'
'1445269108167686595.json'
'1445269110361203248.json'
'1445269112791210489.json'
'1445269119000963903.json'
'1445269122719487762.json'
'1445269125411006548.json'
'1445269127762964020.json'
'1445269129836155861.json'
'1445269132111575135.json'
'1445269134217570416.json'
'1445269136543021559.json'
'1445269138695139898.json'
'1445269140914567682.json'
'1445269142942098025.json'
'1445269145044930788.json'
'1445269147248686797.json'
'1445269149522984507.json'
'1445269152161285087.json'
'1445269155322986789.json'
'1445269157818898906.json'
'1445269160044484047.json'
'1445269162266085471.json'
'1445269164442888373.json'
'1445269166529441082.json'
'1445269168855231051.json'
'1445269171132400258.json'
'1445269173209510973.json'
'1445269175360974881.json'
'1445269177391806404.json'
'1445269179564059457.json'
'1445269181918334941.json'
'1445269184183064047.json'
'1445269186482660799.json'
'1445269188582405643.json'
'1445269190635432324.json'
'1445269192856263789.json'
'1445269195038404565.json'
'1445269197102021853.json'
'1445269199482726135.json'
'1445269201660257229.json'
'1445269203942103478.json'
'1445269206237893322.json'
'1445269208456870810.json'
'1445269210788885279.json'
'1445269213239724034.json'
'1445269215451086036.json'
'1445269217647945453.json'
'1445269220046288284.json'
'1445269222236265440.json'
'1445269224505994866.json'
'1445269226825172010.json'
'1445269229116949026.json'
'1445269231489543733.json'
'1445269233755357471.json'
'1445269235911648747.json'
'1445269237999553699.json'
'1445269240508365024.json'
'1445269242722009927.json'
'1445269244934195076.json'
'1445269247162195032.json'
'1445269249236953713.json'
'1445269251458578943.json'
'1445269253487689604.json'
'1445269255696323064.json'
'1445269257949099645.json'
'1445269260191632330.json'
'1445269262355329886.json'
'1445269264566769605.json'
'1445269266964329940.json'
'1445269269227593807.json'
'1445269271514201936.json'
'1445269273612398920.json'
'1445269275884684268.json'
'1445269278076892764.json'
'1445269280310865878.json'
'1445269282424623299.json'
'1445269284715336825.json'
'1445269286688556553.json'
'1445269288887242319.json'
'1445269291073998385.json'
'1445269293108399667.json'
'1445269295212448901.json'
'1445269297426394018.json'
'1445269299599447234.json'
'1445269301729933144.json'
'1445269303996496226.json'
'1445269306270930877.json'
'1445269308476918049.json'
'1445269310582680614.json'
'1445269312690229962.json'
'1445269314892409324.json'
'1445269316980608523.json'
'1445269319006449029.json'
'1445269321185755416.json'
'1445269323341804973.json'
'1445269325664755068.json'
'1445269327834759470.json'
'1445269330069526259.json'
'1445269332287771312.json'
'1445269334385516439.json'
'1445269336657750533.json'
'1445269338838256481.json'
'1445269340977045479.json'
'1445269343278893069.json'
'1445269345423148790.json'
'1445269347428235854.json'
'1445269349635316570.json'
'1445269351688263000.json'
'1445269354011647956.json'
'1445269356113719565.json'
'1445269358229515145.json'
'1445269360612105490.json'
'1445269362922818774.json'
'1445269365222636184.json'
'1445269367513280151.json'
'1445269370028699953.json'
'1445269372414990361.json'
'1445269374641788750.json'
'1445269377029996590.json'
'1445269379312073874.json'
'1445269381603113183.json'
'1445269383813588267.json'
'1445269386078574000.json'
'1445269388353640395.json'
'1445269390574915000.json'
'1445269392800924652.json'
'1445269395085481942.json'
'1445269397341246657.json'
'1445269399473830151.json'
'1445269401846739679.json'
'1445269404175824085.json'
'1445269406294316012.json'
'1445269408513123706.json'
'1445269410750656000.json'
'1445269413028587778.json'
'1445269415145683723.json'
'1445269417477899634.json'
'1445269419689952826.json'
'1445269421916883311.json'
'1445269424069113886.json'
'1445269426389494628.json'
'1445269427373333034.json'
'1445269898973248759.json'
'1445269901101787379.json'
'1445269902613155311.json'
]
request = require '../../node_modules/request'
allSessionIDs = {}
usernamesBySessionID = {}
userIDsBySessionID = {}
codeLanguagesByUserID = {}
teamNames = ['humans', 'ogres']
matchesByTeam = {humans: {}, ogres: {}}
# Each object's first keys are first team session IDs, second are alternate teams' session IDs.
# values are 1 for win, 0 for loss for first team.
# We do this so that if there are duplicates in the results, we don't double-count them.
done = 0
getFile = (file) ->
request filePrefix + file, (err, resp, body) ->
if err
console.log '\nGot err downloading', file, err, '-- retrying...'
return getFile file
else
process.stdout.write "#{resp.statusCode}: downloaded #{file}, #{done + 1} / #{files.length}\r"
try
matches = JSON.parse body
catch err
console.log '\nGot err parsing', file, err, '-- retrying...'
return getFile file
for match in matches
for team in teamNames
session = match[{humans: 'HumansSession', ogres: 'OgresSession'}[team]]
otherSession = match[{humans: 'OgresSession', ogres: 'HumansSession'}[team]]
allSessionIDs[session] = session
allSessionIDs[otherSession] = otherSession
matchesByTeam[team][session] ?= {}
matchesByTeam[team][session][otherSession] = if match.Winner is session then 1 else 0
if ++done is files.length
console.log ""
getNames()
for file in files
getFile file
[sessionsDone, needed] = [0, 0]
getName = (sessionID) ->
++needed
request "http://localhost:3000/db/level.session/#{sessionID}?project=creatorName,creator,submittedCodeLanguage", (err, resp, body) ->
if err
console.log '\nGot err fetching session', sessionID, err, '-- retrying...'
--needed
return getName sessionID
else
process.stdout.write "#{resp.statusCode}: fetched session #{sessionID}, #{sessionsDone + 1} / #{needed}\r"
try
session = JSON.parse(body)
catch err
console.log '\nGot err parsing', session, err, '-- retrying...'
return getName sessionID
usernamesBySessionID[sessionID] = session.creatorName or session.creator
userIDsBySessionID[sessionID] = session.creator
codeLanguagesByUserID[session.creator] = session.submittedCodeLanguage
if ++sessionsDone is needed
console.log ""
finish()
getNames = ->
for sessionID of allSessionIDs
getName sessionID
finish = ->
findLosses = ['55df8c9207d920b7e4262f33', '55e1d23686c019bc47b640fe', '55fa69c0d1754b86056db36e', '55fa68056e01178605aff259', '55f9d3ffd1754b86056d5faa', '55f9d40066d6808505035c4a']
teamRankings = {}
for team in teamNames
teamRankings[team] = {}
for session, matches of matchesByTeam[team]
for otherSession, result of matches
sessionCreatorName = usernamesBySessionID[session]
otherSessionCreatorName = usernamesBySessionID[otherSession]
continue if sessionCreatorName is otherSessionCreatorName
teamRankings[team][sessionCreatorName] ?= {wins: 0, losses: 0, sessionID: session}
if result is 1
++teamRankings[team][sessionCreatorName].wins
else
if session in findLosses
sessionOne = if team is 'humans' then session else otherSession
sessionTwo = if team is 'humans' then otherSession else session
console.log "#{sessionCreatorName} #{team} lost to #{otherSessionCreatorName}: http://codecombat.com/play/spectate/ace-of-coders?session-one=#{sessionOne}&session-two=#{sessionTwo}"
++teamRankings[team][sessionCreatorName].losses
#console.log teamRankings
fs = require 'fs'
topPlayers = []
playersSeenOnlyOnce = {}
for team, players of teamRankings
for playerName, teamScore of players
player = playersSeenOnlyOnce[playerName]
if player
player.wins += teamScore.wins
player.losses += teamScore.losses
delete playersSeenOnlyOnce[playerName]
else
userID = userIDsBySessionID[teamScore.sessionID]
topPlayers.push {name: <NAME> <NAME>, userID: userID, sessionID: teamScore.sessionID, wins: teamScore.wins, losses: teamScore.losses, codeLanguage: codeLanguagesByUserID[userID], team: team}
playersSeenOnlyOnce[playerName] = topPlayers[topPlayers.length - 1]
teamCounts = humans: Object.keys(teamRankings.humans).length, ogres: Object.keys(teamRankings.ogres).length
console.log '\nPlayers per team:', teamCounts.humans, 'humans,', teamCounts.ogres, 'ogres'
topPlayers.sort (a, b) ->
aScore = 1000 * a.wins - a.losses
bScore = 1000 * b.wins - b.losses
aScore *= 0.999 + (if a.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if a.name of playersSeenOnlyOnce
bScore *= 0.999 + (if b.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if b.name of playersSeenOnlyOnce
return bScore - aScore
topPlayers = (JSON.stringify(p, null, 0) for p in topPlayers)
#console.log "Players seen only once:", playersSeenOnlyOnce
fs.writeFile 'tournament_results.tsv', topPlayers.join('\n') + '\n', {flags: 'w'}, (err) ->
console.log 'Error writing tournament results:', err if err
console.log '\nWrote tournament results!' unless err
process.exit()
| true | filePrefix = 'https://s3.amazonaws.com/ace-of-coders-simulation-results/'
files = [
'1445213331501451880.json'
'1445213333962624756.json'
'1445213336952262072.json'
'1445213340108350108.json'
'1445213343518140279.json'
'1445213347272483737.json'
'1445213351108262273.json'
'1445213354532639917.json'
'1445213357911513320.json'
'1445213361197631052.json'
'1445213364294940845.json'
'1445213368224989716.json'
'1445213372340479451.json'
'1445213375994169440.json'
'1445213379655103566.json'
'1445213383878314932.json'
'1445213387576330718.json'
'1445213391319951764.json'
'1445213395297284000.json'
'1445213398793484459.json'
'1445213403418993676.json'
'1445213407644707083.json'
'1445213410735647885.json'
'1445213414261150207.json'
'1445213417601033684.json'
'1445213421225330915.json'
'1445213425505538665.json'
'1445213429189103401.json'
'1445213433364370512.json'
'1445213436961513794.json'
'1445213439998252285.json'
'1445213445045520520.json'
'1445213449514608844.json'
'1445213453116282525.json'
'1445213457095637020.json'
'1445213460704753277.json'
'1445213464286547013.json'
'1445213468520080180.json'
'1445213472106072387.json'
'1445213475820365779.json'
'1445213480580483030.json'
'1445213483578157536.json'
'1445213487510887752.json'
'1445213491558872807.json'
'1445213499351461770.json'
'1445213502056807146.json'
'1445213505127336236.json'
'1445213508557502702.json'
'1445213511896396212.json'
'1445213515853887904.json'
'1445213519294758676.json'
'1445213523374005620.json'
'1445213527496735584.json'
'1445213531143063123.json'
'1445213535511651949.json'
'1445213539690176930.json'
'1445213543065367025.json'
'1445213546810986010.json'
'1445213550501273173.json'
'1445213554189924874.json'
'1445213565085119935.json'
'1445213568793830161.json'
'1445213572104047422.json'
'1445213577145506271.json'
'1445213581528093563.json'
'1445213584895451031.json'
'1445213588650931726.json'
'1445213592177781823.json'
'1445213594397225133.json'
'1445221277361358834.json'
'1445221279698497496.json'
'1445221282315153388.json'
'1445221285394137604.json'
'1445221288550371312.json'
'1445221291830712255.json'
'1445221295617755173.json'
'1445221299055851329.json'
'1445221302667030249.json'
'1445221306924823599.json'
'1445221310544601607.json'
'1445221314153960734.json'
'1445221317487106931.json'
'1445221320530978932.json'
'1445221324301371325.json'
'1445221327649700997.json'
'1445221331374603621.json'
'1445221335264382014.json'
'1445221338855628920.json'
'1445221342321774765.json'
'1445221346170926762.json'
'1445221349294564500.json'
'1445221352675532474.json'
'1445221356123574608.json'
'1445221359799314313.json'
'1445221363414713316.json'
'1445221367642102253.json'
'1445221371845170779.json'
'1445221375641841704.json'
'1445221379533766000.json'
'1445221383130035077.json'
'1445221386448295330.json'
'1445221390256020947.json'
'1445221393909487800.json'
'1445221397412673003.json'
'1445221401217854685.json'
'1445221404679522730.json'
'1445221408191448392.json'
'1445221411888158269.json'
'1445221415264332233.json'
'1445221419271950364.json'
'1445221423107421701.json'
'1445221454202101214.json'
'1445221474185597968.json'
'1445230073430754517.json'
'1445230075829988193.json'
'1445230078380093476.json'
'1445230080916882830.json'
'1445230084070294552.json'
'1445230087655859195.json'
'1445230091230254125.json'
'1445230094958575254.json'
'1445230102042734819.json'
'1445230105583567102.json'
'1445230110098843063.json'
'1445230113969801967.json'
'1445230117841812597.json'
'1445230122016639650.json'
'1445230126024689010.json'
'1445230129401404124.json'
'1445230132995295000.json'
'1445230136363195000.json'
'1445230139829326559.json'
'1445230143133819179.json'
'1445230146494641982.json'
'1445230149891696294.json'
'1445230153496417929.json'
'1445230157420298551.json'
'1445230161146744249.json'
'1445230164540033734.json'
'1445230168998013060.json'
'1445230172276532046.json'
'1445230175968137164.json'
'1445230179403344385.json'
'1445230182841026516.json'
'1445230186681159479.json'
'1445230190432845401.json'
'1445230194900203984.json'
'1445230198345037383.json'
'1445230202459027705.json'
'1445230205900628657.json'
'1445230209224723942.json'
'1445230213367015311.json'
'1445230220444856604.json'
'1445230223646143199.json'
'1445230227051947244.json'
'1445230230605632712.json'
'1445230234132435840.json'
'1445230237966858392.json'
'1445230241997606689.json'
'1445230245378549461.json'
'1445230248791558064.json'
'1445230252242695234.json'
'1445230255924413167.json'
'1445230259930682818.json'
'1445230263564875800.json'
'1445230267601339066.json'
'1445230271397215053.json'
'1445230275230599755.json'
'1445230278557392386.json'
'1445230282300585592.json'
'1445230285806493395.json'
'1445230289296758798.json'
'1445230292932839638.json'
'1445230296834477367.json'
'1445230300429749446.json'
'1445230304505276137.json'
'1445230307932189005.json'
'1445230311810878110.json'
'1445230315521992848.json'
'1445230318874365773.json'
'1445230322501494654.json'
'1445230326357408114.json'
'1445230330375479959.json'
'1445230334162974388.json'
'1445230337876792548.json'
'1445230341199978481.json'
'1445230344790949698.json'
'1445230348202193367.json'
'1445230351464998190.json'
'1445230355501490291.json'
'1445230359281495971.json'
'1445230363228852324.json'
'1445230366952366378.json'
'1445230370639190487.json'
'1445230374325745381.json'
'1445230377345716000.json'
'1445230380547954192.json'
'1445230384009635808.json'
'1445230387619920999.json'
'1445230391249215619.json'
'1445230395050707005.json'
'1445230398729998271.json'
'1445230402574142636.json'
'1445230406134099482.json'
'1445230409763088472.json'
'1445230413980744826.json'
'1445230427755574837.json'
'1445230430530442943.json'
'1445230433698560888.json'
'1445230437098330832.json'
'1445230440508211654.json'
'1445230444603413823.json'
'1445230448464331046.json'
'1445230451905017875.json'
'1445230455330580775.json'
'1445230459159341642.json'
'1445230463274827425.json'
'1445230467631616726.json'
'1445230471380124991.json'
'1445230475001827687.json'
'1445230478421377779.json'
'1445230482501165731.json'
'1445230489169162067.json'
'1445230492655384286.json'
'1445230496133865127.json'
'1445230499740257000.json'
'1445230503651978021.json'
'1445230507713678144.json'
'1445230511095700007.json'
'1445230513519495119.json'
'1445268620016907631.json'
'1445268622122827559.json'
'1445268624140776755.json'
'1445268626246517429.json'
'1445268628577795578.json'
'1445268630768718013.json'
'1445268632895287713.json'
'1445268635070637388.json'
'1445268637363693700.json'
'1445268639421901763.json'
'1445268641731929243.json'
'1445268644190182245.json'
'1445268646249862525.json'
'1445268648428272556.json'
'1445268650914877177.json'
'1445268653098586788.json'
'1445268655348101903.json'
'1445268657510578000.json'
'1445268659754499998.json'
'1445268662045588316.json'
'1445268664277727860.json'
'1445268666452725794.json'
'1445268668805764606.json'
'1445268670997451288.json'
'1445268673114680160.json'
'1445268675329202192.json'
'1445268677513490711.json'
'1445268679783287172.json'
'1445268682036031414.json'
'1445268684129371531.json'
'1445268686425970598.json'
'1445268688720167258.json'
'1445268691192558105.json'
'1445268693591401980.json'
'1445268695781357250.json'
'1445268698045096075.json'
'1445268700150717503.json'
'1445268702398420842.json'
'1445268704720775279.json'
'1445268707063564355.json'
'1445268709338713945.json'
'1445268711632755548.json'
'1445268713768604227.json'
'1445268716174246278.json'
'1445268718396569875.json'
'1445268720560126457.json'
'1445268722729210983.json'
'1445268724924585705.json'
'1445268727102603087.json'
'1445268729116745670.json'
'1445268731363535604.json'
'1445268733669265741.json'
'1445268735955645041.json'
'1445268738219628792.json'
'1445268740422156492.json'
'1445268742575678088.json'
'1445268744783311234.json'
'1445268746965546913.json'
'1445268749160417454.json'
'1445268751560320842.json'
'1445268753823934772.json'
'1445268756018962812.json'
'1445268758417436266.json'
'1445268760592037000.json'
'1445268762650074634.json'
'1445268764724292438.json'
'1445268766920232465.json'
'1445268769106959357.json'
'1445268771359267849.json'
'1445268773629836795.json'
'1445268775790855329.json'
'1445268777998775005.json'
'1445268780377269826.json'
'1445268782636835024.json'
'1445268785105088940.json'
'1445268787394903774.json'
'1445268789625324163.json'
'1445268791928562868.json'
'1445268794097570133.json'
'1445268796336624399.json'
'1445268798631516823.json'
'1445268801543146203.json'
'1445268803720916221.json'
'1445268806117659719.json'
'1445268808328143702.json'
'1445268810583045236.json'
'1445268812868210294.json'
'1445268815044910115.json'
'1445268817371573566.json'
'1445268819837082598.json'
'1445268822186030265.json'
'1445268824529238254.json'
'1445268826698333397.json'
'1445268829048336564.json'
'1445268831119849897.json'
'1445268833179695745.json'
'1445268835355203152.json'
'1445268837405461490.json'
'1445268839507117921.json'
'1445268841769599236.json'
'1445268843884382755.json'
'1445268846071503011.json'
'1445268848349572818.json'
'1445268850524364412.json'
'1445268852776213937.json'
'1445268854920734373.json'
'1445268857126237087.json'
'1445268859310201176.json'
'1445268861561857965.json'
'1445268864105148024.json'
'1445268866197882910.json'
'1445268868353326182.json'
'1445268870516655449.json'
'1445268872673508915.json'
'1445268874762479150.json'
'1445268877164751364.json'
'1445268879286935114.json'
'1445268881328685986.json'
'1445268883445195315.json'
'1445268885647373744.json'
'1445268887906137602.json'
'1445268890210873534.json'
'1445268892285821181.json'
'1445268894477987144.json'
'1445268896586339497.json'
'1445268898783556149.json'
'1445268901026137511.json'
'1445268903288629511.json'
'1445268905632999958.json'
'1445268907769137075.json'
'1445268910210199749.json'
'1445268912487917439.json'
'1445268914699519986.json'
'1445268916872093395.json'
'1445268919162358705.json'
'1445268921364723116.json'
'1445268923529045633.json'
'1445268925634767250.json'
'1445268927773354402.json'
'1445268930024845244.json'
'1445268932347541598.json'
'1445268934554593819.json'
'1445268936774699728.json'
'1445268939055730840.json'
'1445268941103213627.json'
'1445268943288510342.json'
'1445268945472849529.json'
'1445268947571262875.json'
'1445268949842113619.json'
'1445268953053002587.json'
'1445268955705618031.json'
'1445268957931907119.json'
'1445268960079462662.json'
'1445268962482269944.json'
'1445268964595501883.json'
'1445268966774301554.json'
'1445268969043544169.json'
'1445268971228990112.json'
'1445268973718788263.json'
'1445268975915972005.json'
'1445268978092369714.json'
'1445268980221048405.json'
'1445268982462277288.json'
'1445268984704104467.json'
'1445268986851463154.json'
'1445268988870702929.json'
'1445268991174718359.json'
'1445268993166842169.json'
'1445268995482530004.json'
'1445268997698069030.json'
'1445268999856627198.json'
'1445269001963981298.json'
'1445269005128881832.json'
'1445269007631174328.json'
'1445269010567701718.json'
'1445269012840178714.json'
'1445269015063741658.json'
'1445269017242828233.json'
'1445269019421232891.json'
'1445269021824220288.json'
'1445269023938605981.json'
'1445269026409208695.json'
'1445269028509058790.json'
'1445269030524896000.json'
'1445269032756824238.json'
'1445269035159289304.json'
'1445269037366243450.json'
'1445269039465047380.json'
'1445269041701586560.json'
'1445269043788403673.json'
'1445269046045728613.json'
'1445269048151202850.json'
'1445269050459992316.json'
'1445269053004557688.json'
'1445269055349225134.json'
'1445269057525643140.json'
'1445269059934835285.json'
'1445269062110045209.json'
'1445269064274679000.json'
'1445269066451272607.json'
'1445269068728772237.json'
'1445269070877790585.json'
'1445269073109715995.json'
'1445269075306781702.json'
'1445269077338016409.json'
'1445269079599082477.json'
'1445269081901931619.json'
'1445269083937350893.json'
'1445269086606168066.json'
'1445269089749719526.json'
'1445269092912378322.json'
'1445269095068300466.json'
'1445269097105610715.json'
'1445269099340915790.json'
'1445269101634711008.json'
'1445269103883171321.json'
'1445269105915454000.json'
'1445269108167686595.json'
'1445269110361203248.json'
'1445269112791210489.json'
'1445269119000963903.json'
'1445269122719487762.json'
'1445269125411006548.json'
'1445269127762964020.json'
'1445269129836155861.json'
'1445269132111575135.json'
'1445269134217570416.json'
'1445269136543021559.json'
'1445269138695139898.json'
'1445269140914567682.json'
'1445269142942098025.json'
'1445269145044930788.json'
'1445269147248686797.json'
'1445269149522984507.json'
'1445269152161285087.json'
'1445269155322986789.json'
'1445269157818898906.json'
'1445269160044484047.json'
'1445269162266085471.json'
'1445269164442888373.json'
'1445269166529441082.json'
'1445269168855231051.json'
'1445269171132400258.json'
'1445269173209510973.json'
'1445269175360974881.json'
'1445269177391806404.json'
'1445269179564059457.json'
'1445269181918334941.json'
'1445269184183064047.json'
'1445269186482660799.json'
'1445269188582405643.json'
'1445269190635432324.json'
'1445269192856263789.json'
'1445269195038404565.json'
'1445269197102021853.json'
'1445269199482726135.json'
'1445269201660257229.json'
'1445269203942103478.json'
'1445269206237893322.json'
'1445269208456870810.json'
'1445269210788885279.json'
'1445269213239724034.json'
'1445269215451086036.json'
'1445269217647945453.json'
'1445269220046288284.json'
'1445269222236265440.json'
'1445269224505994866.json'
'1445269226825172010.json'
'1445269229116949026.json'
'1445269231489543733.json'
'1445269233755357471.json'
'1445269235911648747.json'
'1445269237999553699.json'
'1445269240508365024.json'
'1445269242722009927.json'
'1445269244934195076.json'
'1445269247162195032.json'
'1445269249236953713.json'
'1445269251458578943.json'
'1445269253487689604.json'
'1445269255696323064.json'
'1445269257949099645.json'
'1445269260191632330.json'
'1445269262355329886.json'
'1445269264566769605.json'
'1445269266964329940.json'
'1445269269227593807.json'
'1445269271514201936.json'
'1445269273612398920.json'
'1445269275884684268.json'
'1445269278076892764.json'
'1445269280310865878.json'
'1445269282424623299.json'
'1445269284715336825.json'
'1445269286688556553.json'
'1445269288887242319.json'
'1445269291073998385.json'
'1445269293108399667.json'
'1445269295212448901.json'
'1445269297426394018.json'
'1445269299599447234.json'
'1445269301729933144.json'
'1445269303996496226.json'
'1445269306270930877.json'
'1445269308476918049.json'
'1445269310582680614.json'
'1445269312690229962.json'
'1445269314892409324.json'
'1445269316980608523.json'
'1445269319006449029.json'
'1445269321185755416.json'
'1445269323341804973.json'
'1445269325664755068.json'
'1445269327834759470.json'
'1445269330069526259.json'
'1445269332287771312.json'
'1445269334385516439.json'
'1445269336657750533.json'
'1445269338838256481.json'
'1445269340977045479.json'
'1445269343278893069.json'
'1445269345423148790.json'
'1445269347428235854.json'
'1445269349635316570.json'
'1445269351688263000.json'
'1445269354011647956.json'
'1445269356113719565.json'
'1445269358229515145.json'
'1445269360612105490.json'
'1445269362922818774.json'
'1445269365222636184.json'
'1445269367513280151.json'
'1445269370028699953.json'
'1445269372414990361.json'
'1445269374641788750.json'
'1445269377029996590.json'
'1445269379312073874.json'
'1445269381603113183.json'
'1445269383813588267.json'
'1445269386078574000.json'
'1445269388353640395.json'
'1445269390574915000.json'
'1445269392800924652.json'
'1445269395085481942.json'
'1445269397341246657.json'
'1445269399473830151.json'
'1445269401846739679.json'
'1445269404175824085.json'
'1445269406294316012.json'
'1445269408513123706.json'
'1445269410750656000.json'
'1445269413028587778.json'
'1445269415145683723.json'
'1445269417477899634.json'
'1445269419689952826.json'
'1445269421916883311.json'
'1445269424069113886.json'
'1445269426389494628.json'
'1445269427373333034.json'
'1445269898973248759.json'
'1445269901101787379.json'
'1445269902613155311.json'
]
request = require '../../node_modules/request'
allSessionIDs = {}
usernamesBySessionID = {}
userIDsBySessionID = {}
codeLanguagesByUserID = {}
teamNames = ['humans', 'ogres']
matchesByTeam = {humans: {}, ogres: {}}
# Each object's first keys are first team session IDs, second are alternate teams' session IDs.
# values are 1 for win, 0 for loss for first team.
# We do this so that if there are duplicates in the results, we don't double-count them.
done = 0
getFile = (file) ->
request filePrefix + file, (err, resp, body) ->
if err
console.log '\nGot err downloading', file, err, '-- retrying...'
return getFile file
else
process.stdout.write "#{resp.statusCode}: downloaded #{file}, #{done + 1} / #{files.length}\r"
try
matches = JSON.parse body
catch err
console.log '\nGot err parsing', file, err, '-- retrying...'
return getFile file
for match in matches
for team in teamNames
session = match[{humans: 'HumansSession', ogres: 'OgresSession'}[team]]
otherSession = match[{humans: 'OgresSession', ogres: 'HumansSession'}[team]]
allSessionIDs[session] = session
allSessionIDs[otherSession] = otherSession
matchesByTeam[team][session] ?= {}
matchesByTeam[team][session][otherSession] = if match.Winner is session then 1 else 0
if ++done is files.length
console.log ""
getNames()
for file in files
getFile file
[sessionsDone, needed] = [0, 0]
getName = (sessionID) ->
++needed
request "http://localhost:3000/db/level.session/#{sessionID}?project=creatorName,creator,submittedCodeLanguage", (err, resp, body) ->
if err
console.log '\nGot err fetching session', sessionID, err, '-- retrying...'
--needed
return getName sessionID
else
process.stdout.write "#{resp.statusCode}: fetched session #{sessionID}, #{sessionsDone + 1} / #{needed}\r"
try
session = JSON.parse(body)
catch err
console.log '\nGot err parsing', session, err, '-- retrying...'
return getName sessionID
usernamesBySessionID[sessionID] = session.creatorName or session.creator
userIDsBySessionID[sessionID] = session.creator
codeLanguagesByUserID[session.creator] = session.submittedCodeLanguage
if ++sessionsDone is needed
console.log ""
finish()
getNames = ->
for sessionID of allSessionIDs
getName sessionID
finish = ->
findLosses = ['55df8c9207d920b7e4262f33', '55e1d23686c019bc47b640fe', '55fa69c0d1754b86056db36e', '55fa68056e01178605aff259', '55f9d3ffd1754b86056d5faa', '55f9d40066d6808505035c4a']
teamRankings = {}
for team in teamNames
teamRankings[team] = {}
for session, matches of matchesByTeam[team]
for otherSession, result of matches
sessionCreatorName = usernamesBySessionID[session]
otherSessionCreatorName = usernamesBySessionID[otherSession]
continue if sessionCreatorName is otherSessionCreatorName
teamRankings[team][sessionCreatorName] ?= {wins: 0, losses: 0, sessionID: session}
if result is 1
++teamRankings[team][sessionCreatorName].wins
else
if session in findLosses
sessionOne = if team is 'humans' then session else otherSession
sessionTwo = if team is 'humans' then otherSession else session
console.log "#{sessionCreatorName} #{team} lost to #{otherSessionCreatorName}: http://codecombat.com/play/spectate/ace-of-coders?session-one=#{sessionOne}&session-two=#{sessionTwo}"
++teamRankings[team][sessionCreatorName].losses
#console.log teamRankings
fs = require 'fs'
topPlayers = []
playersSeenOnlyOnce = {}
for team, players of teamRankings
for playerName, teamScore of players
player = playersSeenOnlyOnce[playerName]
if player
player.wins += teamScore.wins
player.losses += teamScore.losses
delete playersSeenOnlyOnce[playerName]
else
userID = userIDsBySessionID[teamScore.sessionID]
topPlayers.push {name: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI, userID: userID, sessionID: teamScore.sessionID, wins: teamScore.wins, losses: teamScore.losses, codeLanguage: codeLanguagesByUserID[userID], team: team}
playersSeenOnlyOnce[playerName] = topPlayers[topPlayers.length - 1]
teamCounts = humans: Object.keys(teamRankings.humans).length, ogres: Object.keys(teamRankings.ogres).length
console.log '\nPlayers per team:', teamCounts.humans, 'humans,', teamCounts.ogres, 'ogres'
topPlayers.sort (a, b) ->
aScore = 1000 * a.wins - a.losses
bScore = 1000 * b.wins - b.losses
aScore *= 0.999 + (if a.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if a.name of playersSeenOnlyOnce
bScore *= 0.999 + (if b.team is 'ogres' then (teamCounts.ogres / teamCounts.humans) else (teamCounts.humans / teamCounts.ogres)) if b.name of playersSeenOnlyOnce
return bScore - aScore
topPlayers = (JSON.stringify(p, null, 0) for p in topPlayers)
#console.log "Players seen only once:", playersSeenOnlyOnce
fs.writeFile 'tournament_results.tsv', topPlayers.join('\n') + '\n', {flags: 'w'}, (err) ->
console.log 'Error writing tournament results:', err if err
console.log '\nWrote tournament results!' unless err
process.exit()
|
[
{
"context": "ings\n #get data from form\n @user = 'agent@demo'\n @pass = 'demo'\n # -----------",
"end": 734,
"score": 0.5140128135681152,
"start": 729,
"tag": "USERNAME",
"value": "agent"
},
{
"context": " #get data from form\n @user = 'agen... | app/views/autologin-view.coffee | zzart/mp_old | 0 | View = require 'views/base/view'
template = require 'views/templates/login'
mediator = require 'mediator'
module.exports = class LoginView extends View
autoRender: true
template: template
id: 'login'
attributes: {'data-role':'popup', 'data-overlay-theme':'b', 'data-theme':'b', 'data-dismissible':'false' , 'style':'max-width:400px;'}
initialize: (options) =>
super
@model = mediator.models.user
@template = template
# events
@delegate 'click','#login-verification', @login
@on 'addedToDOM', @login
login: =>
@publishEvent('log:error', 'autologin------')
#check credentials and set up settings
#get data from form
@user = 'agent@demo'
@pass = 'demo'
# -------------------------
# generate app mac
apphash = CryptoJS.HmacSHA256(@model.url, mediator.app_key)
apphash_hexed = apphash.toString(CryptoJS.enc.Hex)
userhash = CryptoJS.HmacSHA256(@model.url, @pass)
userhash_hexed = userhash.toString(CryptoJS.enc.Hex)
header_string = "#{mediator.app}|#{apphash_hexed}|#{@user}|#{userhash_hexed}"
auth_header = btoa(header_string)
# -------------------------
@model.fetch
headers: {'X-Auth-Token' : auth_header}
success: =>
@publishEvent('log:info', 'login SUCCESS')
@model.set({'user_pass':@pass}) # set this manually so we don't send password back and forth
@model.set({'company_name':@user.split('@')[1]}) #
@model.update_db()
$.cookie('user', @user, {expires: 7})
$.cookie('pass', @pass, {expires: 7})
@model.check_free_account()
$('#first-name-placeholder').text(@model.get('first_name') or @model.get('username'))
$('#bon-config-link').attr('href', "/biura/#{@model.get('company_id')}")
$('#agent-config-link').attr('href', "/agenci/#{@model.get('id')}")
# $('#login').popup('close')
@publishEvent 'login:success' #loads additional scripts
@publishEvent 'tell_user', "Logowanie zakończone."
Chaplin.utils.redirectTo {url: ''}
error:(model, response, options) =>
if response.responseJSON?
$('.login-error').text(response.responseJSON['title'])
else
$('.login-error').text('Brak kontaktu z serwerem')
@publishEvent('log:info', 'login FAILED')
attach: =>
super
@publishEvent('log:info', 'view: login afterRender()')
| 164305 | View = require 'views/base/view'
template = require 'views/templates/login'
mediator = require 'mediator'
module.exports = class LoginView extends View
autoRender: true
template: template
id: 'login'
attributes: {'data-role':'popup', 'data-overlay-theme':'b', 'data-theme':'b', 'data-dismissible':'false' , 'style':'max-width:400px;'}
initialize: (options) =>
super
@model = mediator.models.user
@template = template
# events
@delegate 'click','#login-verification', @login
@on 'addedToDOM', @login
login: =>
@publishEvent('log:error', 'autologin------')
#check credentials and set up settings
#get data from form
@user = 'agent@<EMAIL>'
@pass = '<EMAIL>'
# -------------------------
# generate app mac
apphash = CryptoJS.HmacSHA256(@model.url, mediator.app_key)
apphash_hexed = apphash.toString(CryptoJS.enc.Hex)
userhash = CryptoJS.HmacSHA256(@model.url, @pass)
userhash_hexed = userhash.toString(CryptoJS.enc.Hex)
header_string = "#{mediator.app}|#{apphash_hexed}|#{@user}|#{userhash_hexed}"
auth_header = btoa(header_string)
# -------------------------
@model.fetch
headers: {'X-Auth-Token' : auth_header}
success: =>
@publishEvent('log:info', 'login SUCCESS')
@model.set({'user_pass':<PASSWORD>}) # set this manually so we don't send password back and forth
@model.set({'company_name':@user.split('@')[1]}) #
@model.update_db()
$.cookie('user', @user, {expires: 7})
$.cookie('pass', <PASSWORD>, {expires: 7})
@model.check_free_account()
$('#first-name-placeholder').text(@model.get('first_name') or @model.get('username'))
$('#bon-config-link').attr('href', "/biura/#{@model.get('company_id')}")
$('#agent-config-link').attr('href', "/agenci/#{@model.get('id')}")
# $('#login').popup('close')
@publishEvent 'login:success' #loads additional scripts
@publishEvent 'tell_user', "Logowanie zakończone."
Chaplin.utils.redirectTo {url: ''}
error:(model, response, options) =>
if response.responseJSON?
$('.login-error').text(response.responseJSON['title'])
else
$('.login-error').text('Brak kontaktu z serwerem')
@publishEvent('log:info', 'login FAILED')
attach: =>
super
@publishEvent('log:info', 'view: login afterRender()')
| true | View = require 'views/base/view'
template = require 'views/templates/login'
mediator = require 'mediator'
module.exports = class LoginView extends View
autoRender: true
template: template
id: 'login'
attributes: {'data-role':'popup', 'data-overlay-theme':'b', 'data-theme':'b', 'data-dismissible':'false' , 'style':'max-width:400px;'}
initialize: (options) =>
super
@model = mediator.models.user
@template = template
# events
@delegate 'click','#login-verification', @login
@on 'addedToDOM', @login
login: =>
@publishEvent('log:error', 'autologin------')
#check credentials and set up settings
#get data from form
@user = 'agent@PI:EMAIL:<EMAIL>END_PI'
@pass = 'PI:PASSWORD:<EMAIL>END_PI'
# -------------------------
# generate app mac
apphash = CryptoJS.HmacSHA256(@model.url, mediator.app_key)
apphash_hexed = apphash.toString(CryptoJS.enc.Hex)
userhash = CryptoJS.HmacSHA256(@model.url, @pass)
userhash_hexed = userhash.toString(CryptoJS.enc.Hex)
header_string = "#{mediator.app}|#{apphash_hexed}|#{@user}|#{userhash_hexed}"
auth_header = btoa(header_string)
# -------------------------
@model.fetch
headers: {'X-Auth-Token' : auth_header}
success: =>
@publishEvent('log:info', 'login SUCCESS')
@model.set({'user_pass':PI:PASSWORD:<PASSWORD>END_PI}) # set this manually so we don't send password back and forth
@model.set({'company_name':@user.split('@')[1]}) #
@model.update_db()
$.cookie('user', @user, {expires: 7})
$.cookie('pass', PI:PASSWORD:<PASSWORD>END_PI, {expires: 7})
@model.check_free_account()
$('#first-name-placeholder').text(@model.get('first_name') or @model.get('username'))
$('#bon-config-link').attr('href', "/biura/#{@model.get('company_id')}")
$('#agent-config-link').attr('href', "/agenci/#{@model.get('id')}")
# $('#login').popup('close')
@publishEvent 'login:success' #loads additional scripts
@publishEvent 'tell_user', "Logowanie zakończone."
Chaplin.utils.redirectTo {url: ''}
error:(model, response, options) =>
if response.responseJSON?
$('.login-error').text(response.responseJSON['title'])
else
$('.login-error').text('Brak kontaktu z serwerem')
@publishEvent('log:info', 'login FAILED')
attach: =>
super
@publishEvent('log:info', 'view: login afterRender()')
|
[
{
"context": "ileoverview Tests for sort-imports rule.\n# @author Christian Schuller\n###\n\n'use strict'\n\n#-----------------------------",
"end": 78,
"score": 0.9995781183242798,
"start": 60,
"tag": "NAME",
"value": "Christian Schuller"
},
{
"context": "rom 'foo.js'\n '''\n ,\... | src/tests/rules/sort-imports.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for sort-imports rule.
# @author Christian Schuller
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/sort-imports'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'Imports should be sorted alphabetically.'
type: 'ImportDeclaration'
ignoreCaseArgs = [ignoreCase: yes]
ruleTester.run 'sort-imports', rule,
valid: [
'''
import a from 'foo.js'
import b from 'bar.js'
import c from 'baz.js'
'''
'''
import * as B from 'foo.js'
import A from 'bar.js'
'''
'''
import * as B from 'foo.js'
import {a, b} from 'bar.js'
'''
'''
import {b, c} from 'bar.js'
import A from 'foo.js'
'''
,
code: '''
import A from 'bar.js'
import {b, c} from 'foo.js'
'''
options: [memberSyntaxSortOrder: ['single', 'multiple', 'none', 'all']]
,
'''
import {a, b} from 'bar.js'
import {c, d} from 'foo.js'
'''
'''
import A from 'foo.js'
import B from 'bar.js'
'''
'''
import A from 'foo.js'
import a from 'bar.js'
'''
'''
import a, * as b from 'foo.js'
import c from 'bar.js'
'''
'''
import 'foo.js'
import a from 'bar.js'
'''
'''
import B from 'foo.js'
import a from 'bar.js'
'''
,
code: '''
import a from 'foo.js'
import B from 'bar.js'
'''
options: ignoreCaseArgs
,
"import {a, b, c, d} from 'foo.js'"
,
code: "import {b, A, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {B, a, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {a, B, c, D} from 'foo.js'"
options: ignoreCaseArgs
,
"import a, * as b from 'foo.js'"
'''
import * as a from 'foo.js'
import b from 'bar.js'
'''
'''
import * as bar from 'bar.js'
import * as foo from 'foo.js'
'''
,
# https://github.com/eslint/eslint/issues/5130
code: '''
import 'foo'
import bar from 'bar'
'''
options: ignoreCaseArgs
,
# https://github.com/eslint/eslint/issues/5305
"import React, {Component} from 'react'"
]
invalid: [
code: '''
import a from 'foo.js'
import A from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import b from 'foo.js'
import a from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import {b, c} from 'foo.js'
import {a, d} from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import * as foo from 'foo.js'
import * as bar from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import a from 'foo.js'
import {b, c} from 'bar.js'
'''
output: null
errors: [
message: "Expected 'multiple' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import * as b from 'bar.js'
'''
output: null
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import 'bar.js'
'''
output: null
errors: [
message: "Expected 'none' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import b from 'bar.js'
import * as a from 'foo.js'
'''
output: null
options: [memberSyntaxSortOrder: ['all', 'single', 'multiple', 'none']]
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: "import {b, a, d, c} from 'foo.js'"
output: "import {a, b, c, d} from 'foo.js'"
errors: [
message:
"Member 'a' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {a, B, c, D} from 'foo.js'"
output: "import {B, D, a, c} from 'foo.js'"
errors: [
message:
"Member 'B' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, ### comment ### aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz ### comment ###, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {### comment ### zzzzz, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, aaaaa ### comment ###} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: '''
import {
boop,
foo,
zoo,
baz as qux,
bar,
beep
} from 'foo.js'
'''
output: '''
import {
bar,
beep,
boop,
foo,
baz as qux,
zoo
} from 'foo.js'
'''
errors: [
message:
"Member 'qux' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
]
| 2937 | ###*
# @fileoverview Tests for sort-imports rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/sort-imports'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'Imports should be sorted alphabetically.'
type: 'ImportDeclaration'
ignoreCaseArgs = [ignoreCase: yes]
ruleTester.run 'sort-imports', rule,
valid: [
'''
import a from 'foo.js'
import b from 'bar.js'
import c from 'baz.js'
'''
'''
import * as B from 'foo.js'
import A from 'bar.js'
'''
'''
import * as B from 'foo.js'
import {a, b} from 'bar.js'
'''
'''
import {b, c} from 'bar.js'
import A from 'foo.js'
'''
,
code: '''
import A from 'bar.js'
import {b, c} from 'foo.js'
'''
options: [memberSyntaxSortOrder: ['single', 'multiple', 'none', 'all']]
,
'''
import {a, b} from 'bar.js'
import {c, d} from 'foo.js'
'''
'''
import A from 'foo.js'
import B from 'bar.js'
'''
'''
import A from 'foo.js'
import a from 'bar.js'
'''
'''
import a, * as b from 'foo.js'
import c from 'bar.js'
'''
'''
import 'foo.js'
import a from 'bar.js'
'''
'''
import B from 'foo.js'
import a from 'bar.js'
'''
,
code: '''
import a from 'foo.js'
import B from 'bar.js'
'''
options: ignoreCaseArgs
,
"import {a, b, c, d} from 'foo.js'"
,
code: "import {b, A, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {B, a, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {a, B, c, D} from 'foo.js'"
options: ignoreCaseArgs
,
"import a, * as b from 'foo.js'"
'''
import * as a from 'foo.js'
import b from 'bar.js'
'''
'''
import * as bar from 'bar.js'
import * as foo from 'foo.js'
'''
,
# https://github.com/eslint/eslint/issues/5130
code: '''
import 'foo'
import bar from 'bar'
'''
options: ignoreCaseArgs
,
# https://github.com/eslint/eslint/issues/5305
"import React, {Component} from 'react'"
]
invalid: [
code: '''
import a from 'foo.js'
import A from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import b from 'foo.js'
import a from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import {b, c} from 'foo.js'
import {a, d} from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import * as foo from 'foo.js'
import * as bar from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import a from 'foo.js'
import {b, c} from 'bar.js'
'''
output: null
errors: [
message: "Expected 'multiple' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import * as b from 'bar.js'
'''
output: null
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import 'bar.js'
'''
output: null
errors: [
message: "Expected 'none' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import b from 'bar.js'
import * as a from 'foo.js'
'''
output: null
options: [memberSyntaxSortOrder: ['all', 'single', 'multiple', 'none']]
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: "import {b, a, d, c} from 'foo.js'"
output: "import {a, b, c, d} from 'foo.js'"
errors: [
message:
"Member 'a' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {a, B, c, D} from 'foo.js'"
output: "import {B, D, a, c} from 'foo.js'"
errors: [
message:
"Member 'B' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, ### comment ### aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz ### comment ###, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {### comment ### zzzzz, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, aaaaa ### comment ###} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: '''
import {
boop,
foo,
zoo,
baz as qux,
bar,
beep
} from 'foo.js'
'''
output: '''
import {
bar,
beep,
boop,
foo,
baz as qux,
zoo
} from 'foo.js'
'''
errors: [
message:
"Member 'qux' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
]
| true | ###*
# @fileoverview Tests for sort-imports rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/sort-imports'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'Imports should be sorted alphabetically.'
type: 'ImportDeclaration'
ignoreCaseArgs = [ignoreCase: yes]
ruleTester.run 'sort-imports', rule,
valid: [
'''
import a from 'foo.js'
import b from 'bar.js'
import c from 'baz.js'
'''
'''
import * as B from 'foo.js'
import A from 'bar.js'
'''
'''
import * as B from 'foo.js'
import {a, b} from 'bar.js'
'''
'''
import {b, c} from 'bar.js'
import A from 'foo.js'
'''
,
code: '''
import A from 'bar.js'
import {b, c} from 'foo.js'
'''
options: [memberSyntaxSortOrder: ['single', 'multiple', 'none', 'all']]
,
'''
import {a, b} from 'bar.js'
import {c, d} from 'foo.js'
'''
'''
import A from 'foo.js'
import B from 'bar.js'
'''
'''
import A from 'foo.js'
import a from 'bar.js'
'''
'''
import a, * as b from 'foo.js'
import c from 'bar.js'
'''
'''
import 'foo.js'
import a from 'bar.js'
'''
'''
import B from 'foo.js'
import a from 'bar.js'
'''
,
code: '''
import a from 'foo.js'
import B from 'bar.js'
'''
options: ignoreCaseArgs
,
"import {a, b, c, d} from 'foo.js'"
,
code: "import {b, A, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {B, a, C, d} from 'foo.js'"
options: [ignoreMemberSort: yes]
,
code: "import {a, B, c, D} from 'foo.js'"
options: ignoreCaseArgs
,
"import a, * as b from 'foo.js'"
'''
import * as a from 'foo.js'
import b from 'bar.js'
'''
'''
import * as bar from 'bar.js'
import * as foo from 'foo.js'
'''
,
# https://github.com/eslint/eslint/issues/5130
code: '''
import 'foo'
import bar from 'bar'
'''
options: ignoreCaseArgs
,
# https://github.com/eslint/eslint/issues/5305
"import React, {Component} from 'react'"
]
invalid: [
code: '''
import a from 'foo.js'
import A from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import b from 'foo.js'
import a from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import {b, c} from 'foo.js'
import {a, d} from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import * as foo from 'foo.js'
import * as bar from 'bar.js'
'''
output: null
errors: [expectedError]
,
code: '''
import a from 'foo.js'
import {b, c} from 'bar.js'
'''
output: null
errors: [
message: "Expected 'multiple' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import * as b from 'bar.js'
'''
output: null
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import a from 'foo.js'
import 'bar.js'
'''
output: null
errors: [
message: "Expected 'none' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: '''
import b from 'bar.js'
import * as a from 'foo.js'
'''
output: null
options: [memberSyntaxSortOrder: ['all', 'single', 'multiple', 'none']]
errors: [
message: "Expected 'all' syntax before 'single' syntax."
type: 'ImportDeclaration'
]
,
code: "import {b, a, d, c} from 'foo.js'"
output: "import {a, b, c, d} from 'foo.js'"
errors: [
message:
"Member 'a' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {a, B, c, D} from 'foo.js'"
output: "import {B, D, a, c} from 'foo.js'"
errors: [
message:
"Member 'B' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, ### comment ### aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz ### comment ###, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {### comment ### zzzzz, aaaaa} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: "import {zzzzz, aaaaa ### comment ###} from 'foo.js'"
output: null # not fixed due to comment
errors: [
message:
"Member 'aaaaa' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
,
code: '''
import {
boop,
foo,
zoo,
baz as qux,
bar,
beep
} from 'foo.js'
'''
output: '''
import {
bar,
beep,
boop,
foo,
baz as qux,
zoo
} from 'foo.js'
'''
errors: [
message:
"Member 'qux' of the import declaration should be sorted alphabetically."
type: 'ImportSpecifier'
]
]
|
[
{
"context": "ringify(quads))\n\n floatValue: (s, p) ->\n key = s.value + '|' + p.value\n hit = @cachedFloatValues.get(ke",
"end": 9669,
"score": 0.8900423645973206,
"start": 9660,
"tag": "KEY",
"value": "s.value +"
},
{
"context": "s))\n\n floatValue: (s, p) ->\n key = s.... | light9/web/graph.coffee | drewp/light9 | 2 | log = debug('graph')
# Patch is {addQuads: <quads>, delQuads: <quads>}
# <quads> are made with Quad(s,p,o,g)
# for mocha
if require?
`window = {}`
`_ = require('./lib/underscore/underscore-min.js')`
`N3 = require('../../node_modules/n3/n3-browser.js')`
`d3 = require('../../node_modules/d3/dist/d3.min.js')`
`RdfDbClient = require('./rdfdbclient.js').RdfDbClient`
module.exports = window
RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
patchSizeSummary = (patch) ->
'-' + patch.delQuads.length + ' +' + patch.addQuads.length
# (sloppily shared to rdfdbclient.coffee too)
window.patchSizeSummary = patchSizeSummary
patchContainsPreds = (patch, preds) ->
if patch._allPreds == undefined
patch._allPreds = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allPreds.add(q.predicate.value)
for p in preds
if patch._allPreds.has(p.value)
return true
return false
allPatchSubjs = (patch) -> # returns subjs as Set of strings
out = new Set()
if patch._allSubjs == undefined
patch._allSubjs = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allSubjs.add(q.subject.value)
return patch._allSubjs
class Handler
# a function and the quad patterns it cared about
constructor: (@func, @label) ->
@patterns = [] # s,p,o,g quads that should trigger the next run
@innerHandlers = [] # Handlers requested while this one was running
class AutoDependencies
constructor: () ->
# tree of all known Handlers (at least those with non-empty
# patterns). Top node is not a handler.
@handlers = new Handler(null)
@handlerStack = [@handlers] # currently running
runHandler: (func, label) ->
# what if we have this func already? duplicate is safe?
if not label?
throw new Error("missing label")
h = new Handler(func, label)
tailChildren = @handlerStack[@handlerStack.length - 1].innerHandlers
matchingLabel = _.filter(tailChildren, ((c) -> c.label == label)).length
# ohno, something depends on some handlers getting run twice :(
if matchingLabel < 2
tailChildren.push(h)
#console.time("handler #{label}")
@_rerunHandler(h, null)
#console.timeEnd("handler #{label}")
#@_logHandlerTree()
_rerunHandler: (handler, patch) ->
handler.patterns = []
@handlerStack.push(handler)
try
handler.func(patch)
catch e
log('error running handler: ', e)
# assuming here it didn't get to do all its queries, we could
# add a *,*,*,* handler to call for sure the next time?
finally
#log('done. got: ', handler.patterns)
@handlerStack.pop()
# handler might have no watches, in which case we could forget about it
_logHandlerTree: ->
log('handler tree:')
prn = (h, depth) ->
indent = ''
for i in [0...depth]
indent += ' '
log("#{indent} \"#{h.label}\" #{h.patterns.length} pats")
for c in h.innerHandlers
prn(c, depth + 1)
prn(@handlers, 0)
_handlerIsAffected: (child, patchSubjs) ->
if patchSubjs == null
return true
if not child.patterns.length
return false
for stmt in child.patterns
if stmt[0] == null # wildcard on subject
return true
if patchSubjs.has(stmt[0].value)
return true
return false
graphChanged: (patch) ->
# SyncedGraph is telling us this patch just got applied to the graph.
subjs = allPatchSubjs(patch)
rerunInners = (cur) =>
toRun = cur.innerHandlers.slice()
for child in toRun
#match = @_handlerIsAffected(child, subjs)
#continue if not match
#log('match', child.label, match)
#child.innerHandlers = [] # let all children get called again
@_rerunHandler(child, patch)
rerunInners(child)
rerunInners(@handlers)
askedFor: (s, p, o, g) ->
# SyncedGraph is telling us someone did a query that depended on
# quads in the given pattern.
current = @handlerStack[@handlerStack.length - 1]
if current? and current != @handlers
current.patterns.push([s, p, o, g])
#log('push', s,p,o,g)
#else
# console.trace('read outside runHandler')
class window.SyncedGraph
# Main graph object for a browser to use. Syncs both ways with
# rdfdb. Meant to hide the choice of RDF lib, so we can change it
# later.
#
# Note that _applyPatch is the only method to write to the graph, so
# it can fire subscriptions.
constructor: (@patchSenderUrl, @prefixes, @setStatus, @clearCb) ->
# patchSenderUrl is the /syncedGraph path of an rdfdb server.
# prefixes can be used in Uri(curie) calls.
@_autoDeps = new AutoDependencies() # replaces GraphWatchers
@clearGraph()
if @patchSenderUrl
@_client = new RdfDbClient(@patchSenderUrl,
@_clearGraphOnNewConnection.bind(@),
@_applyPatch.bind(@),
@setStatus)
clearGraph: ->
# just deletes the statements; watchers are unaffected.
if @graph?
@_applyPatch({addQuads: [], delQuads: @graph.getQuads()})
# if we had a Store already, this lets N3.Store free all its indices/etc
@graph = N3.Store()
@_addPrefixes(@prefixes)
@cachedFloatValues = new Map() # s + '|' + p -> number
@cachedUriValues = new Map() # s + '|' + p -> Uri
_clearGraphOnNewConnection: -> # must not send a patch to the server!
log('graph: clearGraphOnNewConnection')
@clearGraph()
log('graph: clearGraphOnNewConnection done')
@clearCb() if @clearCb?
_addPrefixes: (prefixes) ->
for k in (prefixes or {})
@prefixes[k] = prefixes[k]
@prefixFuncs = N3.Util.prefixes(@prefixes)
Uri: (curie) ->
if not curie?
throw new Error("no uri")
if curie.match(/^http/)
return N3.DataFactory.namedNode(curie)
part = curie.split(':')
return @prefixFuncs(part[0])(part[1])
Literal: (jsValue) ->
N3.DataFactory.literal(jsValue)
LiteralRoundedFloat: (f) ->
N3.DataFactory.literal(d3.format(".3f")(f),
@Uri("http://www.w3.org/2001/XMLSchema#double"))
Quad: (s, p, o, g) -> N3.DataFactory.quad(s, p, o, g)
toJs: (literal) ->
# incomplete
parseFloat(literal.value)
loadTrig: (trig, cb) -> # for debugging
patch = {delQuads: [], addQuads: []}
parser = N3.Parser()
parser.parse trig, (error, quad, prefixes) =>
if error
throw new Error(error)
if (quad)
patch.addQuads.push(quad)
else
@_applyPatch(patch)
@_addPrefixes(prefixes)
cb() if cb
quads: () -> # for debugging
[q.subject, q.predicate, q.object, q.graph] for q in @graph.getQuads()
applyAndSendPatch: (patch) ->
console.time('applyAndSendPatch')
if not @_client
log('not connected-- dropping patch')
return
if !Array.isArray(patch.addQuads) || !Array.isArray(patch.delQuads)
console.timeEnd('applyAndSendPatch')
log('corrupt patch')
throw new Error("corrupt patch: #{JSON.stringify(patch)}")
@_validatePatch(patch)
@_applyPatch(patch)
@_client.sendPatch(patch) if @_client
console.timeEnd('applyAndSendPatch')
_validatePatch: (patch) ->
for qs in [patch.addQuads, patch.delQuads]
for q in qs
if not q.equals
throw new Error("doesn't look like a proper Quad")
if not q.subject.id or not q.graph.id? or not q.predicate.id?
throw new Error("corrupt patch: #{JSON.stringify(q)}")
_applyPatch: (patch) ->
# In most cases you want applyAndSendPatch.
#
# This is the only method that writes to @graph!
@cachedFloatValues.clear()
@cachedUriValues.clear()
for quad in patch.delQuads
#log("remove #{JSON.stringify(quad)}")
did = @graph.removeQuad(quad)
#log("removed: #{did}")
for quad in patch.addQuads
@graph.addQuad(quad)
#log('applied patch locally', patchSizeSummary(patch))
@_autoDeps.graphChanged(patch)
getObjectPatch: (s, p, newObject, g) ->
# make a patch which removes existing values for (s,p,*,c) and
# adds (s,p,newObject,c). Values in other graphs are not affected.
existing = @graph.getQuads(s, p, null, g)
return {
delQuads: existing,
addQuads: [@Quad(s, p, newObject, g)]
}
patchObject: (s, p, newObject, g) ->
@applyAndSendPatch(@getObjectPatch(s, p, newObject, g))
clearObjects: (s, p, g) ->
@applyAndSendPatch({
delQuads: @graph.getQuads(s, p, null, g),
addQuads: []
})
runHandler: (func, label) ->
# runs your func once, tracking graph calls. if a future patch
# matches what you queried, we runHandler your func again (and
# forget your queries from the first time).
# helps with memleak? not sure yet. The point was if two matching
# labels get puushed on, we should run only one. So maybe
# appending a serial number is backwards.
@serial = 1 if not @serial
@serial += 1
#label = label + @serial
@_autoDeps.runHandler(func, label)
_singleValue: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
objs = new Set(q.object for q in quads)
switch objs.size
when 0
throw new Error("no value for "+s.value+" "+p.value)
when 1
obj = objs.values().next().value
return obj
else
throw new Error("too many different values: " + JSON.stringify(quads))
floatValue: (s, p) ->
key = s.value + '|' + p.value
hit = @cachedFloatValues.get(key)
return hit if hit != undefined
#log('float miss', s, p)
v = @_singleValue(s, p).value
ret = parseFloat(v)
if isNaN(ret)
throw new Error("#{s.value} #{p.value} -> #{v} not a float")
@cachedFloatValues.set(key, ret)
return ret
stringValue: (s, p) ->
@_singleValue(s, p).value
uriValue: (s, p) ->
key = s.value + '|' + p.value
hit = @cachedUriValues.get(key)
return hit if hit != undefined
ret = @_singleValue(s, p)
@cachedUriValues.set(key, ret)
return ret
labelOrTail: (uri) ->
try
ret = @stringValue(uri, @Uri('rdfs:label'))
catch
words = uri.value.split('/')
ret = words[words.length-1]
if not ret
ret = uri.value
return ret
objects: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
return (q.object for q in quads)
subjects: (p, o) ->
@_autoDeps.askedFor(null, p, o, null)
quads = @graph.getQuads(null, p, o)
return (q.subject for q in quads)
items: (list) ->
out = []
current = list
while true
if current == RDF + 'nil'
break
@_autoDeps.askedFor(current, null, null, null) # a little loose
firsts = @graph.getQuads(current, RDF + 'first', null)
rests = @graph.getQuads(current, RDF + 'rest', null)
if firsts.length != 1
throw new Error(
"list node #{current} has #{firsts.length} rdf:first edges")
out.push(firsts[0].object)
if rests.length != 1
throw new Error(
"list node #{current} has #{rests.length} rdf:rest edges")
current = rests[0].object
return out
contains: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
log('contains calling getQuads when graph has ', @graph.size)
return @graph.getQuads(s, p, o).length > 0
nextNumberedResources: (base, howMany) ->
# base is NamedNode or string
# Note this is unsafe before we're synced with the graph. It'll
# always return 'name0'.
base = base.id if base.id
results = []
# @contains is really slow.
@_nextNumber = new Map() unless @_nextNumber?
start = @_nextNumber.get(base)
if start == undefined
start = 0
for serial in [start..1000]
uri = @Uri("#{base}#{serial}")
if not @contains(uri, null, null)
results.push(uri)
log('nextNumberedResources', "picked #{uri}")
@_nextNumber.set(base, serial + 1)
if results.length >= howMany
return results
throw new Error("can't make sequential uri with base #{base}")
nextNumberedResource: (base) ->
@nextNumberedResources(base, 1)[0]
contextsWithPattern: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
ctxs = []
for q in @graph.getQuads(s, p, o)
ctxs.push(q.graph)
return _.unique(ctxs)
sortKey: (uri) ->
parts = uri.value.split(/([0-9]+)/)
expanded = parts.map (p) ->
f = parseInt(p)
return p if isNaN(f)
return p.padStart(8, '0')
return expanded.join('')
sortedUris: (uris) ->
_.sortBy uris, @sortKey
# temporary optimization since autodeps calls too often
@patchContainsPreds: (patch, preds) ->
patchContainsPreds(patch, preds)
prettyLiteral: (x) ->
if typeof(x) == 'number'
@LiteralRoundedFloat(x)
else
@Literal(x)
| 175996 | log = debug('graph')
# Patch is {addQuads: <quads>, delQuads: <quads>}
# <quads> are made with Quad(s,p,o,g)
# for mocha
if require?
`window = {}`
`_ = require('./lib/underscore/underscore-min.js')`
`N3 = require('../../node_modules/n3/n3-browser.js')`
`d3 = require('../../node_modules/d3/dist/d3.min.js')`
`RdfDbClient = require('./rdfdbclient.js').RdfDbClient`
module.exports = window
RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
patchSizeSummary = (patch) ->
'-' + patch.delQuads.length + ' +' + patch.addQuads.length
# (sloppily shared to rdfdbclient.coffee too)
window.patchSizeSummary = patchSizeSummary
patchContainsPreds = (patch, preds) ->
if patch._allPreds == undefined
patch._allPreds = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allPreds.add(q.predicate.value)
for p in preds
if patch._allPreds.has(p.value)
return true
return false
allPatchSubjs = (patch) -> # returns subjs as Set of strings
out = new Set()
if patch._allSubjs == undefined
patch._allSubjs = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allSubjs.add(q.subject.value)
return patch._allSubjs
class Handler
# a function and the quad patterns it cared about
constructor: (@func, @label) ->
@patterns = [] # s,p,o,g quads that should trigger the next run
@innerHandlers = [] # Handlers requested while this one was running
class AutoDependencies
constructor: () ->
# tree of all known Handlers (at least those with non-empty
# patterns). Top node is not a handler.
@handlers = new Handler(null)
@handlerStack = [@handlers] # currently running
runHandler: (func, label) ->
# what if we have this func already? duplicate is safe?
if not label?
throw new Error("missing label")
h = new Handler(func, label)
tailChildren = @handlerStack[@handlerStack.length - 1].innerHandlers
matchingLabel = _.filter(tailChildren, ((c) -> c.label == label)).length
# ohno, something depends on some handlers getting run twice :(
if matchingLabel < 2
tailChildren.push(h)
#console.time("handler #{label}")
@_rerunHandler(h, null)
#console.timeEnd("handler #{label}")
#@_logHandlerTree()
_rerunHandler: (handler, patch) ->
handler.patterns = []
@handlerStack.push(handler)
try
handler.func(patch)
catch e
log('error running handler: ', e)
# assuming here it didn't get to do all its queries, we could
# add a *,*,*,* handler to call for sure the next time?
finally
#log('done. got: ', handler.patterns)
@handlerStack.pop()
# handler might have no watches, in which case we could forget about it
_logHandlerTree: ->
log('handler tree:')
prn = (h, depth) ->
indent = ''
for i in [0...depth]
indent += ' '
log("#{indent} \"#{h.label}\" #{h.patterns.length} pats")
for c in h.innerHandlers
prn(c, depth + 1)
prn(@handlers, 0)
_handlerIsAffected: (child, patchSubjs) ->
if patchSubjs == null
return true
if not child.patterns.length
return false
for stmt in child.patterns
if stmt[0] == null # wildcard on subject
return true
if patchSubjs.has(stmt[0].value)
return true
return false
graphChanged: (patch) ->
# SyncedGraph is telling us this patch just got applied to the graph.
subjs = allPatchSubjs(patch)
rerunInners = (cur) =>
toRun = cur.innerHandlers.slice()
for child in toRun
#match = @_handlerIsAffected(child, subjs)
#continue if not match
#log('match', child.label, match)
#child.innerHandlers = [] # let all children get called again
@_rerunHandler(child, patch)
rerunInners(child)
rerunInners(@handlers)
askedFor: (s, p, o, g) ->
# SyncedGraph is telling us someone did a query that depended on
# quads in the given pattern.
current = @handlerStack[@handlerStack.length - 1]
if current? and current != @handlers
current.patterns.push([s, p, o, g])
#log('push', s,p,o,g)
#else
# console.trace('read outside runHandler')
class window.SyncedGraph
# Main graph object for a browser to use. Syncs both ways with
# rdfdb. Meant to hide the choice of RDF lib, so we can change it
# later.
#
# Note that _applyPatch is the only method to write to the graph, so
# it can fire subscriptions.
constructor: (@patchSenderUrl, @prefixes, @setStatus, @clearCb) ->
# patchSenderUrl is the /syncedGraph path of an rdfdb server.
# prefixes can be used in Uri(curie) calls.
@_autoDeps = new AutoDependencies() # replaces GraphWatchers
@clearGraph()
if @patchSenderUrl
@_client = new RdfDbClient(@patchSenderUrl,
@_clearGraphOnNewConnection.bind(@),
@_applyPatch.bind(@),
@setStatus)
clearGraph: ->
# just deletes the statements; watchers are unaffected.
if @graph?
@_applyPatch({addQuads: [], delQuads: @graph.getQuads()})
# if we had a Store already, this lets N3.Store free all its indices/etc
@graph = N3.Store()
@_addPrefixes(@prefixes)
@cachedFloatValues = new Map() # s + '|' + p -> number
@cachedUriValues = new Map() # s + '|' + p -> Uri
_clearGraphOnNewConnection: -> # must not send a patch to the server!
log('graph: clearGraphOnNewConnection')
@clearGraph()
log('graph: clearGraphOnNewConnection done')
@clearCb() if @clearCb?
_addPrefixes: (prefixes) ->
for k in (prefixes or {})
@prefixes[k] = prefixes[k]
@prefixFuncs = N3.Util.prefixes(@prefixes)
Uri: (curie) ->
if not curie?
throw new Error("no uri")
if curie.match(/^http/)
return N3.DataFactory.namedNode(curie)
part = curie.split(':')
return @prefixFuncs(part[0])(part[1])
Literal: (jsValue) ->
N3.DataFactory.literal(jsValue)
LiteralRoundedFloat: (f) ->
N3.DataFactory.literal(d3.format(".3f")(f),
@Uri("http://www.w3.org/2001/XMLSchema#double"))
Quad: (s, p, o, g) -> N3.DataFactory.quad(s, p, o, g)
toJs: (literal) ->
# incomplete
parseFloat(literal.value)
loadTrig: (trig, cb) -> # for debugging
patch = {delQuads: [], addQuads: []}
parser = N3.Parser()
parser.parse trig, (error, quad, prefixes) =>
if error
throw new Error(error)
if (quad)
patch.addQuads.push(quad)
else
@_applyPatch(patch)
@_addPrefixes(prefixes)
cb() if cb
quads: () -> # for debugging
[q.subject, q.predicate, q.object, q.graph] for q in @graph.getQuads()
applyAndSendPatch: (patch) ->
console.time('applyAndSendPatch')
if not @_client
log('not connected-- dropping patch')
return
if !Array.isArray(patch.addQuads) || !Array.isArray(patch.delQuads)
console.timeEnd('applyAndSendPatch')
log('corrupt patch')
throw new Error("corrupt patch: #{JSON.stringify(patch)}")
@_validatePatch(patch)
@_applyPatch(patch)
@_client.sendPatch(patch) if @_client
console.timeEnd('applyAndSendPatch')
_validatePatch: (patch) ->
for qs in [patch.addQuads, patch.delQuads]
for q in qs
if not q.equals
throw new Error("doesn't look like a proper Quad")
if not q.subject.id or not q.graph.id? or not q.predicate.id?
throw new Error("corrupt patch: #{JSON.stringify(q)}")
_applyPatch: (patch) ->
# In most cases you want applyAndSendPatch.
#
# This is the only method that writes to @graph!
@cachedFloatValues.clear()
@cachedUriValues.clear()
for quad in patch.delQuads
#log("remove #{JSON.stringify(quad)}")
did = @graph.removeQuad(quad)
#log("removed: #{did}")
for quad in patch.addQuads
@graph.addQuad(quad)
#log('applied patch locally', patchSizeSummary(patch))
@_autoDeps.graphChanged(patch)
getObjectPatch: (s, p, newObject, g) ->
# make a patch which removes existing values for (s,p,*,c) and
# adds (s,p,newObject,c). Values in other graphs are not affected.
existing = @graph.getQuads(s, p, null, g)
return {
delQuads: existing,
addQuads: [@Quad(s, p, newObject, g)]
}
patchObject: (s, p, newObject, g) ->
@applyAndSendPatch(@getObjectPatch(s, p, newObject, g))
clearObjects: (s, p, g) ->
@applyAndSendPatch({
delQuads: @graph.getQuads(s, p, null, g),
addQuads: []
})
runHandler: (func, label) ->
# runs your func once, tracking graph calls. if a future patch
# matches what you queried, we runHandler your func again (and
# forget your queries from the first time).
# helps with memleak? not sure yet. The point was if two matching
# labels get puushed on, we should run only one. So maybe
# appending a serial number is backwards.
@serial = 1 if not @serial
@serial += 1
#label = label + @serial
@_autoDeps.runHandler(func, label)
_singleValue: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
objs = new Set(q.object for q in quads)
switch objs.size
when 0
throw new Error("no value for "+s.value+" "+p.value)
when 1
obj = objs.values().next().value
return obj
else
throw new Error("too many different values: " + JSON.stringify(quads))
floatValue: (s, p) ->
key = <KEY> '|' <KEY>
hit = @cachedFloatValues.get(key)
return hit if hit != undefined
#log('float miss', s, p)
v = @_singleValue(s, p).value
ret = parseFloat(v)
if isNaN(ret)
throw new Error("#{s.value} #{p.value} -> #{v} not a float")
@cachedFloatValues.set(key, ret)
return ret
stringValue: (s, p) ->
@_singleValue(s, p).value
uriValue: (s, p) ->
key = s.<KEY> '|' + p.<KEY>
hit = @cachedUriValues.get(key)
return hit if hit != undefined
ret = @_singleValue(s, p)
@cachedUriValues.set(key, ret)
return ret
labelOrTail: (uri) ->
try
ret = @stringValue(uri, @Uri('rdfs:label'))
catch
words = uri.value.split('/')
ret = words[words.length-1]
if not ret
ret = uri.value
return ret
objects: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
return (q.object for q in quads)
subjects: (p, o) ->
@_autoDeps.askedFor(null, p, o, null)
quads = @graph.getQuads(null, p, o)
return (q.subject for q in quads)
items: (list) ->
out = []
current = list
while true
if current == RDF + 'nil'
break
@_autoDeps.askedFor(current, null, null, null) # a little loose
firsts = @graph.getQuads(current, RDF + 'first', null)
rests = @graph.getQuads(current, RDF + 'rest', null)
if firsts.length != 1
throw new Error(
"list node #{current} has #{firsts.length} rdf:first edges")
out.push(firsts[0].object)
if rests.length != 1
throw new Error(
"list node #{current} has #{rests.length} rdf:rest edges")
current = rests[0].object
return out
contains: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
log('contains calling getQuads when graph has ', @graph.size)
return @graph.getQuads(s, p, o).length > 0
nextNumberedResources: (base, howMany) ->
# base is NamedNode or string
# Note this is unsafe before we're synced with the graph. It'll
# always return 'name0'.
base = base.id if base.id
results = []
# @contains is really slow.
@_nextNumber = new Map() unless @_nextNumber?
start = @_nextNumber.get(base)
if start == undefined
start = 0
for serial in [start..1000]
uri = @Uri("#{base}#{serial}")
if not @contains(uri, null, null)
results.push(uri)
log('nextNumberedResources', "picked #{uri}")
@_nextNumber.set(base, serial + 1)
if results.length >= howMany
return results
throw new Error("can't make sequential uri with base #{base}")
nextNumberedResource: (base) ->
@nextNumberedResources(base, 1)[0]
contextsWithPattern: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
ctxs = []
for q in @graph.getQuads(s, p, o)
ctxs.push(q.graph)
return _.unique(ctxs)
sortKey: (uri) ->
parts = uri.value.split(/([0-9]+)/)
expanded = parts.map (p) ->
f = parseInt(p)
return p if isNaN(f)
return p.padStart(8, '0')
return expanded.join('')
sortedUris: (uris) ->
_.sortBy uris, @sortKey
# temporary optimization since autodeps calls too often
@patchContainsPreds: (patch, preds) ->
patchContainsPreds(patch, preds)
prettyLiteral: (x) ->
if typeof(x) == 'number'
@LiteralRoundedFloat(x)
else
@Literal(x)
| true | log = debug('graph')
# Patch is {addQuads: <quads>, delQuads: <quads>}
# <quads> are made with Quad(s,p,o,g)
# for mocha
if require?
`window = {}`
`_ = require('./lib/underscore/underscore-min.js')`
`N3 = require('../../node_modules/n3/n3-browser.js')`
`d3 = require('../../node_modules/d3/dist/d3.min.js')`
`RdfDbClient = require('./rdfdbclient.js').RdfDbClient`
module.exports = window
RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
patchSizeSummary = (patch) ->
'-' + patch.delQuads.length + ' +' + patch.addQuads.length
# (sloppily shared to rdfdbclient.coffee too)
window.patchSizeSummary = patchSizeSummary
patchContainsPreds = (patch, preds) ->
if patch._allPreds == undefined
patch._allPreds = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allPreds.add(q.predicate.value)
for p in preds
if patch._allPreds.has(p.value)
return true
return false
allPatchSubjs = (patch) -> # returns subjs as Set of strings
out = new Set()
if patch._allSubjs == undefined
patch._allSubjs = new Set()
for qq in [patch.addQuads, patch.delQuads]
for q in qq
patch._allSubjs.add(q.subject.value)
return patch._allSubjs
class Handler
# a function and the quad patterns it cared about
constructor: (@func, @label) ->
@patterns = [] # s,p,o,g quads that should trigger the next run
@innerHandlers = [] # Handlers requested while this one was running
class AutoDependencies
constructor: () ->
# tree of all known Handlers (at least those with non-empty
# patterns). Top node is not a handler.
@handlers = new Handler(null)
@handlerStack = [@handlers] # currently running
runHandler: (func, label) ->
# what if we have this func already? duplicate is safe?
if not label?
throw new Error("missing label")
h = new Handler(func, label)
tailChildren = @handlerStack[@handlerStack.length - 1].innerHandlers
matchingLabel = _.filter(tailChildren, ((c) -> c.label == label)).length
# ohno, something depends on some handlers getting run twice :(
if matchingLabel < 2
tailChildren.push(h)
#console.time("handler #{label}")
@_rerunHandler(h, null)
#console.timeEnd("handler #{label}")
#@_logHandlerTree()
_rerunHandler: (handler, patch) ->
handler.patterns = []
@handlerStack.push(handler)
try
handler.func(patch)
catch e
log('error running handler: ', e)
# assuming here it didn't get to do all its queries, we could
# add a *,*,*,* handler to call for sure the next time?
finally
#log('done. got: ', handler.patterns)
@handlerStack.pop()
# handler might have no watches, in which case we could forget about it
_logHandlerTree: ->
log('handler tree:')
prn = (h, depth) ->
indent = ''
for i in [0...depth]
indent += ' '
log("#{indent} \"#{h.label}\" #{h.patterns.length} pats")
for c in h.innerHandlers
prn(c, depth + 1)
prn(@handlers, 0)
_handlerIsAffected: (child, patchSubjs) ->
if patchSubjs == null
return true
if not child.patterns.length
return false
for stmt in child.patterns
if stmt[0] == null # wildcard on subject
return true
if patchSubjs.has(stmt[0].value)
return true
return false
graphChanged: (patch) ->
# SyncedGraph is telling us this patch just got applied to the graph.
subjs = allPatchSubjs(patch)
rerunInners = (cur) =>
toRun = cur.innerHandlers.slice()
for child in toRun
#match = @_handlerIsAffected(child, subjs)
#continue if not match
#log('match', child.label, match)
#child.innerHandlers = [] # let all children get called again
@_rerunHandler(child, patch)
rerunInners(child)
rerunInners(@handlers)
askedFor: (s, p, o, g) ->
# SyncedGraph is telling us someone did a query that depended on
# quads in the given pattern.
current = @handlerStack[@handlerStack.length - 1]
if current? and current != @handlers
current.patterns.push([s, p, o, g])
#log('push', s,p,o,g)
#else
# console.trace('read outside runHandler')
class window.SyncedGraph
# Main graph object for a browser to use. Syncs both ways with
# rdfdb. Meant to hide the choice of RDF lib, so we can change it
# later.
#
# Note that _applyPatch is the only method to write to the graph, so
# it can fire subscriptions.
constructor: (@patchSenderUrl, @prefixes, @setStatus, @clearCb) ->
# patchSenderUrl is the /syncedGraph path of an rdfdb server.
# prefixes can be used in Uri(curie) calls.
@_autoDeps = new AutoDependencies() # replaces GraphWatchers
@clearGraph()
if @patchSenderUrl
@_client = new RdfDbClient(@patchSenderUrl,
@_clearGraphOnNewConnection.bind(@),
@_applyPatch.bind(@),
@setStatus)
clearGraph: ->
# just deletes the statements; watchers are unaffected.
if @graph?
@_applyPatch({addQuads: [], delQuads: @graph.getQuads()})
# if we had a Store already, this lets N3.Store free all its indices/etc
@graph = N3.Store()
@_addPrefixes(@prefixes)
@cachedFloatValues = new Map() # s + '|' + p -> number
@cachedUriValues = new Map() # s + '|' + p -> Uri
_clearGraphOnNewConnection: -> # must not send a patch to the server!
log('graph: clearGraphOnNewConnection')
@clearGraph()
log('graph: clearGraphOnNewConnection done')
@clearCb() if @clearCb?
_addPrefixes: (prefixes) ->
for k in (prefixes or {})
@prefixes[k] = prefixes[k]
@prefixFuncs = N3.Util.prefixes(@prefixes)
Uri: (curie) ->
if not curie?
throw new Error("no uri")
if curie.match(/^http/)
return N3.DataFactory.namedNode(curie)
part = curie.split(':')
return @prefixFuncs(part[0])(part[1])
Literal: (jsValue) ->
N3.DataFactory.literal(jsValue)
LiteralRoundedFloat: (f) ->
N3.DataFactory.literal(d3.format(".3f")(f),
@Uri("http://www.w3.org/2001/XMLSchema#double"))
Quad: (s, p, o, g) -> N3.DataFactory.quad(s, p, o, g)
toJs: (literal) ->
# incomplete
parseFloat(literal.value)
loadTrig: (trig, cb) -> # for debugging
patch = {delQuads: [], addQuads: []}
parser = N3.Parser()
parser.parse trig, (error, quad, prefixes) =>
if error
throw new Error(error)
if (quad)
patch.addQuads.push(quad)
else
@_applyPatch(patch)
@_addPrefixes(prefixes)
cb() if cb
quads: () -> # for debugging
[q.subject, q.predicate, q.object, q.graph] for q in @graph.getQuads()
applyAndSendPatch: (patch) ->
console.time('applyAndSendPatch')
if not @_client
log('not connected-- dropping patch')
return
if !Array.isArray(patch.addQuads) || !Array.isArray(patch.delQuads)
console.timeEnd('applyAndSendPatch')
log('corrupt patch')
throw new Error("corrupt patch: #{JSON.stringify(patch)}")
@_validatePatch(patch)
@_applyPatch(patch)
@_client.sendPatch(patch) if @_client
console.timeEnd('applyAndSendPatch')
_validatePatch: (patch) ->
for qs in [patch.addQuads, patch.delQuads]
for q in qs
if not q.equals
throw new Error("doesn't look like a proper Quad")
if not q.subject.id or not q.graph.id? or not q.predicate.id?
throw new Error("corrupt patch: #{JSON.stringify(q)}")
_applyPatch: (patch) ->
# In most cases you want applyAndSendPatch.
#
# This is the only method that writes to @graph!
@cachedFloatValues.clear()
@cachedUriValues.clear()
for quad in patch.delQuads
#log("remove #{JSON.stringify(quad)}")
did = @graph.removeQuad(quad)
#log("removed: #{did}")
for quad in patch.addQuads
@graph.addQuad(quad)
#log('applied patch locally', patchSizeSummary(patch))
@_autoDeps.graphChanged(patch)
getObjectPatch: (s, p, newObject, g) ->
# make a patch which removes existing values for (s,p,*,c) and
# adds (s,p,newObject,c). Values in other graphs are not affected.
existing = @graph.getQuads(s, p, null, g)
return {
delQuads: existing,
addQuads: [@Quad(s, p, newObject, g)]
}
patchObject: (s, p, newObject, g) ->
@applyAndSendPatch(@getObjectPatch(s, p, newObject, g))
clearObjects: (s, p, g) ->
@applyAndSendPatch({
delQuads: @graph.getQuads(s, p, null, g),
addQuads: []
})
runHandler: (func, label) ->
# runs your func once, tracking graph calls. if a future patch
# matches what you queried, we runHandler your func again (and
# forget your queries from the first time).
# helps with memleak? not sure yet. The point was if two matching
# labels get puushed on, we should run only one. So maybe
# appending a serial number is backwards.
@serial = 1 if not @serial
@serial += 1
#label = label + @serial
@_autoDeps.runHandler(func, label)
_singleValue: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
objs = new Set(q.object for q in quads)
switch objs.size
when 0
throw new Error("no value for "+s.value+" "+p.value)
when 1
obj = objs.values().next().value
return obj
else
throw new Error("too many different values: " + JSON.stringify(quads))
floatValue: (s, p) ->
key = PI:KEY:<KEY>END_PI '|' PI:KEY:<KEY>END_PI
hit = @cachedFloatValues.get(key)
return hit if hit != undefined
#log('float miss', s, p)
v = @_singleValue(s, p).value
ret = parseFloat(v)
if isNaN(ret)
throw new Error("#{s.value} #{p.value} -> #{v} not a float")
@cachedFloatValues.set(key, ret)
return ret
stringValue: (s, p) ->
@_singleValue(s, p).value
uriValue: (s, p) ->
key = s.PI:KEY:<KEY>END_PI '|' + p.PI:KEY:<KEY>END_PI
hit = @cachedUriValues.get(key)
return hit if hit != undefined
ret = @_singleValue(s, p)
@cachedUriValues.set(key, ret)
return ret
labelOrTail: (uri) ->
try
ret = @stringValue(uri, @Uri('rdfs:label'))
catch
words = uri.value.split('/')
ret = words[words.length-1]
if not ret
ret = uri.value
return ret
objects: (s, p) ->
@_autoDeps.askedFor(s, p, null, null)
quads = @graph.getQuads(s, p)
return (q.object for q in quads)
subjects: (p, o) ->
@_autoDeps.askedFor(null, p, o, null)
quads = @graph.getQuads(null, p, o)
return (q.subject for q in quads)
items: (list) ->
out = []
current = list
while true
if current == RDF + 'nil'
break
@_autoDeps.askedFor(current, null, null, null) # a little loose
firsts = @graph.getQuads(current, RDF + 'first', null)
rests = @graph.getQuads(current, RDF + 'rest', null)
if firsts.length != 1
throw new Error(
"list node #{current} has #{firsts.length} rdf:first edges")
out.push(firsts[0].object)
if rests.length != 1
throw new Error(
"list node #{current} has #{rests.length} rdf:rest edges")
current = rests[0].object
return out
contains: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
log('contains calling getQuads when graph has ', @graph.size)
return @graph.getQuads(s, p, o).length > 0
nextNumberedResources: (base, howMany) ->
# base is NamedNode or string
# Note this is unsafe before we're synced with the graph. It'll
# always return 'name0'.
base = base.id if base.id
results = []
# @contains is really slow.
@_nextNumber = new Map() unless @_nextNumber?
start = @_nextNumber.get(base)
if start == undefined
start = 0
for serial in [start..1000]
uri = @Uri("#{base}#{serial}")
if not @contains(uri, null, null)
results.push(uri)
log('nextNumberedResources', "picked #{uri}")
@_nextNumber.set(base, serial + 1)
if results.length >= howMany
return results
throw new Error("can't make sequential uri with base #{base}")
nextNumberedResource: (base) ->
@nextNumberedResources(base, 1)[0]
contextsWithPattern: (s, p, o) ->
@_autoDeps.askedFor(s, p, o, null)
ctxs = []
for q in @graph.getQuads(s, p, o)
ctxs.push(q.graph)
return _.unique(ctxs)
sortKey: (uri) ->
parts = uri.value.split(/([0-9]+)/)
expanded = parts.map (p) ->
f = parseInt(p)
return p if isNaN(f)
return p.padStart(8, '0')
return expanded.join('')
sortedUris: (uris) ->
_.sortBy uris, @sortKey
# temporary optimization since autodeps calls too often
@patchContainsPreds: (patch, preds) ->
patchContainsPreds(patch, preds)
prettyLiteral: (x) ->
if typeof(x) == 'number'
@LiteralRoundedFloat(x)
else
@Literal(x)
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nassert = require 'assert'\n",
"end": 35,
"score": 0.9997118711471558,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/core/mutation.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
assert = require 'assert'
# Public: A record of a single change in a target {Item}.
#
# A new mutation is created to record each attribute set, body text change,
# and child item's update. Use {Outline::onDidChange} to receive this mutation
# record so you can track what has changed as an outline is edited.
module.exports =
class Mutation
###
Section: Constants
###
# Public: ATTRIBUTE_CHANGED Mutation type constant.
@ATTRIBUTE_CHANGED: 'attribute'
# Public: BODT_TEXT_CHANGED Mutation type constant.
@BODT_TEXT_CHANGED: 'bodyText'
# Public: CHILDREN_CHANGED Mutation type constant.
@CHILDREN_CHANGED: 'children'
###
Section: Attributes
###
# Public: Read-only {Item} target of the change delta.
target: null
# Public: Read-only type of change. {Mutation.ATTRIBUTE_CHANGED},
# {Mutation.BODT_TEXT_CHANGED}, or {Mutation.CHILDREN_CHANGED}.
type: null
# Public: Read-only name of changed attribute in the target {Item}, or null.
attributeName: null
# Public: Read-only previous value of changed attribute in the target
# {Item}, or null.
attributeOldValue: null
# Public: Read-only value of the body text location where the insert started
# in the target {Item}, or null.
insertedTextLocation: null
# Public: Read-only value of length of the inserted body text in the target
# {Item}, or null.
insertedTextLength: null
# Public: Read-only value of replaced body text in the target {Item}, or
# null.
replacedText: null
# Public: Read-only {Array} of child {Item}s added to the target.
addedItems: null
# Public: Read-only {Array} of child {Item}s removed from the target.
removedItems: null
# Public: Read-only previous sibling {Item} of the added or removed Items,
# or null.
previousSibling: null
# Public: Read-only next sibling {Item} of the added or removed Items, or
# null.
nextSibling: null
@createAttributeMutation: (target, attributeName, attributeOldValue) ->
mutation = new Mutation target, Mutation.ATTRIBUTE_CHANGED
mutation.attributeName = attributeName
mutation.attributeOldValue = attributeOldValue
mutation
@createBodyTextMutation: (target, insertedTextLocation, insertedTextLength, replacedText) ->
mutation = new Mutation target, Mutation.BODT_TEXT_CHANGED
mutation.insertedTextLocation = insertedTextLocation
mutation.insertedTextLength = insertedTextLength
mutation.replacedText = replacedText
mutation
@createChildrenMutation: (target, addedItems, removedItems, previousSibling, nextSibling) ->
mutation = new Mutation target, Mutation.CHILDREN_CHANGED
mutation.addedItems = addedItems or []
mutation.removedItems = removedItems or []
mutation.previousSibling = previousSibling
mutation.nextSibling = nextSibling
mutation
constructor: (@target, @type) ->
copy: ->
mutation = new Mutation @target, @type
mutation.attributeName = @attributeName
mutation.attributeNewValue = @attributeNewValue
mutation.attributeOldValue = @attributeOldValue
mutation.insertedTextLocation = @insertedTextLocation
mutation.insertedTextLength = @insertedTextLength
mutation.replacedText = @replacedText?.copy()
mutation.addedItems = @addedItems
mutation.removedItems = @removedItems
mutation.previousSibling = @previousSibling
mutation.nextSibling = @nextSibling
mutation
performUndoOperation: ->
switch @type
when Mutation.ATTRIBUTE_CHANGED
@target.setAttribute @attributeName, @attributeOldValue
when Mutation.BODT_TEXT_CHANGED
@target.replaceBodyTextInRange @replacedText, @insertedTextLocation, @insertedTextLength
when Mutation.CHILDREN_CHANGED
if @addedItems.length
@target.removeChildren @addedItems
if @removedItems.length
@target.insertChildrenBefore @removedItems, @nextSibling
coalesce: (operation) ->
return false unless operation instanceof Mutation
return false unless @target is operation.target
return false unless @type is operation.type
return false unless @type is Mutation.BODT_TEXT_CHANGED
thisInsertedTextLocation = @insertedTextLocation
thisInsertLength = @insertedTextLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
newInsertedTextLocation = operation.insertedTextLocation
newInsertedTextLength = operation.insertedTextLength
newReplaceLength = operation.replacedText.length
newReplaceEnd = newInsertedTextLocation + newReplaceLength
singleInsertAtEnd = newInsertedTextLocation is thisInsertEnd and newInsertedTextLength is 1 and newReplaceLength is 0
singleDeleteFromEnd = newReplaceEnd is thisInsertEnd and newInsertedTextLength is 0 and newReplaceLength is 1
if singleInsertAtEnd
@insertedTextLength++
true
else if singleDeleteFromEnd
if newInsertedTextLocation < thisInsertedTextLocation
@replacedText.insertStringAtLocation operation.replacedText, 0
@insertedTextLocation--
else
@insertedTextLength--
true
else
false | 225610 | # Copyright (c) 2015 <NAME>. All rights reserved.
assert = require 'assert'
# Public: A record of a single change in a target {Item}.
#
# A new mutation is created to record each attribute set, body text change,
# and child item's update. Use {Outline::onDidChange} to receive this mutation
# record so you can track what has changed as an outline is edited.
module.exports =
class Mutation
###
Section: Constants
###
# Public: ATTRIBUTE_CHANGED Mutation type constant.
@ATTRIBUTE_CHANGED: 'attribute'
# Public: BODT_TEXT_CHANGED Mutation type constant.
@BODT_TEXT_CHANGED: 'bodyText'
# Public: CHILDREN_CHANGED Mutation type constant.
@CHILDREN_CHANGED: 'children'
###
Section: Attributes
###
# Public: Read-only {Item} target of the change delta.
target: null
# Public: Read-only type of change. {Mutation.ATTRIBUTE_CHANGED},
# {Mutation.BODT_TEXT_CHANGED}, or {Mutation.CHILDREN_CHANGED}.
type: null
# Public: Read-only name of changed attribute in the target {Item}, or null.
attributeName: null
# Public: Read-only previous value of changed attribute in the target
# {Item}, or null.
attributeOldValue: null
# Public: Read-only value of the body text location where the insert started
# in the target {Item}, or null.
insertedTextLocation: null
# Public: Read-only value of length of the inserted body text in the target
# {Item}, or null.
insertedTextLength: null
# Public: Read-only value of replaced body text in the target {Item}, or
# null.
replacedText: null
# Public: Read-only {Array} of child {Item}s added to the target.
addedItems: null
# Public: Read-only {Array} of child {Item}s removed from the target.
removedItems: null
# Public: Read-only previous sibling {Item} of the added or removed Items,
# or null.
previousSibling: null
# Public: Read-only next sibling {Item} of the added or removed Items, or
# null.
nextSibling: null
@createAttributeMutation: (target, attributeName, attributeOldValue) ->
mutation = new Mutation target, Mutation.ATTRIBUTE_CHANGED
mutation.attributeName = attributeName
mutation.attributeOldValue = attributeOldValue
mutation
@createBodyTextMutation: (target, insertedTextLocation, insertedTextLength, replacedText) ->
mutation = new Mutation target, Mutation.BODT_TEXT_CHANGED
mutation.insertedTextLocation = insertedTextLocation
mutation.insertedTextLength = insertedTextLength
mutation.replacedText = replacedText
mutation
@createChildrenMutation: (target, addedItems, removedItems, previousSibling, nextSibling) ->
mutation = new Mutation target, Mutation.CHILDREN_CHANGED
mutation.addedItems = addedItems or []
mutation.removedItems = removedItems or []
mutation.previousSibling = previousSibling
mutation.nextSibling = nextSibling
mutation
constructor: (@target, @type) ->
copy: ->
mutation = new Mutation @target, @type
mutation.attributeName = @attributeName
mutation.attributeNewValue = @attributeNewValue
mutation.attributeOldValue = @attributeOldValue
mutation.insertedTextLocation = @insertedTextLocation
mutation.insertedTextLength = @insertedTextLength
mutation.replacedText = @replacedText?.copy()
mutation.addedItems = @addedItems
mutation.removedItems = @removedItems
mutation.previousSibling = @previousSibling
mutation.nextSibling = @nextSibling
mutation
performUndoOperation: ->
switch @type
when Mutation.ATTRIBUTE_CHANGED
@target.setAttribute @attributeName, @attributeOldValue
when Mutation.BODT_TEXT_CHANGED
@target.replaceBodyTextInRange @replacedText, @insertedTextLocation, @insertedTextLength
when Mutation.CHILDREN_CHANGED
if @addedItems.length
@target.removeChildren @addedItems
if @removedItems.length
@target.insertChildrenBefore @removedItems, @nextSibling
coalesce: (operation) ->
return false unless operation instanceof Mutation
return false unless @target is operation.target
return false unless @type is operation.type
return false unless @type is Mutation.BODT_TEXT_CHANGED
thisInsertedTextLocation = @insertedTextLocation
thisInsertLength = @insertedTextLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
newInsertedTextLocation = operation.insertedTextLocation
newInsertedTextLength = operation.insertedTextLength
newReplaceLength = operation.replacedText.length
newReplaceEnd = newInsertedTextLocation + newReplaceLength
singleInsertAtEnd = newInsertedTextLocation is thisInsertEnd and newInsertedTextLength is 1 and newReplaceLength is 0
singleDeleteFromEnd = newReplaceEnd is thisInsertEnd and newInsertedTextLength is 0 and newReplaceLength is 1
if singleInsertAtEnd
@insertedTextLength++
true
else if singleDeleteFromEnd
if newInsertedTextLocation < thisInsertedTextLocation
@replacedText.insertStringAtLocation operation.replacedText, 0
@insertedTextLocation--
else
@insertedTextLength--
true
else
false | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
assert = require 'assert'
# Public: A record of a single change in a target {Item}.
#
# A new mutation is created to record each attribute set, body text change,
# and child item's update. Use {Outline::onDidChange} to receive this mutation
# record so you can track what has changed as an outline is edited.
module.exports =
class Mutation
###
Section: Constants
###
# Public: ATTRIBUTE_CHANGED Mutation type constant.
@ATTRIBUTE_CHANGED: 'attribute'
# Public: BODT_TEXT_CHANGED Mutation type constant.
@BODT_TEXT_CHANGED: 'bodyText'
# Public: CHILDREN_CHANGED Mutation type constant.
@CHILDREN_CHANGED: 'children'
###
Section: Attributes
###
# Public: Read-only {Item} target of the change delta.
target: null
# Public: Read-only type of change. {Mutation.ATTRIBUTE_CHANGED},
# {Mutation.BODT_TEXT_CHANGED}, or {Mutation.CHILDREN_CHANGED}.
type: null
# Public: Read-only name of changed attribute in the target {Item}, or null.
attributeName: null
# Public: Read-only previous value of changed attribute in the target
# {Item}, or null.
attributeOldValue: null
# Public: Read-only value of the body text location where the insert started
# in the target {Item}, or null.
insertedTextLocation: null
# Public: Read-only value of length of the inserted body text in the target
# {Item}, or null.
insertedTextLength: null
# Public: Read-only value of replaced body text in the target {Item}, or
# null.
replacedText: null
# Public: Read-only {Array} of child {Item}s added to the target.
addedItems: null
# Public: Read-only {Array} of child {Item}s removed from the target.
removedItems: null
# Public: Read-only previous sibling {Item} of the added or removed Items,
# or null.
previousSibling: null
# Public: Read-only next sibling {Item} of the added or removed Items, or
# null.
nextSibling: null
@createAttributeMutation: (target, attributeName, attributeOldValue) ->
mutation = new Mutation target, Mutation.ATTRIBUTE_CHANGED
mutation.attributeName = attributeName
mutation.attributeOldValue = attributeOldValue
mutation
@createBodyTextMutation: (target, insertedTextLocation, insertedTextLength, replacedText) ->
mutation = new Mutation target, Mutation.BODT_TEXT_CHANGED
mutation.insertedTextLocation = insertedTextLocation
mutation.insertedTextLength = insertedTextLength
mutation.replacedText = replacedText
mutation
@createChildrenMutation: (target, addedItems, removedItems, previousSibling, nextSibling) ->
mutation = new Mutation target, Mutation.CHILDREN_CHANGED
mutation.addedItems = addedItems or []
mutation.removedItems = removedItems or []
mutation.previousSibling = previousSibling
mutation.nextSibling = nextSibling
mutation
constructor: (@target, @type) ->
copy: ->
mutation = new Mutation @target, @type
mutation.attributeName = @attributeName
mutation.attributeNewValue = @attributeNewValue
mutation.attributeOldValue = @attributeOldValue
mutation.insertedTextLocation = @insertedTextLocation
mutation.insertedTextLength = @insertedTextLength
mutation.replacedText = @replacedText?.copy()
mutation.addedItems = @addedItems
mutation.removedItems = @removedItems
mutation.previousSibling = @previousSibling
mutation.nextSibling = @nextSibling
mutation
performUndoOperation: ->
switch @type
when Mutation.ATTRIBUTE_CHANGED
@target.setAttribute @attributeName, @attributeOldValue
when Mutation.BODT_TEXT_CHANGED
@target.replaceBodyTextInRange @replacedText, @insertedTextLocation, @insertedTextLength
when Mutation.CHILDREN_CHANGED
if @addedItems.length
@target.removeChildren @addedItems
if @removedItems.length
@target.insertChildrenBefore @removedItems, @nextSibling
coalesce: (operation) ->
return false unless operation instanceof Mutation
return false unless @target is operation.target
return false unless @type is operation.type
return false unless @type is Mutation.BODT_TEXT_CHANGED
thisInsertedTextLocation = @insertedTextLocation
thisInsertLength = @insertedTextLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
thisInsertEnd = thisInsertedTextLocation + thisInsertLength
newInsertedTextLocation = operation.insertedTextLocation
newInsertedTextLength = operation.insertedTextLength
newReplaceLength = operation.replacedText.length
newReplaceEnd = newInsertedTextLocation + newReplaceLength
singleInsertAtEnd = newInsertedTextLocation is thisInsertEnd and newInsertedTextLength is 1 and newReplaceLength is 0
singleDeleteFromEnd = newReplaceEnd is thisInsertEnd and newInsertedTextLength is 0 and newReplaceLength is 1
if singleInsertAtEnd
@insertedTextLength++
true
else if singleDeleteFromEnd
if newInsertedTextLocation < thisInsertedTextLocation
@replacedText.insertStringAtLocation operation.replacedText, 0
@insertedTextLocation--
else
@insertedTextLength--
true
else
false |
[
{
"context": "Send an email using Nodemailer https://github.com/andris9/Nodemailer\n# It expects that config.emailServer a",
"end": 899,
"score": 0.9181981682777405,
"start": 892,
"tag": "USERNAME",
"value": "andris9"
},
{
"context": " from: config.fromEmail || \"Node Notifier ✔... | app.coffee | ChrisCinelli/scraperNotifier | 0 | colors = require 'colors'
winston = require 'winston'
request = require 'request'
_ = require 'underscore'
nodemailer = require 'nodemailer'
request = require 'request'
#We may want to parse the HTML with cheerio eventually, so far I do not need it
#cheerio = require 'cheerio'
#Do we want to dump the html on disk? Maybe later...
#fs = require 'fs'
#Load config.js
try
config = require './config'
catch e
logger.error "Problem reading config.js: ", e.stack || e
config = {};
#Winston Logger rocks baby!
logger = new winston.Logger {
transports: [
new winston.transports.Console({
level : config.logLevel || 'info'
colorize: true
timestamp: true
#Some options that may be useful later
#handleExceptions: true,
#json: true
})
]
exitOnError: true
}
# Send an email using Nodemailer https://github.com/andris9/Nodemailer
# It expects that config.emailServer and config.toEmail are defined (See config.js.template
# You should define at least "subject", and "text". "html" is optional
sendEmail = (options) ->
options.subject = options.rule.url+" is ready!"
emailServerOpt = config.emailServer
#create reusable transport method (opens pool of SMTP connections)
transport = nodemailer.createTransport emailServerOpt.type, emailServerOpt.parameters
#setup e-mail data with unicode symbols
mailOptions = _.extend {}, {
from: config.fromEmail || "Node Notifier ✔ <noreply@nodenotifier.tv>" # sender address
to: config.toEmail # list of receivers comma separated
#subject: "Your subject" # Subject line
#text: "Your text" # plaintext body
#You can add "html" to specify the HTML body
}, options
#send mail with defined transport object
transport.sendMail mailOptions, (error, response) ->
if (error)
logger.warn(error);
else
logger.info("Message sent: " + response.message);
# if you don't want to use this transport object anymore, uncomment following line
transport.close(); # shut down the connection pool, no more messages
slackRequest = (url, data, done) ->
if !url
logger.error('No URL')
return false
if !_.isFunction(done)
done = () -> {}
request.post url, {
form:
payload: JSON.stringify(data)
}, (err, response) ->
if err
logger.info "slackRequest : Error sending message"
return done(err)
if response.body isnt 'ok'
logger.info "slackRequest : Error sending message"
return done(new Error(response.body))
logger.info "slackRequest : Message sent", data
done()
sendSlack = (options) ->
return if !config.slackWebhook
options = _.extend {}, options, config.slackOpts
data = {}
logger.info "sendSlack : Sending message", data
hooks = if _.isArray(config.slackWebhook) then config.slackWebhook else [config.slackWebhook]
hooks.map ((url) ->
_data = _.extend {}, options.extra, data
# You can define your own parsing function (for example to return attachemnts)
parseFn = options.rule.fn || options.parseFn || (ops) -> {text : (if options.prefix then options.prefix + " - " else "") + (options.text + "") }
_data = parseFn (_data)
slackRequest url, _data
)
#send a notification according to the config
notify = (options) ->
if config.toEmail
sendEmail options
if config.slackWebhook
sendSlack options
#send notification that
notifySuccess = (rule, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Your condition was matched at "+rule.url # plaintext body
#send notification that
notifyError = (rule, error, response, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Error on #{ rule.url }\nError: #{ error }\nResponse code: #{ response && response.statusCode }\nContent: #{ body }"
#Rule grammar. You can add here new rules or etent what you have already.
whenRuleMap = [
{type: 'exist', f: (whenRule, body) -> return body.indexOf(whenRule) >= 0 }
{type: 'notExist', f: (whenRule, body) -> return body.indexOf(whenRule) < 0 }
{type: 'regExpMatch', f: (whenRule, body) -> return body.match(whenRule) }
]
#Check the "when" rules
checkWhenRules = (rule, body) ->
w = rule.when
if not w
logger.error "you need a when rule"
return
if _.isArray w
#currentlyImplementing OR logic (one of the "when" is true => notifySuccess)
#It may be rearchitected to have both OR and AND logic
for whenRule in w
found = false
for wr in whenRuleMap
if whenRule[wr.type]
found = true
logger.debug wr.type, whenRule[wr.type]
if wr.f(whenRule[wr.type], body)
notifySuccess(rule, body)
return
else
logger.debug wr.type + " not matched"
if not found then logger.warn "Unknown 'when' rule for url", rule.url, " The only known rules are in whenRuleMap"
else if _.isFunction w
logger.debug "Checking function result"
if w(body, rule)
notifySuccess(rule, body)
return
else
logger.debug "function returned falsy"
#request the HTML and parse it once it is received
getHTMLAndCheckWhenRules = (rule) ->
url = rule.url
options = {
'method': 'GET',
'uri': url,
}
logger.debug "Retriving url:", url
request options, (error, response, body) ->
if !error && response.statusCode == 200
checkWhenRules rule, body
else if error
logger.warn "error: #{error}".red
if config.notifyErrors then notifyError rule, error, response, body
else
logger.warn ("Response code: " + response.statusCode + "\nContent: " + body).red
if config.notifyErrors then notifyError rule, error, response, body
#Start monitoring the rules at specific intervals (default 1h)
monitorRule = (rule) ->
do (rule) ->
often = rule.frequency || 60*60*1000
logger.info "Every ",often / 1000," sec, I will monitor rule", rule
rule.timerID = setInterval ->
getHTMLAndCheckWhenRules(rule)
, often #defalt every 1 hour
getHTMLAndCheckWhenRules(rule)
#Is any rule defined?
if not config.rules or config.rules.length == 0
logger.error "No rules to track".error
process.exit(-1);
#Check all the rules
for rule in config.rules
if not rule.url
logger.error "Missing URL".error, rule
process.exit(-1);
monitorRule rule
#In case we want to provide a web interface to this puppy... otherwise we can delete this
express = require('express')
app = express()
app.use(express.logger())
app.use(express.bodyParser())
app.use("/static", express["static"](__dirname + '/styles'))
#views
app.set('views', __dirname + '/views')
app.engine('.html', require('ejs').__express)
app.set('view engine', 'ejs') #Set auto extension to .ejs
#test please!
app.get '/test', (req, res) ->
res.send("Hello world!");
#listen on port 3000 for localhost or whatever for heroku deploy
port = process.env.PORT || config.port || 3000
app.listen port, () ->
logger.log "Listening on " + port
| 202263 | colors = require 'colors'
winston = require 'winston'
request = require 'request'
_ = require 'underscore'
nodemailer = require 'nodemailer'
request = require 'request'
#We may want to parse the HTML with cheerio eventually, so far I do not need it
#cheerio = require 'cheerio'
#Do we want to dump the html on disk? Maybe later...
#fs = require 'fs'
#Load config.js
try
config = require './config'
catch e
logger.error "Problem reading config.js: ", e.stack || e
config = {};
#Winston Logger rocks baby!
logger = new winston.Logger {
transports: [
new winston.transports.Console({
level : config.logLevel || 'info'
colorize: true
timestamp: true
#Some options that may be useful later
#handleExceptions: true,
#json: true
})
]
exitOnError: true
}
# Send an email using Nodemailer https://github.com/andris9/Nodemailer
# It expects that config.emailServer and config.toEmail are defined (See config.js.template
# You should define at least "subject", and "text". "html" is optional
sendEmail = (options) ->
options.subject = options.rule.url+" is ready!"
emailServerOpt = config.emailServer
#create reusable transport method (opens pool of SMTP connections)
transport = nodemailer.createTransport emailServerOpt.type, emailServerOpt.parameters
#setup e-mail data with unicode symbols
mailOptions = _.extend {}, {
from: config.fromEmail || "Node Notifier ✔ <<EMAIL>>" # sender address
to: config.toEmail # list of receivers comma separated
#subject: "Your subject" # Subject line
#text: "Your text" # plaintext body
#You can add "html" to specify the HTML body
}, options
#send mail with defined transport object
transport.sendMail mailOptions, (error, response) ->
if (error)
logger.warn(error);
else
logger.info("Message sent: " + response.message);
# if you don't want to use this transport object anymore, uncomment following line
transport.close(); # shut down the connection pool, no more messages
slackRequest = (url, data, done) ->
if !url
logger.error('No URL')
return false
if !_.isFunction(done)
done = () -> {}
request.post url, {
form:
payload: JSON.stringify(data)
}, (err, response) ->
if err
logger.info "slackRequest : Error sending message"
return done(err)
if response.body isnt 'ok'
logger.info "slackRequest : Error sending message"
return done(new Error(response.body))
logger.info "slackRequest : Message sent", data
done()
sendSlack = (options) ->
return if !config.slackWebhook
options = _.extend {}, options, config.slackOpts
data = {}
logger.info "sendSlack : Sending message", data
hooks = if _.isArray(config.slackWebhook) then config.slackWebhook else [config.slackWebhook]
hooks.map ((url) ->
_data = _.extend {}, options.extra, data
# You can define your own parsing function (for example to return attachemnts)
parseFn = options.rule.fn || options.parseFn || (ops) -> {text : (if options.prefix then options.prefix + " - " else "") + (options.text + "") }
_data = parseFn (_data)
slackRequest url, _data
)
#send a notification according to the config
notify = (options) ->
if config.toEmail
sendEmail options
if config.slackWebhook
sendSlack options
#send notification that
notifySuccess = (rule, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Your condition was matched at "+rule.url # plaintext body
#send notification that
notifyError = (rule, error, response, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Error on #{ rule.url }\nError: #{ error }\nResponse code: #{ response && response.statusCode }\nContent: #{ body }"
#Rule grammar. You can add here new rules or etent what you have already.
whenRuleMap = [
{type: 'exist', f: (whenRule, body) -> return body.indexOf(whenRule) >= 0 }
{type: 'notExist', f: (whenRule, body) -> return body.indexOf(whenRule) < 0 }
{type: 'regExpMatch', f: (whenRule, body) -> return body.match(whenRule) }
]
#Check the "when" rules
checkWhenRules = (rule, body) ->
w = rule.when
if not w
logger.error "you need a when rule"
return
if _.isArray w
#currentlyImplementing OR logic (one of the "when" is true => notifySuccess)
#It may be rearchitected to have both OR and AND logic
for whenRule in w
found = false
for wr in whenRuleMap
if whenRule[wr.type]
found = true
logger.debug wr.type, whenRule[wr.type]
if wr.f(whenRule[wr.type], body)
notifySuccess(rule, body)
return
else
logger.debug wr.type + " not matched"
if not found then logger.warn "Unknown 'when' rule for url", rule.url, " The only known rules are in whenRuleMap"
else if _.isFunction w
logger.debug "Checking function result"
if w(body, rule)
notifySuccess(rule, body)
return
else
logger.debug "function returned falsy"
#request the HTML and parse it once it is received
getHTMLAndCheckWhenRules = (rule) ->
url = rule.url
options = {
'method': 'GET',
'uri': url,
}
logger.debug "Retriving url:", url
request options, (error, response, body) ->
if !error && response.statusCode == 200
checkWhenRules rule, body
else if error
logger.warn "error: #{error}".red
if config.notifyErrors then notifyError rule, error, response, body
else
logger.warn ("Response code: " + response.statusCode + "\nContent: " + body).red
if config.notifyErrors then notifyError rule, error, response, body
#Start monitoring the rules at specific intervals (default 1h)
monitorRule = (rule) ->
do (rule) ->
often = rule.frequency || 60*60*1000
logger.info "Every ",often / 1000," sec, I will monitor rule", rule
rule.timerID = setInterval ->
getHTMLAndCheckWhenRules(rule)
, often #defalt every 1 hour
getHTMLAndCheckWhenRules(rule)
#Is any rule defined?
if not config.rules or config.rules.length == 0
logger.error "No rules to track".error
process.exit(-1);
#Check all the rules
for rule in config.rules
if not rule.url
logger.error "Missing URL".error, rule
process.exit(-1);
monitorRule rule
#In case we want to provide a web interface to this puppy... otherwise we can delete this
express = require('express')
app = express()
app.use(express.logger())
app.use(express.bodyParser())
app.use("/static", express["static"](__dirname + '/styles'))
#views
app.set('views', __dirname + '/views')
app.engine('.html', require('ejs').__express)
app.set('view engine', 'ejs') #Set auto extension to .ejs
#test please!
app.get '/test', (req, res) ->
res.send("Hello world!");
#listen on port 3000 for localhost or whatever for heroku deploy
port = process.env.PORT || config.port || 3000
app.listen port, () ->
logger.log "Listening on " + port
| true | colors = require 'colors'
winston = require 'winston'
request = require 'request'
_ = require 'underscore'
nodemailer = require 'nodemailer'
request = require 'request'
#We may want to parse the HTML with cheerio eventually, so far I do not need it
#cheerio = require 'cheerio'
#Do we want to dump the html on disk? Maybe later...
#fs = require 'fs'
#Load config.js
try
config = require './config'
catch e
logger.error "Problem reading config.js: ", e.stack || e
config = {};
#Winston Logger rocks baby!
logger = new winston.Logger {
transports: [
new winston.transports.Console({
level : config.logLevel || 'info'
colorize: true
timestamp: true
#Some options that may be useful later
#handleExceptions: true,
#json: true
})
]
exitOnError: true
}
# Send an email using Nodemailer https://github.com/andris9/Nodemailer
# It expects that config.emailServer and config.toEmail are defined (See config.js.template
# You should define at least "subject", and "text". "html" is optional
sendEmail = (options) ->
options.subject = options.rule.url+" is ready!"
emailServerOpt = config.emailServer
#create reusable transport method (opens pool of SMTP connections)
transport = nodemailer.createTransport emailServerOpt.type, emailServerOpt.parameters
#setup e-mail data with unicode symbols
mailOptions = _.extend {}, {
from: config.fromEmail || "Node Notifier ✔ <PI:EMAIL:<EMAIL>END_PI>" # sender address
to: config.toEmail # list of receivers comma separated
#subject: "Your subject" # Subject line
#text: "Your text" # plaintext body
#You can add "html" to specify the HTML body
}, options
#send mail with defined transport object
transport.sendMail mailOptions, (error, response) ->
if (error)
logger.warn(error);
else
logger.info("Message sent: " + response.message);
# if you don't want to use this transport object anymore, uncomment following line
transport.close(); # shut down the connection pool, no more messages
slackRequest = (url, data, done) ->
if !url
logger.error('No URL')
return false
if !_.isFunction(done)
done = () -> {}
request.post url, {
form:
payload: JSON.stringify(data)
}, (err, response) ->
if err
logger.info "slackRequest : Error sending message"
return done(err)
if response.body isnt 'ok'
logger.info "slackRequest : Error sending message"
return done(new Error(response.body))
logger.info "slackRequest : Message sent", data
done()
sendSlack = (options) ->
return if !config.slackWebhook
options = _.extend {}, options, config.slackOpts
data = {}
logger.info "sendSlack : Sending message", data
hooks = if _.isArray(config.slackWebhook) then config.slackWebhook else [config.slackWebhook]
hooks.map ((url) ->
_data = _.extend {}, options.extra, data
# You can define your own parsing function (for example to return attachemnts)
parseFn = options.rule.fn || options.parseFn || (ops) -> {text : (if options.prefix then options.prefix + " - " else "") + (options.text + "") }
_data = parseFn (_data)
slackRequest url, _data
)
#send a notification according to the config
notify = (options) ->
if config.toEmail
sendEmail options
if config.slackWebhook
sendSlack options
#send notification that
notifySuccess = (rule, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Your condition was matched at "+rule.url # plaintext body
#send notification that
notifyError = (rule, error, response, body) ->
#So far only notification through email is implemented
notify
rule: rule
text: "Error on #{ rule.url }\nError: #{ error }\nResponse code: #{ response && response.statusCode }\nContent: #{ body }"
#Rule grammar. You can add here new rules or etent what you have already.
whenRuleMap = [
{type: 'exist', f: (whenRule, body) -> return body.indexOf(whenRule) >= 0 }
{type: 'notExist', f: (whenRule, body) -> return body.indexOf(whenRule) < 0 }
{type: 'regExpMatch', f: (whenRule, body) -> return body.match(whenRule) }
]
#Check the "when" rules
checkWhenRules = (rule, body) ->
w = rule.when
if not w
logger.error "you need a when rule"
return
if _.isArray w
#currentlyImplementing OR logic (one of the "when" is true => notifySuccess)
#It may be rearchitected to have both OR and AND logic
for whenRule in w
found = false
for wr in whenRuleMap
if whenRule[wr.type]
found = true
logger.debug wr.type, whenRule[wr.type]
if wr.f(whenRule[wr.type], body)
notifySuccess(rule, body)
return
else
logger.debug wr.type + " not matched"
if not found then logger.warn "Unknown 'when' rule for url", rule.url, " The only known rules are in whenRuleMap"
else if _.isFunction w
logger.debug "Checking function result"
if w(body, rule)
notifySuccess(rule, body)
return
else
logger.debug "function returned falsy"
#request the HTML and parse it once it is received
getHTMLAndCheckWhenRules = (rule) ->
url = rule.url
options = {
'method': 'GET',
'uri': url,
}
logger.debug "Retriving url:", url
request options, (error, response, body) ->
if !error && response.statusCode == 200
checkWhenRules rule, body
else if error
logger.warn "error: #{error}".red
if config.notifyErrors then notifyError rule, error, response, body
else
logger.warn ("Response code: " + response.statusCode + "\nContent: " + body).red
if config.notifyErrors then notifyError rule, error, response, body
#Start monitoring the rules at specific intervals (default 1h)
monitorRule = (rule) ->
do (rule) ->
often = rule.frequency || 60*60*1000
logger.info "Every ",often / 1000," sec, I will monitor rule", rule
rule.timerID = setInterval ->
getHTMLAndCheckWhenRules(rule)
, often #defalt every 1 hour
getHTMLAndCheckWhenRules(rule)
#Is any rule defined?
if not config.rules or config.rules.length == 0
logger.error "No rules to track".error
process.exit(-1);
#Check all the rules
for rule in config.rules
if not rule.url
logger.error "Missing URL".error, rule
process.exit(-1);
monitorRule rule
#In case we want to provide a web interface to this puppy... otherwise we can delete this
express = require('express')
app = express()
app.use(express.logger())
app.use(express.bodyParser())
app.use("/static", express["static"](__dirname + '/styles'))
#views
app.set('views', __dirname + '/views')
app.engine('.html', require('ejs').__express)
app.set('view engine', 'ejs') #Set auto extension to .ejs
#test please!
app.get '/test', (req, res) ->
res.send("Hello world!");
#listen on port 3000 for localhost or whatever for heroku deploy
port = process.env.PORT || config.port || 3000
app.listen port, () ->
logger.log "Listening on " + port
|
[
{
"context": "me, lastname, position, bars} = member\n key = firstname+lastname\n\n BarList = for bar, i in bars\n ",
"end": 218,
"score": 0.8049129247665405,
"start": 209,
"tag": "KEY",
"value": "firstname"
},
{
"context": "e, position, bars} = member\n key = first... | app/view/main/members.cjsx | OOKB/contemporary | 0 | React = require 'react'
module.exports = React.createClass
render: ->
{members} = @props.data
MemberRows = for member, i in members
{firstname, lastname, position, bars} = member
key = firstname+lastname
BarList = for bar, i in bars
{name, url} = bar
<li key={name}>
<a href={url}>{name}</a>
</li>
<tr className="member" key={key}>
<td><p>
<span className="fname">{firstname}</span> <span className="lname">{lastname}</span>
</p></td>
<td><p>{position}</p></td>
<td><ul>
{BarList}
</ul></td></tr>
<section id="instagram">
<h3>Members</h3>
<table id="bbg">
<thead>
<tr>
<th className="views-align-left">Member</th>
<th></th>
<th className="views-align-left">Bar</th>
</tr>
</thead>
<tbody>
{MemberRows}
</tbody>
</table>
</section>
| 132971 | React = require 'react'
module.exports = React.createClass
render: ->
{members} = @props.data
MemberRows = for member, i in members
{firstname, lastname, position, bars} = member
key = <KEY>+<KEY>
BarList = for bar, i in bars
{name, url} = bar
<li key={name}>
<a href={url}>{name}</a>
</li>
<tr className="member" key={key}>
<td><p>
<span className="fname">{firstname}</span> <span className="lname">{lastname}</span>
</p></td>
<td><p>{position}</p></td>
<td><ul>
{BarList}
</ul></td></tr>
<section id="instagram">
<h3>Members</h3>
<table id="bbg">
<thead>
<tr>
<th className="views-align-left">Member</th>
<th></th>
<th className="views-align-left">Bar</th>
</tr>
</thead>
<tbody>
{MemberRows}
</tbody>
</table>
</section>
| true | React = require 'react'
module.exports = React.createClass
render: ->
{members} = @props.data
MemberRows = for member, i in members
{firstname, lastname, position, bars} = member
key = PI:KEY:<KEY>END_PI+PI:KEY:<KEY>END_PI
BarList = for bar, i in bars
{name, url} = bar
<li key={name}>
<a href={url}>{name}</a>
</li>
<tr className="member" key={key}>
<td><p>
<span className="fname">{firstname}</span> <span className="lname">{lastname}</span>
</p></td>
<td><p>{position}</p></td>
<td><ul>
{BarList}
</ul></td></tr>
<section id="instagram">
<h3>Members</h3>
<table id="bbg">
<thead>
<tr>
<th className="views-align-left">Member</th>
<th></th>
<th className="views-align-left">Bar</th>
</tr>
</thead>
<tbody>
{MemberRows}
</tbody>
</table>
</section>
|
[
{
"context": "to 'hubot'.\n#\n# Commands:\n# None\n#\n# Author:\n# Gavin Mogan <gavin@gavinmogan.com>\n\n'use strict'\n\nUrl = req",
"end": 210,
"score": 0.9998719096183777,
"start": 199,
"tag": "NAME",
"value": "Gavin Mogan"
},
{
"context": "# Commands:\n# None\n#\n# Author:... | src/scripts/hubot-brain-redis-hash.coffee | actionshrimp/hubot-brain-redis-hash | 0 | # Description:
# None
#
# Dependencies:
# "redis": "0.7.2"
#
# Configuration:
# REDISTOGO_URL
# REDIS_PREFIX - If not provided will default to 'hubot'.
#
# Commands:
# None
#
# Author:
# Gavin Mogan <gavin@gavinmogan.com>
'use strict'
Url = require "url"
Redis = require "redis"
# sets up hooks to persist the brain into redis.
module.exports = (robot) ->
robot.brain.redis_hash = {}
client = robot.brain.redis_hash.client = module.exports.createClient()
prefix = process.env.REDIS_PREFIX or 'hubot'
oldkeys = {}
client.on "error", (err) ->
robot.logger.error err
client.on "connect", ->
robot.logger.debug "Successfully connected to Redis"
client.hgetall "#{prefix}:brain", (err, reply) ->
if err
throw err
else if reply
robot.logger.info "Brain data retrieved from redis-brain storage"
results = {}
oldkeys = {}
for key in Object.keys(reply)
results[key] = JSON.parse(reply[key].toString())
oldkeys[key] = 1
robot.brain.mergeData results
else
robot.logger.info "Initializing new redis-brain storage"
robot.brain.mergeData {}
robot.logger.info "Enabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave true
# Prevent autosaves until connect has occured
robot.logger.info "Disabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave false
robot.brain.on 'save', (data = {}) ->
robot.logger.debug "Saving brain data"
multi = do client.multi
keys = Object.keys data
jsonified = {}
for key in keys
jsonified[key] = JSON.stringify data[key]
for key in oldkeys
if !jsonified[key]
multi.hdel "#{prefix}:brain", key
oldkeys = {}
for key in keys
if jsonified[key]?
oldkeys[key] = 1
multi.hset "#{prefix}:brain", key, jsonified[key]
multi.exec (err,replies) ->
robot.brain.emit 'done:save'
return
robot.brain.on 'close', ->
client.quit()
@
module.exports.createClient = () ->
info = Url.parse process.env.REDISTOGO_URL || process.env.BOXEN_REDIS_URL || 'redis://localhost:6379'
client = Redis.createClient(info.port, info.hostname)
if info.auth
client.auth info.auth.split(":")[1]
return client
| 95148 | # Description:
# None
#
# Dependencies:
# "redis": "0.7.2"
#
# Configuration:
# REDISTOGO_URL
# REDIS_PREFIX - If not provided will default to 'hubot'.
#
# Commands:
# None
#
# Author:
# <NAME> <<EMAIL>>
'use strict'
Url = require "url"
Redis = require "redis"
# sets up hooks to persist the brain into redis.
module.exports = (robot) ->
robot.brain.redis_hash = {}
client = robot.brain.redis_hash.client = module.exports.createClient()
prefix = process.env.REDIS_PREFIX or 'hubot'
oldkeys = {}
client.on "error", (err) ->
robot.logger.error err
client.on "connect", ->
robot.logger.debug "Successfully connected to Redis"
client.hgetall "#{prefix}:brain", (err, reply) ->
if err
throw err
else if reply
robot.logger.info "Brain data retrieved from redis-brain storage"
results = {}
oldkeys = {}
for key in Object.keys(reply)
results[key] = JSON.parse(reply[key].toString())
oldkeys[key] = 1
robot.brain.mergeData results
else
robot.logger.info "Initializing new redis-brain storage"
robot.brain.mergeData {}
robot.logger.info "Enabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave true
# Prevent autosaves until connect has occured
robot.logger.info "Disabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave false
robot.brain.on 'save', (data = {}) ->
robot.logger.debug "Saving brain data"
multi = do client.multi
keys = Object.keys data
jsonified = {}
for key in keys
jsonified[key] = JSON.stringify data[key]
for key in oldkeys
if !jsonified[key]
multi.hdel "#{prefix}:brain", key
oldkeys = {}
for key in keys
if jsonified[key]?
oldkeys[key] = 1
multi.hset "#{prefix}:brain", key, jsonified[key]
multi.exec (err,replies) ->
robot.brain.emit 'done:save'
return
robot.brain.on 'close', ->
client.quit()
@
module.exports.createClient = () ->
info = Url.parse process.env.REDISTOGO_URL || process.env.BOXEN_REDIS_URL || 'redis://localhost:6379'
client = Redis.createClient(info.port, info.hostname)
if info.auth
client.auth info.auth.split(":")[1]
return client
| true | # Description:
# None
#
# Dependencies:
# "redis": "0.7.2"
#
# Configuration:
# REDISTOGO_URL
# REDIS_PREFIX - If not provided will default to 'hubot'.
#
# Commands:
# None
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
'use strict'
Url = require "url"
Redis = require "redis"
# sets up hooks to persist the brain into redis.
module.exports = (robot) ->
robot.brain.redis_hash = {}
client = robot.brain.redis_hash.client = module.exports.createClient()
prefix = process.env.REDIS_PREFIX or 'hubot'
oldkeys = {}
client.on "error", (err) ->
robot.logger.error err
client.on "connect", ->
robot.logger.debug "Successfully connected to Redis"
client.hgetall "#{prefix}:brain", (err, reply) ->
if err
throw err
else if reply
robot.logger.info "Brain data retrieved from redis-brain storage"
results = {}
oldkeys = {}
for key in Object.keys(reply)
results[key] = JSON.parse(reply[key].toString())
oldkeys[key] = 1
robot.brain.mergeData results
else
robot.logger.info "Initializing new redis-brain storage"
robot.brain.mergeData {}
robot.logger.info "Enabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave true
# Prevent autosaves until connect has occured
robot.logger.info "Disabling brain auto-saving"
if robot.brain.setAutoSave?
robot.brain.setAutoSave false
robot.brain.on 'save', (data = {}) ->
robot.logger.debug "Saving brain data"
multi = do client.multi
keys = Object.keys data
jsonified = {}
for key in keys
jsonified[key] = JSON.stringify data[key]
for key in oldkeys
if !jsonified[key]
multi.hdel "#{prefix}:brain", key
oldkeys = {}
for key in keys
if jsonified[key]?
oldkeys[key] = 1
multi.hset "#{prefix}:brain", key, jsonified[key]
multi.exec (err,replies) ->
robot.brain.emit 'done:save'
return
robot.brain.on 'close', ->
client.quit()
@
module.exports.createClient = () ->
info = Url.parse process.env.REDISTOGO_URL || process.env.BOXEN_REDIS_URL || 'redis://localhost:6379'
client = Redis.createClient(info.port, info.hostname)
if info.auth
client.auth info.auth.split(":")[1]
return client
|
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998878240585327,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/kanban/sortable.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/kanban/sortable.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaKanban")
#############################################################################
## Sortable Directive
#############################################################################
KanbanSortableDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
bindOnce $scope, "project", (project) ->
if not (project.my_permissions.indexOf("modify_us") > -1)
return
oldParentScope = null
newParentScope = null
itemEl = null
tdom = $el
deleteElement = (itemEl) ->
# Completelly remove item and its scope from dom
itemEl.scope().$destroy()
itemEl.off()
itemEl.remove()
tdom.sortable({
handle: ".kanban-task-inner"
dropOnEmpty: true
connectWith: ".kanban-uses-box"
revert: 400
})
tdom.on "sortstop", (event, ui) ->
parentEl = ui.item.parent()
itemEl = ui.item
itemUs = itemEl.scope().us
itemIndex = itemEl.index()
newParentScope = parentEl.scope()
newStatusId = newParentScope.s.id
oldStatusId = oldParentScope.s.id
if newStatusId != oldStatusId
deleteElement(itemEl)
$scope.$apply ->
$rootscope.$broadcast("kanban:us:move", itemUs, newStatusId, itemIndex)
ui.item.find('a').removeClass('noclick')
tdom.on "sortstart", (event, ui) ->
oldParentScope = ui.item.parent().scope()
ui.item.find('a').addClass('noclick')
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgKanbanSortable", [
"$tgRepo",
"$tgResources",
"$rootScope",
KanbanSortableDirective
])
| 36628 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/kanban/sortable.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaKanban")
#############################################################################
## Sortable Directive
#############################################################################
KanbanSortableDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
bindOnce $scope, "project", (project) ->
if not (project.my_permissions.indexOf("modify_us") > -1)
return
oldParentScope = null
newParentScope = null
itemEl = null
tdom = $el
deleteElement = (itemEl) ->
# Completelly remove item and its scope from dom
itemEl.scope().$destroy()
itemEl.off()
itemEl.remove()
tdom.sortable({
handle: ".kanban-task-inner"
dropOnEmpty: true
connectWith: ".kanban-uses-box"
revert: 400
})
tdom.on "sortstop", (event, ui) ->
parentEl = ui.item.parent()
itemEl = ui.item
itemUs = itemEl.scope().us
itemIndex = itemEl.index()
newParentScope = parentEl.scope()
newStatusId = newParentScope.s.id
oldStatusId = oldParentScope.s.id
if newStatusId != oldStatusId
deleteElement(itemEl)
$scope.$apply ->
$rootscope.$broadcast("kanban:us:move", itemUs, newStatusId, itemIndex)
ui.item.find('a').removeClass('noclick')
tdom.on "sortstart", (event, ui) ->
oldParentScope = ui.item.parent().scope()
ui.item.find('a').addClass('noclick')
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgKanbanSortable", [
"$tgRepo",
"$tgResources",
"$rootScope",
KanbanSortableDirective
])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/kanban/sortable.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaKanban")
#############################################################################
## Sortable Directive
#############################################################################
KanbanSortableDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
bindOnce $scope, "project", (project) ->
if not (project.my_permissions.indexOf("modify_us") > -1)
return
oldParentScope = null
newParentScope = null
itemEl = null
tdom = $el
deleteElement = (itemEl) ->
# Completelly remove item and its scope from dom
itemEl.scope().$destroy()
itemEl.off()
itemEl.remove()
tdom.sortable({
handle: ".kanban-task-inner"
dropOnEmpty: true
connectWith: ".kanban-uses-box"
revert: 400
})
tdom.on "sortstop", (event, ui) ->
parentEl = ui.item.parent()
itemEl = ui.item
itemUs = itemEl.scope().us
itemIndex = itemEl.index()
newParentScope = parentEl.scope()
newStatusId = newParentScope.s.id
oldStatusId = oldParentScope.s.id
if newStatusId != oldStatusId
deleteElement(itemEl)
$scope.$apply ->
$rootscope.$broadcast("kanban:us:move", itemUs, newStatusId, itemIndex)
ui.item.find('a').removeClass('noclick')
tdom.on "sortstart", (event, ui) ->
oldParentScope = ui.item.parent().scope()
ui.item.find('a').addClass('noclick')
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgKanbanSortable", [
"$tgRepo",
"$tgResources",
"$rootScope",
KanbanSortableDirective
])
|
[
{
"context": "ts = ()->\n method = {}\n\n method.webhookToken = \"tLK3w8TgCnbeLixtqXqKpqDG\"\n method.token = \"SYB244fFe6JePkdvBqHDgSzs\"\n me",
"end": 93,
"score": 0.8627226948738098,
"start": 69,
"tag": "KEY",
"value": "tLK3w8TgCnbeLixtqXqKpqDG"
},
{
"context": "en = \"tLK3w8T... | config/kr.coffee | pcruise/peoply-slackbot | 0 | #한국 슬랙
module.exports = ()->
method = {}
method.webhookToken = "tLK3w8TgCnbeLixtqXqKpqDG"
method.token = "SYB244fFe6JePkdvBqHDgSzs"
method.parse_app_id = 'NAllo4M9E53cRyp6SGtHVQchPJmYbrHdA5Iz9Anq'
method.parse_app_key = 'BQiD4TQOl1tC0qCemsFyRxN7DkecFRE2RuLnJRGd'
method.domain = "peoply"
method.bot_name = "PeoplyBot"
method.auto_msg =
wait: '안녕하세요! 컨시어지를 찾아주셔서 감사합니다. 현재 컨시어지 마스터님과 연결중이니 잠시만 기다려주세요.'
timeout: '안녕하세요! 현재 컨시어지는 매일 08:00 ~ 02:00 에 만나실 수 있습니다. 입력하신 메시지는 컨시어지 마스터에게 전달이 되었으니 내일 오전에 다시 연락 드리겠습니다 :)'
return method | 64824 | #한국 슬랙
module.exports = ()->
method = {}
method.webhookToken = "<KEY>"
method.token = "<KEY>"
method.parse_app_id = 'NAllo4M9E53cRyp6SGtHVQchPJmYbrHdA5Iz9Anq'
method.parse_app_key = '<KEY>'
method.domain = "peoply"
method.bot_name = "PeoplyBot"
method.auto_msg =
wait: '안녕하세요! 컨시어지를 찾아주셔서 감사합니다. 현재 컨시어지 마스터님과 연결중이니 잠시만 기다려주세요.'
timeout: '안녕하세요! 현재 컨시어지는 매일 08:00 ~ 02:00 에 만나실 수 있습니다. 입력하신 메시지는 컨시어지 마스터에게 전달이 되었으니 내일 오전에 다시 연락 드리겠습니다 :)'
return method | true | #한국 슬랙
module.exports = ()->
method = {}
method.webhookToken = "PI:KEY:<KEY>END_PI"
method.token = "PI:KEY:<KEY>END_PI"
method.parse_app_id = 'NAllo4M9E53cRyp6SGtHVQchPJmYbrHdA5Iz9Anq'
method.parse_app_key = 'PI:KEY:<KEY>END_PI'
method.domain = "peoply"
method.bot_name = "PeoplyBot"
method.auto_msg =
wait: '안녕하세요! 컨시어지를 찾아주셔서 감사합니다. 현재 컨시어지 마스터님과 연결중이니 잠시만 기다려주세요.'
timeout: '안녕하세요! 현재 컨시어지는 매일 08:00 ~ 02:00 에 만나실 수 있습니다. 입력하신 메시지는 컨시어지 마스터에게 전달이 되었으니 내일 오전에 다시 연락 드리겠습니다 :)'
return method |
[
{
"context": " 'адреса', 'адресов']\n 'person': ['человек', 'человека', 'человек']\n 'ton': [",
"end": 1196,
"score": 0.9690707921981812,
"start": 1189,
"tag": "NAME",
"value": "человек"
},
{
"context": "'адресов']\n 'person': ['человек', ... | resources/assets/coffee/directives/plural.coffee | maxflex/tweb | 0 | angular.module 'App'
.directive 'plural', ->
restrict: 'E'
scope:
count: '=' # кол-во
type: '@' # тип plural age | student | ...
noneText: '@' # текст, если кол-во равно нулю
templateUrl: '/directives/plural'
controller: ($scope, $element, $attrs, $timeout) ->
$scope.textOnly = $attrs.hasOwnProperty('textOnly')
$scope.hideZero = $attrs.hasOwnProperty('hideZero')
$scope.when =
'age': ['год', 'года', 'лет']
'student': ['ученик', 'ученика', 'учеников']
'minute': ['минуту', 'минуты', 'минут']
'hour': ['час', 'часа', 'часов']
'day': ['день', 'дня', 'дней']
'rubbles': ['рубль', 'рубля', 'рублей']
'client': ['клиент', 'клиента', 'клиентов']
'mark': ['оценки', 'оценок', 'оценок']
'review': ['отзыв', 'отзыва', 'отзывов']
'request': ['заявка', 'заявки', 'заявок']
'profile': ['анкета', 'анкеты', 'анкет']
'address': ['адрес', 'адреса', 'адресов']
'person': ['человек', 'человека', 'человек']
'ton': ['тонна', 'тонны', 'тонн']
'yacht': ['яхта', 'яхты', 'яхт']
'photo': ['фото', 'фотографии', 'фотографий']
| 29531 | angular.module 'App'
.directive 'plural', ->
restrict: 'E'
scope:
count: '=' # кол-во
type: '@' # тип plural age | student | ...
noneText: '@' # текст, если кол-во равно нулю
templateUrl: '/directives/plural'
controller: ($scope, $element, $attrs, $timeout) ->
$scope.textOnly = $attrs.hasOwnProperty('textOnly')
$scope.hideZero = $attrs.hasOwnProperty('hideZero')
$scope.when =
'age': ['год', 'года', 'лет']
'student': ['ученик', 'ученика', 'учеников']
'minute': ['минуту', 'минуты', 'минут']
'hour': ['час', 'часа', 'часов']
'day': ['день', 'дня', 'дней']
'rubbles': ['рубль', 'рубля', 'рублей']
'client': ['клиент', 'клиента', 'клиентов']
'mark': ['оценки', 'оценок', 'оценок']
'review': ['отзыв', 'отзыва', 'отзывов']
'request': ['заявка', 'заявки', 'заявок']
'profile': ['анкета', 'анкеты', 'анкет']
'address': ['адрес', 'адреса', 'адресов']
'person': ['<NAME>', '<NAME>', 'человек']
'ton': ['тонна', 'тонны', 'тонн']
'yacht': ['яхта', 'яхты', 'яхт']
'photo': ['фото', 'фотографии', 'фотографий']
| true | angular.module 'App'
.directive 'plural', ->
restrict: 'E'
scope:
count: '=' # кол-во
type: '@' # тип plural age | student | ...
noneText: '@' # текст, если кол-во равно нулю
templateUrl: '/directives/plural'
controller: ($scope, $element, $attrs, $timeout) ->
$scope.textOnly = $attrs.hasOwnProperty('textOnly')
$scope.hideZero = $attrs.hasOwnProperty('hideZero')
$scope.when =
'age': ['год', 'года', 'лет']
'student': ['ученик', 'ученика', 'учеников']
'minute': ['минуту', 'минуты', 'минут']
'hour': ['час', 'часа', 'часов']
'day': ['день', 'дня', 'дней']
'rubbles': ['рубль', 'рубля', 'рублей']
'client': ['клиент', 'клиента', 'клиентов']
'mark': ['оценки', 'оценок', 'оценок']
'review': ['отзыв', 'отзыва', 'отзывов']
'request': ['заявка', 'заявки', 'заявок']
'profile': ['анкета', 'анкеты', 'анкет']
'address': ['адрес', 'адреса', 'адресов']
'person': ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'человек']
'ton': ['тонна', 'тонны', 'тонн']
'yacht': ['яхта', 'яхты', 'яхт']
'photo': ['фото', 'фотографии', 'фотографий']
|
[
{
"context": "on sun\nAll now covered with snow\n\"\"\",\n \"\"\"\nCopley brought me to a monument\nQuiet before the crunch ",
"end": 1844,
"score": 0.8701058030128479,
"start": 1838,
"tag": "NAME",
"value": "Copley"
}
] | scripts/poetry.coffee | jsullivan3/pinkybot | 1 | # Description:
# Poems and whimsical retorts
#
# Commands:
# hubot read me a poem - reads a random poem from the hit game Interstate 76
poetry = [ """
Looking out the window of your room onto a wet rainy day
Main street under a slate gray afternoon sky
The light on your face is soft and dim under the lace curtain
And the streets are empty
In the distance, there is a flash and a rumble
Clouds sail the sky like giant wooden ships
On a blackened evergreen sea
Capped with foam
""",
"""
I'm a storm torrent across a slate-gray sea
I rush in billowed reflections a fast, fast dark sky over an Edinburgh's meadow's wet
I bolt white high through snowfall cold
I am lightning in the night
I sprint like fire across a match head
And leap across lakes of dream-stuff
Over ancient walls
Past armies fast as fast is
Faster than quicksilver can fall into the sun
I, bounding, prance unstoppable to you
My all
My everything dream
""",
"""
It's a high pitched sound
Hot rubber eternally pressing against a blackened pavement
A wheel is forever
A car is infinity times four
""",
"""
From where I lie
The oceans are deep and dry
Empty
The sky is black smoke bearing winter's frozen gifts
It will snow in this land for a thousand years
And I will sleep under it...forever
""",
"""
My dream
It takes place in the white room, in back
The plaster walls echo sounds
The brown wood floor is cold and solid beneath my brown, bare feet
This place was a nursery before
Now it is empty
Save for the hollow sound of my voice
""",
"""
This window above the Charles
Wire embedded in cold frames the world
Across white space to the frozen shore
I see through curls and eddies of falling snow
The once green field
And a birthday on the grass
A party for three in the Boston sun
All now covered with snow
""",
"""
Copley brought me to a monument
Quiet before the crunch of solitary footfall through ice
An obelisk stands in the winter city
Its relief tells of a death and justification
The precipitation of war
And my own memories
""",
"""
I'm silver smooth
Bathed ten times a second in an aerosol fire
Five thousand degrees in here
I course with electricity from my feet to my tongue
Where I vomit a torque-delivering spark
""",
"""
It's nicked at the edges
And leans backwards, almost reclining
Grass grows in tufts near where it enters the earth
Its words are worn with time
And its stained face is drawn long with wear
""",
"""
It's malleable, my design
Things just bolt on here and there
Real clean scraped face
A new gasket fitted and...
Tightened and...
I'm done.
""",
"""
She's my girl
Pearl white, slick and sexy
Never complains, always faithful
She cuts the air like a charging buffalo
In her arms, it's quiet
Her engine whispers to me:
"It's gonna be just fine"
""",
"""
They twist like quad-coiled vipers
Feeding on combustion's waste
Black as ink and hot as Hades they join below
Eternally in shadow, unless of course, I roll
They belt a rumbling and vibrate fear
Into the bones of my foe
""",
"""
It's not a happy place, between the dusk and the dawn
Deep below the well-lit and open spaces
I wait under the under
For them to come and rip me asunder
Tearing my core until morning
""",
"""
Glass, flat and forever
It stretches out and never stops
Unless it finds the hills whose lines rise to mountain peaks
Far as far can be
""",
"""
There is a breeze out here
That filters through the scrub
Over hills and down through long dry riverbeds
Across the Texas blacktop
It cools the skin and brings the most subtle song in the world
To the ears of those who listen
"""
]
module.exports = (robot) ->
robot.respond /(read me)|(how a?bout) a poem/, (msg) ->
msg.send msg.random poetry
| 110359 | # Description:
# Poems and whimsical retorts
#
# Commands:
# hubot read me a poem - reads a random poem from the hit game Interstate 76
poetry = [ """
Looking out the window of your room onto a wet rainy day
Main street under a slate gray afternoon sky
The light on your face is soft and dim under the lace curtain
And the streets are empty
In the distance, there is a flash and a rumble
Clouds sail the sky like giant wooden ships
On a blackened evergreen sea
Capped with foam
""",
"""
I'm a storm torrent across a slate-gray sea
I rush in billowed reflections a fast, fast dark sky over an Edinburgh's meadow's wet
I bolt white high through snowfall cold
I am lightning in the night
I sprint like fire across a match head
And leap across lakes of dream-stuff
Over ancient walls
Past armies fast as fast is
Faster than quicksilver can fall into the sun
I, bounding, prance unstoppable to you
My all
My everything dream
""",
"""
It's a high pitched sound
Hot rubber eternally pressing against a blackened pavement
A wheel is forever
A car is infinity times four
""",
"""
From where I lie
The oceans are deep and dry
Empty
The sky is black smoke bearing winter's frozen gifts
It will snow in this land for a thousand years
And I will sleep under it...forever
""",
"""
My dream
It takes place in the white room, in back
The plaster walls echo sounds
The brown wood floor is cold and solid beneath my brown, bare feet
This place was a nursery before
Now it is empty
Save for the hollow sound of my voice
""",
"""
This window above the Charles
Wire embedded in cold frames the world
Across white space to the frozen shore
I see through curls and eddies of falling snow
The once green field
And a birthday on the grass
A party for three in the Boston sun
All now covered with snow
""",
"""
<NAME> brought me to a monument
Quiet before the crunch of solitary footfall through ice
An obelisk stands in the winter city
Its relief tells of a death and justification
The precipitation of war
And my own memories
""",
"""
I'm silver smooth
Bathed ten times a second in an aerosol fire
Five thousand degrees in here
I course with electricity from my feet to my tongue
Where I vomit a torque-delivering spark
""",
"""
It's nicked at the edges
And leans backwards, almost reclining
Grass grows in tufts near where it enters the earth
Its words are worn with time
And its stained face is drawn long with wear
""",
"""
It's malleable, my design
Things just bolt on here and there
Real clean scraped face
A new gasket fitted and...
Tightened and...
I'm done.
""",
"""
She's my girl
Pearl white, slick and sexy
Never complains, always faithful
She cuts the air like a charging buffalo
In her arms, it's quiet
Her engine whispers to me:
"It's gonna be just fine"
""",
"""
They twist like quad-coiled vipers
Feeding on combustion's waste
Black as ink and hot as Hades they join below
Eternally in shadow, unless of course, I roll
They belt a rumbling and vibrate fear
Into the bones of my foe
""",
"""
It's not a happy place, between the dusk and the dawn
Deep below the well-lit and open spaces
I wait under the under
For them to come and rip me asunder
Tearing my core until morning
""",
"""
Glass, flat and forever
It stretches out and never stops
Unless it finds the hills whose lines rise to mountain peaks
Far as far can be
""",
"""
There is a breeze out here
That filters through the scrub
Over hills and down through long dry riverbeds
Across the Texas blacktop
It cools the skin and brings the most subtle song in the world
To the ears of those who listen
"""
]
module.exports = (robot) ->
robot.respond /(read me)|(how a?bout) a poem/, (msg) ->
msg.send msg.random poetry
| true | # Description:
# Poems and whimsical retorts
#
# Commands:
# hubot read me a poem - reads a random poem from the hit game Interstate 76
poetry = [ """
Looking out the window of your room onto a wet rainy day
Main street under a slate gray afternoon sky
The light on your face is soft and dim under the lace curtain
And the streets are empty
In the distance, there is a flash and a rumble
Clouds sail the sky like giant wooden ships
On a blackened evergreen sea
Capped with foam
""",
"""
I'm a storm torrent across a slate-gray sea
I rush in billowed reflections a fast, fast dark sky over an Edinburgh's meadow's wet
I bolt white high through snowfall cold
I am lightning in the night
I sprint like fire across a match head
And leap across lakes of dream-stuff
Over ancient walls
Past armies fast as fast is
Faster than quicksilver can fall into the sun
I, bounding, prance unstoppable to you
My all
My everything dream
""",
"""
It's a high pitched sound
Hot rubber eternally pressing against a blackened pavement
A wheel is forever
A car is infinity times four
""",
"""
From where I lie
The oceans are deep and dry
Empty
The sky is black smoke bearing winter's frozen gifts
It will snow in this land for a thousand years
And I will sleep under it...forever
""",
"""
My dream
It takes place in the white room, in back
The plaster walls echo sounds
The brown wood floor is cold and solid beneath my brown, bare feet
This place was a nursery before
Now it is empty
Save for the hollow sound of my voice
""",
"""
This window above the Charles
Wire embedded in cold frames the world
Across white space to the frozen shore
I see through curls and eddies of falling snow
The once green field
And a birthday on the grass
A party for three in the Boston sun
All now covered with snow
""",
"""
PI:NAME:<NAME>END_PI brought me to a monument
Quiet before the crunch of solitary footfall through ice
An obelisk stands in the winter city
Its relief tells of a death and justification
The precipitation of war
And my own memories
""",
"""
I'm silver smooth
Bathed ten times a second in an aerosol fire
Five thousand degrees in here
I course with electricity from my feet to my tongue
Where I vomit a torque-delivering spark
""",
"""
It's nicked at the edges
And leans backwards, almost reclining
Grass grows in tufts near where it enters the earth
Its words are worn with time
And its stained face is drawn long with wear
""",
"""
It's malleable, my design
Things just bolt on here and there
Real clean scraped face
A new gasket fitted and...
Tightened and...
I'm done.
""",
"""
She's my girl
Pearl white, slick and sexy
Never complains, always faithful
She cuts the air like a charging buffalo
In her arms, it's quiet
Her engine whispers to me:
"It's gonna be just fine"
""",
"""
They twist like quad-coiled vipers
Feeding on combustion's waste
Black as ink and hot as Hades they join below
Eternally in shadow, unless of course, I roll
They belt a rumbling and vibrate fear
Into the bones of my foe
""",
"""
It's not a happy place, between the dusk and the dawn
Deep below the well-lit and open spaces
I wait under the under
For them to come and rip me asunder
Tearing my core until morning
""",
"""
Glass, flat and forever
It stretches out and never stops
Unless it finds the hills whose lines rise to mountain peaks
Far as far can be
""",
"""
There is a breeze out here
That filters through the scrub
Over hills and down through long dry riverbeds
Across the Texas blacktop
It cools the skin and brings the most subtle song in the world
To the ears of those who listen
"""
]
module.exports = (robot) ->
robot.respond /(read me)|(how a?bout) a poem/, (msg) ->
msg.send msg.random poetry
|
[
{
"context": "new models.shares.Share()\n share.password = '' #req.body.password\n share.allowComments = ",
"end": 650,
"score": 0.9282909631729126,
"start": 650,
"tag": "PASSWORD",
"value": ""
},
{
"context": "odels.shares.Share()\n share.password = '' #req.body... | player/src/controllers/shares.coffee | setpixel/storyboard-fountain | 148 | require('string.prototype.endswith')
util = require('util')
_ = require('underscore')
#geoip = require('geoip-lite')
class NotFound extends Error
module.exports = {
initialize: (app) ->
models = require('../models')
helpers = require('../req_helpers')
fs = require('fs')
app.get '/shares/:key.json',
helpers.requireShare('key'),
(req, res) ->
{share} = req.current
res.json share
app.get '/shares/new',
(req, res) ->
res.render 'new_share'
app.post '/shares',
(req, res) ->
# create the db record
share = new models.shares.Share()
share.password = '' #req.body.password
share.allowComments = yes #req.body.allow_comments is '1'
await models.shares.save share, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
dataPath = process.env.DATA_PATH + '/' + share.key
imagesPath = process.env.DATA_PATH + '/' + share.key + '/images'
dataFile = dataPath + '/data.zip'
# create the data dir
await fs.mkdir dataPath, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
# if busboy doesn't detect a valid request
unless req.busboy
res.end(400)
return
req.pipe(req.busboy)
console.log('hwm', req.busboy.highWaterMark, 'fileHwm', req.busboy.fileHwm, )
req.busboy.on 'field', (fieldname, value) ->
console.log('field', fieldname, value)
req.busboy.on 'partsLimit', ->
console.log('partsLimit')
req.busboy.on 'filesLimit', ->
console.log('filesLimit')
req.busboy.on 'fieldsLimit', ->
console.log('fieldsLimit')
doneWithFile = no
# store the files
req.busboy.on 'file', (fieldname, file, filename, encoding, mimetype) ->
console.log('file', filename, encoding, mimetype)
file.pipe(fs.createWriteStream(dataFile))
# TODO: busboy.on 'field', ()
req.busboy.on 'error', (err) -> console.log(err)
req.busboy.on 'finish', ->
console.log('finish')
res.json {key: share.key}
console.log('doneWithFile', doneWithFile)
# unzip it
exec = require('child_process').exec
exec "cd #{dataPath} && unzip #{dataFile}", ->
}
| 186765 | require('string.prototype.endswith')
util = require('util')
_ = require('underscore')
#geoip = require('geoip-lite')
class NotFound extends Error
module.exports = {
initialize: (app) ->
models = require('../models')
helpers = require('../req_helpers')
fs = require('fs')
app.get '/shares/:key.json',
helpers.requireShare('key'),
(req, res) ->
{share} = req.current
res.json share
app.get '/shares/new',
(req, res) ->
res.render 'new_share'
app.post '/shares',
(req, res) ->
# create the db record
share = new models.shares.Share()
share.password =<PASSWORD> '' #<PASSWORD>
share.allowComments = yes #req.body.allow_comments is '1'
await models.shares.save share, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
dataPath = process.env.DATA_PATH + '/' + share.key
imagesPath = process.env.DATA_PATH + '/' + share.key + '/images'
dataFile = dataPath + '/data.zip'
# create the data dir
await fs.mkdir dataPath, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
# if busboy doesn't detect a valid request
unless req.busboy
res.end(400)
return
req.pipe(req.busboy)
console.log('hwm', req.busboy.highWaterMark, 'fileHwm', req.busboy.fileHwm, )
req.busboy.on 'field', (fieldname, value) ->
console.log('field', fieldname, value)
req.busboy.on 'partsLimit', ->
console.log('partsLimit')
req.busboy.on 'filesLimit', ->
console.log('filesLimit')
req.busboy.on 'fieldsLimit', ->
console.log('fieldsLimit')
doneWithFile = no
# store the files
req.busboy.on 'file', (fieldname, file, filename, encoding, mimetype) ->
console.log('file', filename, encoding, mimetype)
file.pipe(fs.createWriteStream(dataFile))
# TODO: busboy.on 'field', ()
req.busboy.on 'error', (err) -> console.log(err)
req.busboy.on 'finish', ->
console.log('finish')
res.json {key: share.key}
console.log('doneWithFile', doneWithFile)
# unzip it
exec = require('child_process').exec
exec "cd #{dataPath} && unzip #{dataFile}", ->
}
| true | require('string.prototype.endswith')
util = require('util')
_ = require('underscore')
#geoip = require('geoip-lite')
class NotFound extends Error
module.exports = {
initialize: (app) ->
models = require('../models')
helpers = require('../req_helpers')
fs = require('fs')
app.get '/shares/:key.json',
helpers.requireShare('key'),
(req, res) ->
{share} = req.current
res.json share
app.get '/shares/new',
(req, res) ->
res.render 'new_share'
app.post '/shares',
(req, res) ->
# create the db record
share = new models.shares.Share()
share.password =PI:PASSWORD:<PASSWORD>END_PI '' #PI:PASSWORD:<PASSWORD>END_PI
share.allowComments = yes #req.body.allow_comments is '1'
await models.shares.save share, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
dataPath = process.env.DATA_PATH + '/' + share.key
imagesPath = process.env.DATA_PATH + '/' + share.key + '/images'
dataFile = dataPath + '/data.zip'
# create the data dir
await fs.mkdir dataPath, defer(err)
console.log(err)
throw new helpers.SystemError(err) if err?
# if busboy doesn't detect a valid request
unless req.busboy
res.end(400)
return
req.pipe(req.busboy)
console.log('hwm', req.busboy.highWaterMark, 'fileHwm', req.busboy.fileHwm, )
req.busboy.on 'field', (fieldname, value) ->
console.log('field', fieldname, value)
req.busboy.on 'partsLimit', ->
console.log('partsLimit')
req.busboy.on 'filesLimit', ->
console.log('filesLimit')
req.busboy.on 'fieldsLimit', ->
console.log('fieldsLimit')
doneWithFile = no
# store the files
req.busboy.on 'file', (fieldname, file, filename, encoding, mimetype) ->
console.log('file', filename, encoding, mimetype)
file.pipe(fs.createWriteStream(dataFile))
# TODO: busboy.on 'field', ()
req.busboy.on 'error', (err) -> console.log(err)
req.busboy.on 'finish', ->
console.log('finish')
res.json {key: share.key}
console.log('doneWithFile', doneWithFile)
# unzip it
exec = require('child_process').exec
exec "cd #{dataPath} && unzip #{dataFile}", ->
}
|
[
{
"context": "quire '../payment'\n\n @bannedUserList = ['abrt', 'amykhailov', 'apache', 'about', 'visa', 'shared-',\n ",
"end": 1072,
"score": 0.9996464848518372,
"start": 1062,
"tag": "USERNAME",
"value": "amykhailov"
},
{
"context": ": no\n indexes :\n user... | workers/social/lib/social/models/user/index.coffee | ezgikaysi/koding | 1 | async = require 'async'
jraphical = require 'jraphical'
Regions = require 'koding-regions'
request = require 'request'
KONFIG = require 'koding-config-manager'
Flaggable = require '../../traits/flaggable'
KodingError = require '../../error'
emailsanitize = require './emailsanitize'
{ extend, uniq } = require 'underscore'
{ protocol, hostname } = KONFIG
module.exports = class JUser extends jraphical.Module
{ v4: createId } = require 'node-uuid'
{ Relationship } = jraphical
{ secure, signature } = require 'bongo'
JAccount = require '../account'
JSession = require '../session'
JInvitation = require '../invitation'
JName = require '../name'
JGroup = require '../group'
JLog = require '../log'
ComputeProvider = require '../computeproviders/computeprovider'
Tracker = require '../tracker'
Payment = require '../payment'
@bannedUserList = ['abrt', 'amykhailov', 'apache', 'about', 'visa', 'shared-',
'cthorn', 'daemon', 'dbus', 'dyasar', 'ec2-user', 'http',
'games', 'ggoksel', 'gopher', 'haldaemon', 'halt', 'mail',
'nfsnobody', 'nginx', 'nobody', 'node', 'operator', 'https',
'root', 'rpcuser', 'saslauth', 'shutdown', 'sinanlocal',
'sshd', 'sync', 'tcpdump', 'uucp', 'vcsa', 'zabbix',
'search', 'blog', 'activity', 'guest', 'credits', 'about',
'kodingen', 'alias', 'backup', 'bin', 'bind', 'daemon',
'Debian-exim', 'dhcp', 'drweb', 'games', 'gnats', 'klog',
'kluser', 'libuuid', 'list', 'mhandlers-user', 'more',
'mysql', 'nagios', 'news', 'nobody', 'popuser', 'postgres',
'proxy', 'psaadm', 'psaftp', 'qmaild', 'qmaill', 'qmailp',
'qmailq', 'qmailr', 'qmails', 'sshd', 'statd', 'sw-cp-server',
'sync', 'syslog', 'tomcat', 'tomcat55', 'uucp', 'what',
'www-data', 'fuck', 'porn', 'p0rn', 'porno', 'fucking',
'fucker', 'admin', 'postfix', 'puppet', 'main', 'invite',
'administrator', 'members', 'register', 'activate', 'shared',
'groups', 'blogs', 'forums', 'topics', 'develop', 'terminal',
'term', 'twitter', 'facebook', 'google', 'framework', 'kite',
'landing', 'hello', 'dev', 'sandbox', 'latest',
'all', 'channel', 'admins', 'group', 'team'
]
hashPassword = (value, salt) ->
require('crypto').createHash('sha1').update(salt + value).digest('hex')
createSalt = require 'hat'
rack = createSalt.rack 64
@share()
@trait __dirname, '../../traits/flaggable'
@getFlagRole = -> 'owner'
@set
softDelete : yes
broadcastable : no
indexes :
username : 'unique'
email : 'unique'
sanitizedEmail: ['unique', 'sparse']
'foreignAuth.github.foreignId' : 'ascending'
'foreignAuth.facebook.foreignId' : 'ascending'
'foreignAuth.google.foreignId' : 'ascending'
'foreignAuth.linkedin.foreignId' : 'ascending'
'foreignAuth.twitter.foreignId' : 'ascending'
sharedEvents :
# do not share any events
static : []
instance : []
sharedMethods :
# do not share any instance methods
# instances :
static :
login : (signature Object, Function)
whoami : (signature Function)
logout : (signature Function)
convert : (signature Object, Function)
fetchUser : (signature Function)
setSSHKeys : (signature [Object], Function)
getSSHKeys : (signature Function)
unregister : (signature String, Function)
verifyByPin : (signature Object, Function)
changeEmail : (signature Object, Function)
verifyPassword : (signature Object, Function)
emailAvailable : (signature String, Function)
changePassword : (signature String, Function)
usernameAvailable : (signature String, Function)
authenticateWithOauth : (signature Object, Function)
isRegistrationEnabled : (signature Function)
schema :
username :
type : String
validate : JName.validateName
set : (value) -> value.toLowerCase()
oldUsername : String
uid :
type : Number
set : Math.floor
email :
type : String
validate : JName.validateEmail
set : emailsanitize
sanitizedEmail:
type : String
validate : JName.validateEmail
set : (value) ->
return unless typeof value is 'string'
emailsanitize value, { excludeDots: yes, excludePlus: yes }
password : String
salt : String
twofactorkey : String
blockedUntil : Date
blockedReason : String
status :
type : String
enum : [
'invalid status type', [
'unconfirmed', 'confirmed', 'blocked', 'deleted'
]
]
default : 'unconfirmed'
passwordStatus:
type : String
enum : [
'invalid password status type', [
'needs reset', 'needs set', 'valid', 'autogenerated'
]
]
default : 'valid'
registeredAt :
type : Date
default : -> new Date
registeredFrom:
ip : String
country : String
region : String
lastLoginDate :
type : Date
default : -> new Date
# store fields for janitor worker. see go/src/koding/db/models/user.go for more details.
inactive : Object
# stores user preference for how often email should be sent.
# see go/src/koding/db/models/user.go for more details.
emailFrequency: Object
onlineStatus :
actual :
type : String
enum : ['invalid status', ['online', 'offline']]
default : 'online'
userPreference:
type : String
# enum : ['invalid status',['online','offline','away','busy']]
sshKeys :
type : Object
default : []
foreignAuth :
github :
foreignId : String
username : String
token : String
firstName : String
lastName : String
email : String
scope : String
facebook :
foreignId : String
username : String
token : String
linkedin :
foreignId : String
relationships :
ownAccount :
targetType : JAccount
as : 'owner'
sessions = {}
users = {}
guests = {}
@unregister = secure (client, toBeDeletedUsername, callback) ->
{ delegate } = client.connection
{ nickname } = delegate.profile
console.log "#{nickname} requested to delete: #{toBeDeletedUsername}"
# deleter should be registered one
if delegate.type is 'unregistered'
return callback new KodingError 'You are not registered!'
# only owner and the dummy admins can delete a user
unless toBeDeletedUsername is nickname or
delegate.can 'administer accounts'
return callback new KodingError 'You must confirm this action!'
username = @createGuestUsername()
# Adding -rm suffix to separate them from real guests
# -rm was intentional otherwise we are exceeding the max username length
username = "#{username}-rm"
# Why we do have such thing? ~ GG
email = "#{username}@koding.com"
@one { username: toBeDeletedUsername }, (err, user) ->
return callback err if err?
unless user
return callback new KodingError \
"User not found #{toBeDeletedUsername}"
userValues = {
email : email
sanitizedEmail : email
# here we have a trick, emailBeforeDeletion is not in the schema but we
# are setting it to the db. it is not in the schema because we dont want
# it to be seen in the codebase and it wont be mapped to a JUser
emailBeforeDeletion : user.email
status : 'deleted'
sshKeys : []
username : username
password : createId()
foreignAuth : {}
onlineStatus : 'offline'
registeredAt : new Date 0
lastLoginDate : new Date 0
passwordStatus : 'autogenerated'
emailFrequency : {}
}
modifier = { $set: userValues, $unset: { oldUsername: 1 } }
# update the user with empty data
user.update modifier, updateUnregisteredUserAccount({
user, username, toBeDeletedUsername, client
}, callback)
@isRegistrationEnabled = (callback) ->
JRegistrationPreferences = require '../registrationpreferences'
JRegistrationPreferences.one {}, (err, prefs) ->
callback err? or prefs?.isRegistrationEnabled or no
@authenticateClient: (clientId, callback) ->
logError = (message, rest...) ->
console.error "[JUser::authenticateClient] #{message}", rest...
logout = (reason, clientId, callback) =>
@logout clientId, (err) ->
logError reason, clientId
callback new KodingError reason
# Let's try to lookup provided session first
JSession.one { clientId }, (err, session) ->
if err
# This is a very rare state here
logError 'error finding session', { err, clientId }
callback new KodingError err
else unless session?
# We couldn't find the session with given token
# so we are creating a new one now.
JSession.createSession (err, { session, account }) ->
if err?
logError 'failed to create session', { err }
callback err
else
# Voila session created and sent back, scenario #1
callback null, { session, account }
else
# So we have a session, let's check it out if its a valid one
checkSessionValidity { session, logout, clientId }, callback
@getHash = getHash = (value) ->
require('crypto').createHash('md5').update(value.toLowerCase()).digest('hex')
@whoami = secure ({ connection:{ delegate } }, callback) -> callback null, delegate
@getBlockedMessage = (toDate) ->
return """
This account has been put on suspension due to a violation of our acceptable use policy. The ban will be in effect until <b>#{toDate}.</b><br><br>
If you have any questions, please email <a class="ban" href='mailto:ban@#{KONFIG.domains.mail}'>ban@#{KONFIG.domains.mail}</a> and allow 2-3 business days for a reply. Even though your account is banned, all your data is safe.<br><br>
Please note, repeated violations of our acceptable use policy will result in the permanent deletion of your account.<br><br>
Team Koding
"""
checkBlockedStatus = (user, callback) ->
return callback null if user.status isnt 'blocked'
if user.blockedUntil and user.blockedUntil > new Date
toDate = user.blockedUntil.toUTCString()
message = JUser.getBlockedMessage toDate
callback new KodingError message
else
user.unblock callback
@normalizeLoginId = (loginId, callback) ->
if /@/.test loginId
email = emailsanitize loginId
JUser.someData { email }, { username: 1 }, (err, cursor) ->
return callback err if err
cursor.nextObject (err, data) ->
return callback err if err?
return callback new KodingError 'Unrecognized email' unless data?
callback null, data.username
else
process.nextTick -> callback null, loginId
@login$ = secure (client, credentials, callback) ->
{ sessionToken : clientId, connection } = client
@login clientId, credentials, (err, response) ->
return callback err if err
connection.delegate = response.account
callback null, response
fetchSession = (options, callback) ->
{ clientId, username } = options
# fetch session of the current requester
JSession.fetchSession clientId, (err, { session: fetchedSession }) ->
return callback err if err
session = fetchedSession
unless session
console.error "login: session not found #{username}"
return callback new KodingError 'Couldn\'t restore your session!'
callback null, session
validateLoginCredentials = (options, callback) ->
{ username, password, tfcode } = options
# check credential validity
JUser.one { username }, (err, user) ->
return logAndReturnLoginError username, err.message, callback if err
# if user not found it means we dont know about given username
unless user?
return logAndReturnLoginError username, 'Unknown user name', callback
# if password is autogenerated return error
if user.getAt('passwordStatus') is 'needs reset'
return logAndReturnLoginError username, \
'You should reset your password in order to continue!', callback
# check if provided password is correct
unless user.checkPassword password
return logAndReturnLoginError username, 'Access denied!', callback
# check if user is using 2factor auth and provided key is ok
if !!(user.getAt 'twofactorkey')
unless tfcode
return callback new KodingError \
'TwoFactor auth Enabled', 'VERIFICATION_CODE_NEEDED'
unless user.check2FactorAuth tfcode
return logAndReturnLoginError username, 'Access denied!', callback
# if everything is fine, just continue
callback null, user
fetchInvitationByCode = (invitationToken, callback) ->
JInvitation = require '../invitation'
JInvitation.byCode invitationToken, (err, invitation) ->
return callback err if err
return callback new KodingError 'invitation is not valid' unless invitation
callback null, invitation
fetchInvitationByData = (options, callback) ->
{ user, groupName } = options
selector = { email: user.email, groupName }
JInvitation = require '../invitation'
JInvitation.one selector, {}, (err, invitation) ->
callback err, invitation
validateLogin = (options, callback) ->
{ loginId, clientId, password, tfcode } = options
username = null
async.series {
username: (next) ->
JUser.normalizeLoginId loginId, (err, username_) ->
username = username_?.toLowerCase?() or ''
next err, username
# fetch session and check for brute force attack
session: (next) ->
fetchSession { clientId, username }, (err, session) ->
return next err if err
bruteForceControlData =
ip : session.clientIP
username : username
# todo add alert support(mail, log etc)
JLog.checkLoginBruteForce bruteForceControlData, (res) ->
unless res
return next new KodingError \
"Your login access is blocked for #{JLog.timeLimit()} minutes."
next null, session
user: (next) ->
validateLoginCredentials { username, password, tfcode }, (err, user) ->
next err, user
}, callback
@login = (clientId, credentials, callback) ->
{ username: loginId, password, groupIsBeingCreated
groupName, tfcode, invitationToken } = credentials
user = null
session = null
account = null
username = null
groupName ?= 'koding'
invitation = null
queue = [
(next) ->
args = { loginId, clientId, password, tfcode }
validateLogin args, (err, data) ->
return next err if err
{ username, user, session } = data
next()
(next) ->
# fetch account of the user, we will use it later
JAccount.one { 'profile.nickname' : username }, (err, account_) ->
return next new KodingError 'couldn\'t find account!' if err
account = account_
next()
(next) ->
{ isSoloAccessible } = require './validators'
opts =
groupName: groupName
account: account
env: KONFIG.environment
return next() if isSoloAccessible opts
next new Error 'You can not login to koding team, please use your own team'
(next) ->
# if we dont have an invitation code, do not continue
return next() unless invitationToken
# check if user can access to group
#
# there can be two cases here
# # user is member, check validity
# # user is not member, and trying to access with invitationToken
# both should succeed
fetchInvitationByCode invitationToken, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) ->
# check if user has pending invitation
return next() if invitationToken
fetchInvitationByData { user, groupName }, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) =>
return next() if groupIsBeingCreated
@addToGroupByInvitation { groupName, account, user, invitation }, next
(next) ->
return next() if groupIsBeingCreated
# we are sure that user can access to the group, set group name into
# cookie while logging in
session.update { $set : { groupName } }, next
]
async.series queue, (err) ->
return callback err if err
# continue login
afterLogin user, clientId, session, (err, response) ->
return callback err if err
callback err, response
@verifyPassword = secure (client, options, callback) ->
{ password, email } = options
{ connection : { delegate } } = client
email = emailsanitize email if email
# handles error and decide to invalidate pin or not
# depending on email and user variables
handleError = (err, user) ->
if email and user
# when email and user is set, we need to invalidate verification token
params =
email : email
action : 'update-email'
username : user.username
JVerificationToken = require '../verificationtoken'
JVerificationToken.invalidatePin params, (err) ->
return console.error 'Pin invalidation error occurred', err if err
callback err, no
# fetch user for invalidating created token
@fetchUser client, (err, user) ->
return handleError err if err
if not password or password is ''
return handleError new KodingError('Password cannot be empty!'), user
confirmed = user.getAt('password') is hashPassword password, user.getAt('salt')
return callback null, yes if confirmed
return handleError null, user
verifyByPin: (options, callback) ->
if (@getAt 'status') is 'confirmed'
return callback null
JVerificationToken = require '../verificationtoken'
{ pin, resendIfExists } = options
email = @getAt 'email'
username = @getAt 'username'
options = {
user : this
action : 'verify-account'
resendIfExists, pin, username, email
}
unless pin?
JVerificationToken.requestNewPin options, (err) -> callback err
else
JVerificationToken.confirmByPin options, (err, confirmed) =>
if err
callback err
else if confirmed
@confirmEmail callback
else
callback new KodingError 'PIN is not confirmed.'
@verifyByPin = secure (client, options, callback) ->
account = client.connection.delegate
account.fetchUser (err, user) ->
return callback new Error 'User not found' unless user
user.verifyByPin options, callback
@addToGroupByInvitation = (options, callback) ->
{ groupName, account, user, invitation } = options
# check for membership
JGroup.one { slug: groupName }, (err, group) ->
return callback new KodingError err if err
return callback new KodingError 'group doesnt exist' if not group
group.isMember account, (err, isMember) ->
return callback err if err
return callback null if isMember # if user is already member, we can continue
# addGroup will check all prerequistes about joining to a group
JUser.addToGroup account, groupName, user.email, invitation, callback
redeemInvitation = (options, callback) ->
{ account, invitation, slug, email } = options
return invitation.accept account, callback if invitation
JInvitation.one { email, groupName : slug }, (err, invitation_) ->
# if we got error or invitation doesnt exist, just return
return callback null if err or not invitation_
return invitation_.accept account, callback
# check if user's email domain is in allowed domains
checkWithDomain = (groupName, email, callback) ->
JGroup.one { slug: groupName }, (err, group) ->
return callback err if err
# yes weird, but we are creating user before creating group
return callback null, { isEligible: yes } if not group
unless group.isInAllowedDomain email
domainErr = 'Your email domain is not in allowed domains for this group'
return callback new KodingError domainErr if group.allowedDomains?.length > 0
return callback new KodingError 'You are not allowed to access this team'
return callback null, { isEligible: yes }
checkSessionValidity = (options, callback) ->
{ session, logout, clientId } = options
{ username } = session
unless username?
# A session without a username is nothing, let's kill it
# and logout the user, this is also a rare condition
logout 'no username found', clientId, callback
return
# If we are dealing with a guest session we know that we need to
# use fake guest user
if /^guest-/.test username
JUser.fetchGuestUser (err, response) ->
return logout 'error fetching guest account' if err
{ account } = response
return logout 'guest account not found' if not response?.account
account.profile.nickname = username
return callback null, { account, session }
return
JUser.one { username }, (err, user) ->
if err?
logout 'error finding user with username', clientId, callback
else unless user?
logout "no user found with #{username} and sessionId", clientId, callback
else
context = { group: session?.groupName ? 'koding' }
user.fetchAccount context, (err, account) ->
if err?
logout 'error fetching account', clientId, callback
else
# A valid session, a valid user attached to
# it voila, scenario #2
callback null, { session, account }
updateUnregisteredUserAccount = (options, callback) ->
{ username : usernameAfterDelete, toBeDeletedUsername, user, client } = options
return (err, docs) ->
return callback err if err?
accountValues = {
type : 'deleted'
skillTags : []
ircNickame : ''
globalFlags : ['deleted']
locationTags : []
onlineStatus : 'offline'
'profile.about' : ''
'profile.hash' : getHash createId()
'profile.avatar' : ''
'profile.nickname' : usernameAfterDelete
'profile.lastName' : 'koding user'
'profile.firstName' : 'a former'
'profile.experience' : ''
'profile.experiencePoints': 0
'profile.lastStatusUpdate': ''
}
params = { 'profile.nickname' : toBeDeletedUsername }
JAccount.one params, (err, account) ->
return callback err if err?
unless account
return callback new KodingError \
"Account not found #{toBeDeletedUsername}"
# update the account to be deleted with empty data
account.update { $set: accountValues }, (err) ->
return callback err if err?
JName.release toBeDeletedUsername, (err) ->
return callback err if err?
JAccount.emit 'UsernameChanged', {
oldUsername : toBeDeletedUsername
isRegistration : false
username : usernameAfterDelete
}
user.unlinkOAuths ->
Payment = require '../payment'
deletedClient = { connection: { delegate: account } }
Payment.deleteAccount deletedClient, (err) ->
account.leaveFromAllGroups client, ->
JUser.logout deletedClient, callback
validateConvertInput = (userFormData, client) ->
{ username
password
passwordConfirm } = userFormData
{ connection } = client
{ delegate : account } = connection
# only unregistered accounts can be "converted"
if account.type is 'registered'
return new KodingError 'This account is already registered.'
if /^guest-/.test username
return new KodingError 'Reserved username!'
if username is 'guestuser'
return new KodingError 'Reserved username: \'guestuser\'!'
if password isnt passwordConfirm
return new KodingError 'Passwords must match!'
unless typeof username is 'string'
return new KodingError 'Username must be a string!'
return null
logAndReturnLoginError = (username, error, callback) ->
JLog.log { type: 'login', username: username, success: no }, ->
callback new KodingError error
updateUserPasswordStatus = (user, callback) ->
# let user log in for the first time, than set password status
# as 'needs reset'
if user.passwordStatus is 'needs set'
user.update { $set : { passwordStatus : 'needs reset' } }, callback
else
callback null
afterLogin = (user, clientId, session, callback) ->
{ username } = user
account = null
replacementToken = null
queue = [
(next) ->
# fetching account, will be used to check login constraints of user
user.fetchOwnAccount (err, account_) ->
return next err if err
account = account_
next()
(next) ->
# checking login constraints
checkBlockedStatus user, next
(next) ->
# updating user passwordStatus if necessary
updateUserPasswordStatus user, (err) ->
return next err if err
replacementToken = createId()
next()
(next) ->
# updating session data after login
sessionUpdateOptions =
$set :
username : username
clientId : replacementToken
lastLoginDate : lastLoginDate = new Date
$unset :
guestId : 1
guestSessionBegan : 1
guestUsername = session.username
session.update sessionUpdateOptions, (err) ->
return next err if err
Tracker.identify username, { lastLoginDate }
Tracker.alias guestUsername, username
next()
(next) ->
# updating user data after login
userUpdateData = { lastLoginDate : new Date }
if session.foreignAuth
{ foreignAuth } = user
foreignAuth or= {}
foreignAuth = extend foreignAuth, session.foreignAuth
userUpdateData.foreignAuth = foreignAuth
userUpdateOptions =
$set : userUpdateData
$unset :
inactive : 1
user.update userUpdateOptions, (err) ->
return next err if err
# This should be called after login and this
# is not correct place to do it, FIXME GG
# p.s. we could do that in workers
account.updateCounts()
if foreignAuth
providers = {}
Object.keys(foreignAuth).forEach (provider) ->
providers[provider] = yes
Tracker.identify user.username, { foreignAuth: providers }
JLog.log { type: 'login', username , success: yes }
next()
(next) ->
JUser.clearOauthFromSession session, next
]
async.series queue, (err) ->
return callback err if err
callback null, { account, replacementToken, returnUrl: session.returnUrl }
Tracker.track username, { subject : Tracker.types.LOGGED_IN }
@logout = secure (client, callback) ->
if 'string' is typeof client
sessionToken = client
else
{ sessionToken } = client
delete client.connection.delegate
delete client.sessionToken
# if sessionToken doesnt exist, safe to return
return callback null unless sessionToken
JSession.remove { clientId: sessionToken }, callback
@verifyEnrollmentEligibility = (options, callback) ->
{ email, invitationToken, groupName, skipAllowedDomainCheck } = options
# this is legacy but still in use, just checks if registeration is enabled or not
JRegistrationPreferences = require '../registrationpreferences'
JInvitation = require '../invitation'
JRegistrationPreferences.one {}, (err, prefs) ->
return callback err if err
unless prefs.isRegistrationEnabled
return callback new Error 'Registration is currently disabled!'
# return without checking domain if skipAllowedDomainCheck is true
return callback null, { isEligible : yes } if skipAllowedDomainCheck
# check if email domain is in allowed domains
return checkWithDomain groupName, email, callback unless invitationToken
JInvitation.byCode invitationToken, (err, invitation) ->
# check if invitation exists
if err or not invitation?
return callback new KodingError 'Invalid invitation code!'
# check if invitation is valid
if invitation.isValid() and invitation.groupName is groupName
return callback null, { isEligible: yes, invitation }
# last resort, check if email domain is under allowed domains
return checkWithDomain groupName, email, callback
@addToGroup = (account, slug, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
options.email = email
options.groupName = slug
options.invitationToken = invitation.code if invitation?.code
JUser.verifyEnrollmentEligibility options, (err, res) ->
return callback err if err
return callback new KodingError 'malformed response' if not res
return callback new KodingError 'can not join to group' if not res.isEligible
# fetch group that we are gonna add account in
JGroup.one { slug }, (err, group) ->
return callback err if err
return callback null if not group
roles = ['member']
if invitation?.role and slug isnt 'koding'
roles.push invitation.role
roles = uniq roles
group.approveMember account, roles, (err) ->
return callback err if err
if code = invitation?.code
groupUrl = "#{protocol}//#{slug}.#{hostname}"
properties =
groupName : slug
link : "#{groupUrl}/Invitation/#{encodeURIComponent code}"
options =
subject : Tracker.types.TEAMS_JOINED_TEAM
Tracker.identifyAndTrack email, options, properties
# do not forget to redeem invitation
redeemInvitation {
account, invitation, slug, email
}, callback
@addToGroups = (account, slugs, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
slugs.push invitation.groupName if invitation?.groupName
slugs = uniq slugs # clean up slugs
queue = slugs.map (slug) => (fin) =>
@addToGroup account, slug, email, invitation, options, fin
async.parallel queue, callback
@createGuestUsername = -> "guest-#{rack()}"
@fetchGuestUser = (callback) ->
username = @createGuestUsername()
account = new JAccount()
account.profile = { nickname: username }
account.type = 'unregistered'
callback null, { account, replacementToken: createId() }
@createUser = (userInfo, callback) ->
{ username, email, password, passwordStatus,
firstName, lastName, foreignAuth, silence, emailFrequency } = userInfo
if typeof username isnt 'string'
return callback new KodingError 'Username must be a string!'
# lower casing username is necessary to prevent conflicts with other JModels
username = username.toLowerCase()
email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
emailFrequencyDefaults = {
global : on
daily : off
privateMessage : on
followActions : off
comment : on
likeActivities : off
groupInvite : on
groupRequest : on
groupApproved : on
groupJoined : on
groupLeft : off
mention : on
marketing : on
}
# _.defaults doesnt handle undefined, extend handles correctly
emailFrequency = extend emailFrequencyDefaults, emailFrequency
slug =
slug : username
constructorName : 'JUser'
usedAsPath : 'username'
collectionName : 'jUsers'
JName.claim username, [slug], 'JUser', (err, nameDoc) ->
return callback err if err
salt = createSalt()
user = new JUser {
username
email
sanitizedEmail
salt
password : hashPassword password, salt
passwordStatus : passwordStatus or 'valid'
emailFrequency : emailFrequency
}
user.foreignAuth = foreignAuth if foreignAuth
user.save (err) ->
if err
nameDoc.remove?()
return if err.code is 11000
then callback new KodingError "Sorry, \"#{email}\" is already in use!"
else callback err
account = new JAccount
profile : {
nickname : username
hash : getHash email
firstName
lastName
}
account.save (err) ->
if err
user.remove?()
nameDoc.remove?()
callback err
else user.addOwnAccount account, (err) ->
if err then callback err
else callback null, user, account
@fetchUserByProvider = (provider, session, callback) ->
{ foreignAuth } = session
unless foreignAuth?[provider]?.foreignId
return callback new KodingError "No foreignAuth:#{provider} info in session"
query = {}
query["foreignAuth.#{provider}.foreignId"] = foreignAuth[provider].foreignId
JUser.one query, callback
@authenticateWithOauth = secure (client, resp, callback) ->
{ isUserLoggedIn, provider } = resp
{ sessionToken } = client
JSession.one { clientId: sessionToken }, (err, session) =>
return callback new KodingError err if err
unless session
{ connection: { delegate: { profile: { nickname } } } } = client
console.error 'authenticateWithOauth: session not found', nickname
return callback new KodingError 'Couldn\'t restore your session!'
kallback = (err, resp = {}) ->
{ account, replacementToken, returnUrl } = resp
callback err, {
isNewUser : false
userInfo : null
account
replacementToken
returnUrl
}
@fetchUserByProvider provider, session, (err, user) =>
return callback new KodingError err.message if err
if isUserLoggedIn
if user and user.username isnt client.connection.delegate.profile.nickname
@clearOauthFromSession session, ->
callback new KodingError '''
Account is already linked with another user.
'''
else
@fetchUser client, (err, user) =>
return callback new KodingError err.message if err
@persistOauthInfo user.username, sessionToken, kallback
else
if user
afterLogin user, sessionToken, session, kallback
else
return callback new KodingError 'Koding Solo registrations are closed!'
@validateAll = (userFormData, callback) ->
Validator = require './validators'
validator = new Validator
isError = no
errors = {}
queue = []
(key for key of validator).forEach (field) =>
queue.push (fin) => validator[field].call this, userFormData, (err) ->
if err?
errors[field] = err
isError = yes
fin()
async.parallel queue, ->
callback if isError
{ message: 'Errors were encountered during validation', errors }
else null
@changeEmailByUsername = (options, callback) ->
{ account, oldUsername, email } = options
# prevent from leading and trailing spaces
email = emailsanitize email
@update { username: oldUsername }, { $set: { email } }, (err, res) ->
return callback err if err
account.profile.hash = getHash email
account.save (err) -> console.error if err
callback null
@changeUsernameByAccount = (options, callback) ->
{ account, username, clientId, isRegistration, groupName } = options
account.changeUsername { username, isRegistration }, (err) ->
return callback err if err?
return callback null unless clientId?
newToken = createId()
JSession.one { clientId }, (err, session) ->
if err?
return callback new KodingError 'Could not update your session'
if session?
sessionUpdateOptions =
$set : { clientId : newToken, username, groupName }
$unset : { guestSessionBegan : 1 }
session.update sessionUpdateOptions, (err) ->
return callback err if err?
callback null, newToken
else
callback new KodingError 'Session not found!'
@removeFromGuestsGroup = (account, callback) ->
JGroup.one { slug: 'guests' }, (err, guestsGroup) ->
return callback err if err?
return callback new KodingError 'Guests group not found!' unless guestsGroup?
guestsGroup.removeMember account, callback
createGroupStack = (account, groupName, callback) ->
_client =
connection :
delegate : account
context :
group : groupName
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack for #{account.profile.nickname}:", err
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback()
verifyUser = (options, callback) ->
{ slug
email
recaptcha
disableCaptcha
userFormData
foreignAuthType } = options
queue = [
(next) ->
# verifying recaptcha if enabled
return next() if disableCaptcha or not KONFIG.recaptcha.enabled
JUser.verifyRecaptcha recaptcha, { foreignAuthType, slug }, next
(next) ->
JUser.validateAll userFormData, next
(next) ->
JUser.emailAvailable email, (err, res) ->
if err
return next new KodingError 'Something went wrong'
if res is no
return next new KodingError 'Email is already in use!'
next()
]
async.series queue, callback
createUser = (options, callback) ->
{ userInfo } = options
# creating a new user
JUser.createUser userInfo, (err, user, account) ->
return callback err if err
unless user? and account?
return callback new KodingError 'Failed to create user!'
callback null, { user, account }
updateUserInfo = (options, callback) ->
{ user, ip, country, region, username,
client, account, clientId, password } = options
newToken = null
queue = [
(next) ->
# updating user's location related info
return next() unless ip? and country? and region?
locationModifier =
$set :
'registeredFrom.ip' : ip
'registeredFrom.region' : region
'registeredFrom.country' : country
user.update locationModifier, ->
next()
(next) ->
JUser.persistOauthInfo username, client.sessionToken, next
(next) ->
return next() unless username?
_options =
account : account
username : username
clientId : clientId
groupName : client.context.group
isRegistration : yes
JUser.changeUsernameByAccount _options, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
user.setPassword password, next
]
async.series queue, (err) ->
return callback err if err
callback null, newToken
updateAccountInfo = (options, callback) ->
{ account, referrer, username } = options
queue = [
(next) ->
account.update { $set: { type: 'registered' } }, next
(next) ->
account.createSocialApiId next
(next) ->
# setting referrer
return next() unless referrer
if username is referrer
console.error "User (#{username}) tried to refer themself."
return next()
JUser.count { username: referrer }, (err, count) ->
if err? or count < 1
console.error 'Provided referrer not valid:', err
return next()
account.update { $set: { referrerUsername: referrer } }, (err) ->
if err?
then console.error err
else console.log "#{referrer} referred #{username}"
next()
]
async.series queue, callback
createDefaultStackForKodingGroup = (options, callback) ->
{ account } = options
# create default stack for koding group, when a user joins this is only
# required for koding group, not neeed for other teams
_client =
connection :
delegate : account
context :
group : 'koding'
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack
for #{account.profile.nickname}:#{err}"
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback null
confirmAccountIfNeeded = (options, callback) ->
{ user, email, username, group } = options
if KONFIG.autoConfirmAccounts or group isnt 'koding'
user.confirmEmail (err) ->
console.warn err if err?
return callback err
else
_options =
email : email
action : 'verify-account'
username : username
JVerificationToken = require '../verificationtoken'
JVerificationToken.createNewPin _options, (err, confirmation) ->
console.warn 'Failed to send verification token:', err if err
callback err, confirmation?.pin
validateConvert = (options, callback) ->
{ client, userFormData, foreignAuthType, skipAllowedDomainCheck } = options
{ slug, email, invitationToken, recaptcha, disableCaptcha } = userFormData
invitation = null
queue = [
(next) ->
params = { slug, email, recaptcha, disableCaptcha, userFormData, foreignAuthType }
verifyUser params, next
(next) ->
params = {
groupName : client.context.group
invitationToken, skipAllowedDomainCheck, email
}
JUser.verifyEnrollmentEligibility params, (err, res) ->
return next err if err
{ isEligible, invitation } = res
if not isEligible
return next new Error "you can not register to #{client.context.group}"
next()
]
async.series queue, (err) ->
return callback err if err
callback null, { invitation }
processConvert = (options, callback) ->
{ ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck } = options
{ sessionToken : clientId } = client
{ referrer, email, username, password,
emailFrequency, firstName, lastName } = userFormData
user = null
error = null
account = null
newToken = null
queue = [
(next) ->
userInfo = {
email, username, password, lastName, firstName, emailFrequency
}
createUser { userInfo }, (err, data) ->
return next err if err
{ user, account } = data
next()
(next) ->
params = {
user, ip, country, region, username
password, clientId, account, client
}
updateUserInfo params, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
updateAccountInfo { account, referrer, username }, next
(next) ->
groupNames = [client.context.group, 'koding']
options = { skipAllowedDomainCheck }
JUser.addToGroups account, groupNames, user.email, invitation, options, (err) ->
error = err
next()
(next) ->
createDefaultStackForKodingGroup { account }, next
]
async.series queue, (err) ->
return callback err if err
# passing "error" variable to be used as an argument in the callback func.
# that is being called after registration process is completed.
callback null, { error, newToken, user, account }
@convert = secure (client, userFormData, options, callback) ->
[options, callback] = [{}, options] unless callback
{ slug, email, agree, username, lastName, referrer,
password, firstName, recaptcha, emailFrequency,
invitationToken, passwordConfirm, disableCaptcha } = userFormData
{ skipAllowedDomainCheck } = options
{ clientIP, connection } = client
{ delegate : account } = connection
{ nickname : oldUsername } = account.profile
# if firstname is not received use username as firstname
userFormData.firstName = username unless firstName
userFormData.lastName = '' unless lastName
if error = validateConvertInput userFormData, client
return callback error
# lower casing username is necessary to prevent conflicts with other JModels
username = userFormData.username = username.toLowerCase()
email = userFormData.email = emailsanitize email
if clientIP
{ ip, country, region } = Regions.findLocation clientIP
pin = null
user = null
error = null
newToken = null
invitation = null
foreignAuthType = null
subscription = null
queue = [
(next) =>
@extractOauthFromSession client.sessionToken, (err, foreignAuthInfo) ->
if err
console.log 'Error while getting oauth data from session', err
return next()
return next() unless foreignAuthInfo
# Password is not required for GitHub users since they are authorized via GitHub.
# To prevent having the same password for all GitHub users since it may be
# a security hole, let's auto generate it if it's not provided in request
unless password
password = userFormData.password = createId()
passwordConfirm = userFormData.passwordConfirm = password
next()
(next) ->
options = { client, userFormData, foreignAuthType, skipAllowedDomainCheck }
validateConvert options, (err, data) ->
return next err if err
{ invitation } = data
next()
(next) ->
params = {
ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck
}
processConvert params, (err, data) ->
return next err if err
{ error, newToken, user, account } = data
next()
(next) ->
date = new Date 0
subscription =
accountId : account.getId()
planTitle : 'free'
planInterval : 'month'
state : 'active'
provider : 'koding'
expiredAt : date
canceledAt : date
currentPeriodStart : date
currentPeriodEnd : date
args = { user, account, subscription, pin, oldUsername }
identifyUserOnRegister disableCaptcha, args
JUser.emit 'UserRegistered', { user, account }
next()
(next) ->
# Auto confirm accounts for development environment or Teams ~ GG
args = { group : client.context.group, user, email, username }
confirmAccountIfNeeded args, (err, pin_) ->
pin = pin_
next err
]
async.series queue, (err) ->
return callback err if err
# don't block register
callback error, { account, newToken, user }
group = client.context.group
args = { user, group, pin, firstName, lastName }
trackUserOnRegister disableCaptcha, args
SiftScience = require '../siftscience'
SiftScience.createAccount client, referrer, ->
identifyUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
{ user, account, subscription, pin, oldUsername } = args
{ status, lastLoginDate, username, email } = user
{ createdAt, profile } = account.meta
{ firstName, lastName } = account.profile
jwtToken = JUser.createJWT { username }
sshKeysCount = user.sshKeys.length
emailFrequency =
global : user.emailFrequency.global
marketing : user.emailFrequency.marketing
traits = {
email
createdAt
lastLoginDate
status
firstName
lastName
subscription
sshKeysCount
emailFrequency
pin
jwtToken
}
Tracker.identify username, traits
Tracker.alias oldUsername, username
trackUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
subject = Tracker.types.START_REGISTER
{ user, group, pin, firstName, lastName } = args
{ username, email } = user
opts = { pin, group, user : { user_id : username, email, firstName, lastName } }
Tracker.track username, { to : email, subject }, opts
@createJWT: (data, options = {}) ->
{ secret, confirmExpiresInMinutes } = KONFIG.jwt
jwt = require 'jsonwebtoken'
# uses 'HS256' as default for signing
options.expiresInMinutes ?= confirmExpiresInMinutes
return jwt.sign data, secret, options
@removeUnsubscription:({ email }, callback) ->
JUnsubscribedMail = require '../unsubscribedmail'
JUnsubscribedMail.one { email }, (err, unsubscribed) ->
return callback err if err or not unsubscribed
unsubscribed.remove callback
@grantInitialInvitations = (username) ->
JInvitation.grant { 'profile.nickname': username }, 3, (err) ->
console.log 'An error granting invitations', err if err
@fetchUser = secure (client, callback) ->
JSession.one { clientId: client.sessionToken }, (err, session) ->
return callback err if err
noUserError = -> new KodingError \
'No user found! Not logged in or session expired'
if not session or not session.username
return callback noUserError()
JUser.one { username: session.username }, (err, user) ->
if err or not user
console.log '[JUser::fetchUser]', err if err?
callback noUserError()
else
callback null, user
@changePassword = secure (client, password, callback) ->
@fetchUser client, (err, user) ->
if err or not user
return callback new KodingError \
'Something went wrong please try again!'
if user.getAt('password') is hashPassword password, user.getAt('salt')
return callback new KodingError 'PasswordIsSame'
user.changePassword password, (err) ->
return callback err if err
account = client.connection.delegate
clientId = client.sessionToken
account.sendNotification 'SessionHasEnded', { clientId }
selector = { clientId: { $ne: client.sessionToken } }
user.killSessions selector, callback
sendChangedEmail = (username, firstName, to, type) ->
subject = if type is 'email' then Tracker.types.CHANGED_EMAIL
else Tracker.types.CHANGED_PASSWORD
Tracker.track username, { to, subject }, { firstName }
@changeEmail = secure (client, options, callback) ->
{ email } = options
email = options.email = emailsanitize email
account = client.connection.delegate
account.fetchUser (err, user) =>
return callback new KodingError 'Something went wrong please try again!' if err
return callback new KodingError 'EmailIsSameError' if email is user.email
@emailAvailable email, (err, res) ->
return callback new KodingError 'Something went wrong please try again!' if err
if res is no
callback new KodingError 'Email is already in use!'
else
user.changeEmail account, options, callback
@emailAvailable = (email, callback) ->
unless typeof email is 'string'
return callback new KodingError 'Not a valid email!'
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
@count { sanitizedEmail }, (err, count) ->
callback err, count is 0
@getValidUsernameLengthRange = -> { minLength : 4, maxLength : 25 }
@usernameAvailable = (username, callback) ->
JName = require '../name'
username += ''
res =
kodingUser : no
forbidden : yes
JName.count { name: username }, (err, count) =>
{ minLength, maxLength } = JUser.getValidUsernameLengthRange()
if err or username.length < minLength or username.length > maxLength
callback err, res
else
res.kodingUser = count is 1
res.forbidden = username in @bannedUserList
callback null, res
fetchAccount: (context, rest...) -> @fetchOwnAccount rest...
setPassword: (password, callback) ->
salt = createSalt()
@update {
$set :
salt : salt
password : hashPassword password, salt
passwordStatus : 'valid'
}, callback
changePassword: (newPassword, callback) ->
@setPassword newPassword, (err) =>
return callback err if err
@fetchAccount 'koding', (err, account) =>
return callback err if err
return callback new KodingError 'Account not found' unless account
{ firstName } = account.profile
sendChangedEmail @getAt('username'), firstName, @getAt('email'), 'password'
callback null
changeEmail: (account, options, callback) ->
JVerificationToken = require '../verificationtoken'
{ email, pin } = options
email = options.email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
if account.type is 'unregistered'
@update { $set: { email , sanitizedEmail } }, (err) ->
return callback err if err
callback null
return
action = 'update-email'
if not pin
options = {
email, action, user: this, resendIfExists: yes
}
JVerificationToken.requestNewPin options, callback
else
options = {
email, action, pin, username: @getAt 'username'
}
JVerificationToken.confirmByPin options, (err, confirmed) =>
return callback err if err
unless confirmed
return callback new KodingError 'PIN is not confirmed.'
oldEmail = @getAt 'email'
@update { $set: { email, sanitizedEmail } }, (err, res) =>
return callback err if err
account.profile.hash = getHash email
account.save (err) =>
return callback err if err
{ firstName } = account.profile
# send EmailChanged event
@constructor.emit 'EmailChanged', {
username: @getAt('username')
oldEmail: oldEmail
newEmail: email
}
sendChangedEmail @getAt('username'), firstName, oldEmail, 'email'
callback null
Tracker.identify @username, { email }
fetchHomepageView: (options, callback) ->
{ account, bongoModels } = options
@fetchAccount 'koding', (err, account) ->
return callback err if err
return callback new KodingError 'Account not found' unless account
account.fetchHomepageView options, callback
confirmEmail: (callback) ->
status = @getAt 'status'
username = @getAt 'username'
# for some reason status is sometimes 'undefined', so check for that
if status? and status isnt 'unconfirmed'
return callback null
modifier = { status: 'confirmed' }
@update { $set: modifier }, (err, res) =>
return callback err if err
JUser.emit 'EmailConfirmed', this
callback null
Tracker.identify username, modifier
Tracker.track username, { subject: Tracker.types.FINISH_REGISTER }
block: (blockedUntil, callback) ->
unless blockedUntil then return callback new KodingError 'Blocking date is not defined'
status = 'blocked'
@update { $set: { status, blockedUntil } }, (err) =>
return callback err if err
JUser.emit 'UserBlocked', this
console.log 'JUser#block JSession#remove', { @username, blockedUntil }
# clear all of the cookies of the blocked user
JSession.remove { username: @username }, callback
Tracker.identify @username, { status }
unblock: (callback) ->
status = 'confirmed'
op =
$set : { status }
$unset : { blockedUntil: yes }
@update op, (err) =>
return callback err if err
JUser.emit 'UserUnblocked', this
callback()
Tracker.identify @username, { status }
unlinkOAuths: (callback) ->
@update { $unset: { foreignAuth:1 , foreignAuthType:1 } }, (err) =>
return callback err if err
@fetchOwnAccount (err, account) ->
return callback err if err
account.unstoreAll callback
@persistOauthInfo: (username, clientId, callback) ->
@extractOauthFromSession clientId, (err, foreignAuthInfo) =>
return callback err if err
return callback null unless foreignAuthInfo
return callback null unless foreignAuthInfo.session
@saveOauthToUser foreignAuthInfo, username, (err) =>
return callback err if err
do (foreignAuth = {}) ->
{ foreignAuthType } = foreignAuthInfo
foreignAuth[foreignAuthType] = yes
Tracker.identify username, { foreignAuth }
@clearOauthFromSession foreignAuthInfo.session, (err) =>
return callback err if err
@copyPublicOauthToAccount username, foreignAuthInfo, (err, resp = {}) ->
return callback err if err
{ session: { returnUrl } } = foreignAuthInfo
resp.returnUrl = returnUrl if returnUrl
return callback null, resp
@extractOauthFromSession: (clientId, callback) ->
JSession.one { clientId: clientId }, (err, session) ->
return callback err if err
return callback null unless session
{ foreignAuth, foreignAuthType } = session
if foreignAuth and foreignAuthType
callback null, { foreignAuth, foreignAuthType, session }
else
callback null # WARNING: don't assume it's an error if there's no foreignAuth
@saveOauthToUser: ({ foreignAuth, foreignAuthType }, username, callback) ->
query = {}
query["foreignAuth.#{foreignAuthType}"] = foreignAuth[foreignAuthType]
@update { username }, { $set: query }, callback
@clearOauthFromSession: (session, callback) ->
session.update { $unset: { foreignAuth:1, foreignAuthType:1 } }, callback
@copyPublicOauthToAccount: (username, { foreignAuth, foreignAuthType }, callback) ->
JAccount.one { 'profile.nickname' : username }, (err, account) ->
return callback err if err
name = "ext|profile|#{foreignAuthType}"
content = foreignAuth[foreignAuthType].profile
account._store { name, content }, callback
@setSSHKeys: secure (client, sshKeys, callback) ->
@fetchUser client, (err, user) ->
user.sshKeys = sshKeys
user.save callback
Tracker.identify user.username, { sshKeysCount: sshKeys.length }
@getSSHKeys: secure (client, callback) ->
@fetchUser client, (err, user) ->
return callback user?.sshKeys or []
###*
* Compare provided password with JUser.password
*
* @param {string} password
###
checkPassword: (password) ->
# hash of given password and given user's salt should match with user's password
return @getAt('password') is hashPassword password, @getAt('salt')
###*
* Compare provided verification token with time
* based generated 2Factor code. If 2Factor not enabled returns true
*
* @param {string} verificationCode
###
check2FactorAuth: (verificationCode) ->
key = @getAt 'twofactorkey'
speakeasy = require 'speakeasy'
generatedKey = speakeasy.totp { key, encoding: 'base32' }
return generatedKey is verificationCode
###*
* Verify if `response` from client is valid by asking recaptcha servers.
* Check is disabled in dev mode or when user is authenticating via `github`.
*
* @param {string} response
* @param {string} foreignAuthType
* @param {function} callback
###
@verifyRecaptcha = (response, params, callback) ->
{ url, secret } = KONFIG.recaptcha
{ foreignAuthType, slug } = params
return callback null if foreignAuthType is 'github'
# TODO: temporarily disable recaptcha for groups
if slug? and slug isnt 'koding'
return callback null
request.post url, { form: { response, secret } }, (err, res, raw) ->
if err
console.log "Recaptcha: err validation captcha: #{err}"
if not err and res.statusCode is 200
try
if JSON.parse(raw)['success']
return callback null
catch e
console.log "Recaptcha: parsing response failed. #{raw}"
return callback new KodingError 'Captcha not valid. Please try again.'
###*
* Remove session documents matching selector object.
*
* @param {Object} [selector={}] - JSession query selector.
* @param {Function} - Callback.
###
killSessions: (selector = {}, callback) ->
selector.username = @username
JSession.remove selector, callback
| 90423 | async = require 'async'
jraphical = require 'jraphical'
Regions = require 'koding-regions'
request = require 'request'
KONFIG = require 'koding-config-manager'
Flaggable = require '../../traits/flaggable'
KodingError = require '../../error'
emailsanitize = require './emailsanitize'
{ extend, uniq } = require 'underscore'
{ protocol, hostname } = KONFIG
module.exports = class JUser extends jraphical.Module
{ v4: createId } = require 'node-uuid'
{ Relationship } = jraphical
{ secure, signature } = require 'bongo'
JAccount = require '../account'
JSession = require '../session'
JInvitation = require '../invitation'
JName = require '../name'
JGroup = require '../group'
JLog = require '../log'
ComputeProvider = require '../computeproviders/computeprovider'
Tracker = require '../tracker'
Payment = require '../payment'
@bannedUserList = ['abrt', 'amykhailov', 'apache', 'about', 'visa', 'shared-',
'cthorn', 'daemon', 'dbus', 'dyasar', 'ec2-user', 'http',
'games', 'ggoksel', 'gopher', 'haldaemon', 'halt', 'mail',
'nfsnobody', 'nginx', 'nobody', 'node', 'operator', 'https',
'root', 'rpcuser', 'saslauth', 'shutdown', 'sinanlocal',
'sshd', 'sync', 'tcpdump', 'uucp', 'vcsa', 'zabbix',
'search', 'blog', 'activity', 'guest', 'credits', 'about',
'kodingen', 'alias', 'backup', 'bin', 'bind', 'daemon',
'Debian-exim', 'dhcp', 'drweb', 'games', 'gnats', 'klog',
'kluser', 'libuuid', 'list', 'mhandlers-user', 'more',
'mysql', 'nagios', 'news', 'nobody', 'popuser', 'postgres',
'proxy', 'psaadm', 'psaftp', 'qmaild', 'qmaill', 'qmailp',
'qmailq', 'qmailr', 'qmails', 'sshd', 'statd', 'sw-cp-server',
'sync', 'syslog', 'tomcat', 'tomcat55', 'uucp', 'what',
'www-data', 'fuck', 'porn', 'p0rn', 'porno', 'fucking',
'fucker', 'admin', 'postfix', 'puppet', 'main', 'invite',
'administrator', 'members', 'register', 'activate', 'shared',
'groups', 'blogs', 'forums', 'topics', 'develop', 'terminal',
'term', 'twitter', 'facebook', 'google', 'framework', 'kite',
'landing', 'hello', 'dev', 'sandbox', 'latest',
'all', 'channel', 'admins', 'group', 'team'
]
hashPassword = (value, salt) ->
require('crypto').createHash('sha1').update(salt + value).digest('hex')
createSalt = require 'hat'
rack = createSalt.rack 64
@share()
@trait __dirname, '../../traits/flaggable'
@getFlagRole = -> 'owner'
@set
softDelete : yes
broadcastable : no
indexes :
username : 'unique'
email : 'unique'
sanitizedEmail: ['unique', 'sparse']
'foreignAuth.github.foreignId' : 'ascending'
'foreignAuth.facebook.foreignId' : 'ascending'
'foreignAuth.google.foreignId' : 'ascending'
'foreignAuth.linkedin.foreignId' : 'ascending'
'foreignAuth.twitter.foreignId' : 'ascending'
sharedEvents :
# do not share any events
static : []
instance : []
sharedMethods :
# do not share any instance methods
# instances :
static :
login : (signature Object, Function)
whoami : (signature Function)
logout : (signature Function)
convert : (signature Object, Function)
fetchUser : (signature Function)
setSSHKeys : (signature [Object], Function)
getSSHKeys : (signature Function)
unregister : (signature String, Function)
verifyByPin : (signature Object, Function)
changeEmail : (signature Object, Function)
verifyPassword : (signature Object, Function)
emailAvailable : (signature String, Function)
changePassword : (signature String, Function)
usernameAvailable : (signature String, Function)
authenticateWithOauth : (signature Object, Function)
isRegistrationEnabled : (signature Function)
schema :
username :
type : String
validate : JName.validateName
set : (value) -> value.toLowerCase()
oldUsername : String
uid :
type : Number
set : Math.floor
email :
type : String
validate : JName.validateEmail
set : emailsanitize
sanitizedEmail:
type : String
validate : JName.validateEmail
set : (value) ->
return unless typeof value is 'string'
emailsanitize value, { excludeDots: yes, excludePlus: yes }
password : String
salt : String
twofactorkey : String
blockedUntil : Date
blockedReason : String
status :
type : String
enum : [
'invalid status type', [
'unconfirmed', 'confirmed', 'blocked', 'deleted'
]
]
default : 'unconfirmed'
passwordStatus:
type : String
enum : [
'invalid password status type', [
'needs reset', 'needs set', 'valid', 'autogenerated'
]
]
default : 'valid'
registeredAt :
type : Date
default : -> new Date
registeredFrom:
ip : String
country : String
region : String
lastLoginDate :
type : Date
default : -> new Date
# store fields for janitor worker. see go/src/koding/db/models/user.go for more details.
inactive : Object
# stores user preference for how often email should be sent.
# see go/src/koding/db/models/user.go for more details.
emailFrequency: Object
onlineStatus :
actual :
type : String
enum : ['invalid status', ['online', 'offline']]
default : 'online'
userPreference:
type : String
# enum : ['invalid status',['online','offline','away','busy']]
sshKeys :
type : Object
default : []
foreignAuth :
github :
foreignId : String
username : String
token : String
firstName : String
lastName : String
email : String
scope : String
facebook :
foreignId : String
username : String
token : String
linkedin :
foreignId : String
relationships :
ownAccount :
targetType : JAccount
as : 'owner'
sessions = {}
users = {}
guests = {}
@unregister = secure (client, toBeDeletedUsername, callback) ->
{ delegate } = client.connection
{ nickname } = delegate.profile
console.log "#{nickname} requested to delete: #{toBeDeletedUsername}"
# deleter should be registered one
if delegate.type is 'unregistered'
return callback new KodingError 'You are not registered!'
# only owner and the dummy admins can delete a user
unless toBeDeletedUsername is nickname or
delegate.can 'administer accounts'
return callback new KodingError 'You must confirm this action!'
username = @createGuestUsername()
# Adding -rm suffix to separate them from real guests
# -rm was intentional otherwise we are exceeding the max username length
username = "#{username}-rm"
# Why we do have such thing? ~ GG
email = <EMAIL>"
@one { username: toBeDeletedUsername }, (err, user) ->
return callback err if err?
unless user
return callback new KodingError \
"User not found #{toBeDeletedUsername}"
userValues = {
email : email
sanitizedEmail : email
# here we have a trick, emailBeforeDeletion is not in the schema but we
# are setting it to the db. it is not in the schema because we dont want
# it to be seen in the codebase and it wont be mapped to a JUser
emailBeforeDeletion : user.email
status : 'deleted'
sshKeys : []
username : username
password : createId()
foreignAuth : {}
onlineStatus : 'offline'
registeredAt : new Date 0
lastLoginDate : new Date 0
passwordStatus : '<PASSWORD>'
emailFrequency : {}
}
modifier = { $set: userValues, $unset: { oldUsername: 1 } }
# update the user with empty data
user.update modifier, updateUnregisteredUserAccount({
user, username, toBeDeletedUsername, client
}, callback)
@isRegistrationEnabled = (callback) ->
JRegistrationPreferences = require '../registrationpreferences'
JRegistrationPreferences.one {}, (err, prefs) ->
callback err? or prefs?.isRegistrationEnabled or no
@authenticateClient: (clientId, callback) ->
logError = (message, rest...) ->
console.error "[JUser::authenticateClient] #{message}", rest...
logout = (reason, clientId, callback) =>
@logout clientId, (err) ->
logError reason, clientId
callback new KodingError reason
# Let's try to lookup provided session first
JSession.one { clientId }, (err, session) ->
if err
# This is a very rare state here
logError 'error finding session', { err, clientId }
callback new KodingError err
else unless session?
# We couldn't find the session with given token
# so we are creating a new one now.
JSession.createSession (err, { session, account }) ->
if err?
logError 'failed to create session', { err }
callback err
else
# Voila session created and sent back, scenario #1
callback null, { session, account }
else
# So we have a session, let's check it out if its a valid one
checkSessionValidity { session, logout, clientId }, callback
@getHash = getHash = (value) ->
require('crypto').createHash('md5').update(value.toLowerCase()).digest('hex')
@whoami = secure ({ connection:{ delegate } }, callback) -> callback null, delegate
@getBlockedMessage = (toDate) ->
return """
This account has been put on suspension due to a violation of our acceptable use policy. The ban will be in effect until <b>#{toDate}.</b><br><br>
If you have any questions, please email <a class="ban" href='mailto:<EMAIL>}'><EMAIL>}</a> and allow 2-3 business days for a reply. Even though your account is banned, all your data is safe.<br><br>
Please note, repeated violations of our acceptable use policy will result in the permanent deletion of your account.<br><br>
<NAME>
"""
checkBlockedStatus = (user, callback) ->
return callback null if user.status isnt 'blocked'
if user.blockedUntil and user.blockedUntil > new Date
toDate = user.blockedUntil.toUTCString()
message = JUser.getBlockedMessage toDate
callback new KodingError message
else
user.unblock callback
@normalizeLoginId = (loginId, callback) ->
if /@/.test loginId
email = emailsanitize loginId
JUser.someData { email }, { username: 1 }, (err, cursor) ->
return callback err if err
cursor.nextObject (err, data) ->
return callback err if err?
return callback new KodingError 'Unrecognized email' unless data?
callback null, data.username
else
process.nextTick -> callback null, loginId
@login$ = secure (client, credentials, callback) ->
{ sessionToken : clientId, connection } = client
@login clientId, credentials, (err, response) ->
return callback err if err
connection.delegate = response.account
callback null, response
fetchSession = (options, callback) ->
{ clientId, username } = options
# fetch session of the current requester
JSession.fetchSession clientId, (err, { session: fetchedSession }) ->
return callback err if err
session = fetchedSession
unless session
console.error "login: session not found #{username}"
return callback new KodingError 'Couldn\'t restore your session!'
callback null, session
validateLoginCredentials = (options, callback) ->
{ username, password, tfcode } = options
# check credential validity
JUser.one { username }, (err, user) ->
return logAndReturnLoginError username, err.message, callback if err
# if user not found it means we dont know about given username
unless user?
return logAndReturnLoginError username, 'Unknown user name', callback
# if password is autogenerated return error
if user.getAt('passwordStatus') is 'needs reset'
return logAndReturnLoginError username, \
'You should reset your password in order to continue!', callback
# check if provided password is correct
unless user.checkPassword password
return logAndReturnLoginError username, 'Access denied!', callback
# check if user is using 2factor auth and provided key is ok
if !!(user.getAt 'twofactorkey')
unless tfcode
return callback new KodingError \
'TwoFactor auth Enabled', 'VERIFICATION_CODE_NEEDED'
unless user.check2FactorAuth tfcode
return logAndReturnLoginError username, 'Access denied!', callback
# if everything is fine, just continue
callback null, user
fetchInvitationByCode = (invitationToken, callback) ->
JInvitation = require '../invitation'
JInvitation.byCode invitationToken, (err, invitation) ->
return callback err if err
return callback new KodingError 'invitation is not valid' unless invitation
callback null, invitation
fetchInvitationByData = (options, callback) ->
{ user, groupName } = options
selector = { email: user.email, groupName }
JInvitation = require '../invitation'
JInvitation.one selector, {}, (err, invitation) ->
callback err, invitation
validateLogin = (options, callback) ->
{ loginId, clientId, password, tfcode } = options
username = null
async.series {
username: (next) ->
JUser.normalizeLoginId loginId, (err, username_) ->
username = username_?.toLowerCase?() or ''
next err, username
# fetch session and check for brute force attack
session: (next) ->
fetchSession { clientId, username }, (err, session) ->
return next err if err
bruteForceControlData =
ip : session.clientIP
username : username
# todo add alert support(mail, log etc)
JLog.checkLoginBruteForce bruteForceControlData, (res) ->
unless res
return next new KodingError \
"Your login access is blocked for #{JLog.timeLimit()} minutes."
next null, session
user: (next) ->
validateLoginCredentials { username, password, tfcode }, (err, user) ->
next err, user
}, callback
@login = (clientId, credentials, callback) ->
{ username: loginId, password, groupIsBeingCreated
groupName, tfcode, invitationToken } = credentials
user = null
session = null
account = null
username = null
groupName ?= 'koding'
invitation = null
queue = [
(next) ->
args = { loginId, clientId, password, tfcode }
validateLogin args, (err, data) ->
return next err if err
{ username, user, session } = data
next()
(next) ->
# fetch account of the user, we will use it later
JAccount.one { 'profile.nickname' : username }, (err, account_) ->
return next new KodingError 'couldn\'t find account!' if err
account = account_
next()
(next) ->
{ isSoloAccessible } = require './validators'
opts =
groupName: groupName
account: account
env: KONFIG.environment
return next() if isSoloAccessible opts
next new Error 'You can not login to koding team, please use your own team'
(next) ->
# if we dont have an invitation code, do not continue
return next() unless invitationToken
# check if user can access to group
#
# there can be two cases here
# # user is member, check validity
# # user is not member, and trying to access with invitationToken
# both should succeed
fetchInvitationByCode invitationToken, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) ->
# check if user has pending invitation
return next() if invitationToken
fetchInvitationByData { user, groupName }, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) =>
return next() if groupIsBeingCreated
@addToGroupByInvitation { groupName, account, user, invitation }, next
(next) ->
return next() if groupIsBeingCreated
# we are sure that user can access to the group, set group name into
# cookie while logging in
session.update { $set : { groupName } }, next
]
async.series queue, (err) ->
return callback err if err
# continue login
afterLogin user, clientId, session, (err, response) ->
return callback err if err
callback err, response
@verifyPassword = secure (client, options, callback) ->
{ password, email } = options
{ connection : { delegate } } = client
email = emailsanitize email if email
# handles error and decide to invalidate pin or not
# depending on email and user variables
handleError = (err, user) ->
if email and user
# when email and user is set, we need to invalidate verification token
params =
email : email
action : 'update-email'
username : user.username
JVerificationToken = require '../verificationtoken'
JVerificationToken.invalidatePin params, (err) ->
return console.error 'Pin invalidation error occurred', err if err
callback err, no
# fetch user for invalidating created token
@fetchUser client, (err, user) ->
return handleError err if err
if not password or password is ''
return handleError new KodingError('Password cannot be empty!'), user
confirmed = user.getAt('password') is hashPassword password, user.getAt('salt')
return callback null, yes if confirmed
return handleError null, user
verifyByPin: (options, callback) ->
if (@getAt 'status') is 'confirmed'
return callback null
JVerificationToken = require '../verificationtoken'
{ pin, resendIfExists } = options
email = @getAt 'email'
username = @getAt 'username'
options = {
user : this
action : 'verify-account'
resendIfExists, pin, username, email
}
unless pin?
JVerificationToken.requestNewPin options, (err) -> callback err
else
JVerificationToken.confirmByPin options, (err, confirmed) =>
if err
callback err
else if confirmed
@confirmEmail callback
else
callback new KodingError 'PIN is not confirmed.'
@verifyByPin = secure (client, options, callback) ->
account = client.connection.delegate
account.fetchUser (err, user) ->
return callback new Error 'User not found' unless user
user.verifyByPin options, callback
@addToGroupByInvitation = (options, callback) ->
{ groupName, account, user, invitation } = options
# check for membership
JGroup.one { slug: groupName }, (err, group) ->
return callback new KodingError err if err
return callback new KodingError 'group doesnt exist' if not group
group.isMember account, (err, isMember) ->
return callback err if err
return callback null if isMember # if user is already member, we can continue
# addGroup will check all prerequistes about joining to a group
JUser.addToGroup account, groupName, user.email, invitation, callback
redeemInvitation = (options, callback) ->
{ account, invitation, slug, email } = options
return invitation.accept account, callback if invitation
JInvitation.one { email, groupName : slug }, (err, invitation_) ->
# if we got error or invitation doesnt exist, just return
return callback null if err or not invitation_
return invitation_.accept account, callback
# check if user's email domain is in allowed domains
checkWithDomain = (groupName, email, callback) ->
JGroup.one { slug: groupName }, (err, group) ->
return callback err if err
# yes weird, but we are creating user before creating group
return callback null, { isEligible: yes } if not group
unless group.isInAllowedDomain email
domainErr = 'Your email domain is not in allowed domains for this group'
return callback new KodingError domainErr if group.allowedDomains?.length > 0
return callback new KodingError 'You are not allowed to access this team'
return callback null, { isEligible: yes }
checkSessionValidity = (options, callback) ->
{ session, logout, clientId } = options
{ username } = session
unless username?
# A session without a username is nothing, let's kill it
# and logout the user, this is also a rare condition
logout 'no username found', clientId, callback
return
# If we are dealing with a guest session we know that we need to
# use fake guest user
if /^guest-/.test username
JUser.fetchGuestUser (err, response) ->
return logout 'error fetching guest account' if err
{ account } = response
return logout 'guest account not found' if not response?.account
account.profile.nickname = username
return callback null, { account, session }
return
JUser.one { username }, (err, user) ->
if err?
logout 'error finding user with username', clientId, callback
else unless user?
logout "no user found with #{username} and sessionId", clientId, callback
else
context = { group: session?.groupName ? 'koding' }
user.fetchAccount context, (err, account) ->
if err?
logout 'error fetching account', clientId, callback
else
# A valid session, a valid user attached to
# it voila, scenario #2
callback null, { session, account }
updateUnregisteredUserAccount = (options, callback) ->
{ username : usernameAfterDelete, toBeDeletedUsername, user, client } = options
return (err, docs) ->
return callback err if err?
accountValues = {
type : 'deleted'
skillTags : []
ircNickame : ''
globalFlags : ['deleted']
locationTags : []
onlineStatus : 'offline'
'profile.about' : ''
'profile.hash' : getHash createId()
'profile.avatar' : ''
'profile.nickname' : usernameAfterDelete
'profile.lastName' : '<NAME>'
'profile.firstName' : '<NAME>'
'profile.experience' : ''
'profile.experiencePoints': 0
'profile.lastStatusUpdate': ''
}
params = { 'profile.nickname' : toBeDeletedUsername }
JAccount.one params, (err, account) ->
return callback err if err?
unless account
return callback new KodingError \
"Account not found #{toBeDeletedUsername}"
# update the account to be deleted with empty data
account.update { $set: accountValues }, (err) ->
return callback err if err?
JName.release toBeDeletedUsername, (err) ->
return callback err if err?
JAccount.emit 'UsernameChanged', {
oldUsername : toBeDeletedUsername
isRegistration : false
username : usernameAfterDelete
}
user.unlinkOAuths ->
Payment = require '../payment'
deletedClient = { connection: { delegate: account } }
Payment.deleteAccount deletedClient, (err) ->
account.leaveFromAllGroups client, ->
JUser.logout deletedClient, callback
validateConvertInput = (userFormData, client) ->
{ username
password
passwordConfirm } = userFormData
{ connection } = client
{ delegate : account } = connection
# only unregistered accounts can be "converted"
if account.type is 'registered'
return new KodingError 'This account is already registered.'
if /^guest-/.test username
return new KodingError 'Reserved username!'
if username is 'guestuser'
return new KodingError 'Reserved username: \'guestuser\'!'
if password isnt passwordConfirm
return new KodingError 'Passwords must match!'
unless typeof username is 'string'
return new KodingError 'Username must be a string!'
return null
logAndReturnLoginError = (username, error, callback) ->
JLog.log { type: 'login', username: username, success: no }, ->
callback new KodingError error
updateUserPasswordStatus = (user, callback) ->
# let user log in for the first time, than set password status
# as 'needs reset'
if user.passwordStatus is 'needs set'
user.update { $set : { passwordStatus : 'needs reset' } }, callback
else
callback null
afterLogin = (user, clientId, session, callback) ->
{ username } = user
account = null
replacementToken = null
queue = [
(next) ->
# fetching account, will be used to check login constraints of user
user.fetchOwnAccount (err, account_) ->
return next err if err
account = account_
next()
(next) ->
# checking login constraints
checkBlockedStatus user, next
(next) ->
# updating user passwordStatus if necessary
updateUserPasswordStatus user, (err) ->
return next err if err
replacementToken = createId()
next()
(next) ->
# updating session data after login
sessionUpdateOptions =
$set :
username : username
clientId : replacementToken
lastLoginDate : lastLoginDate = new Date
$unset :
guestId : 1
guestSessionBegan : 1
guestUsername = session.username
session.update sessionUpdateOptions, (err) ->
return next err if err
Tracker.identify username, { lastLoginDate }
Tracker.alias guestUsername, username
next()
(next) ->
# updating user data after login
userUpdateData = { lastLoginDate : new Date }
if session.foreignAuth
{ foreignAuth } = user
foreignAuth or= {}
foreignAuth = extend foreignAuth, session.foreignAuth
userUpdateData.foreignAuth = foreignAuth
userUpdateOptions =
$set : userUpdateData
$unset :
inactive : 1
user.update userUpdateOptions, (err) ->
return next err if err
# This should be called after login and this
# is not correct place to do it, FIXME GG
# p.s. we could do that in workers
account.updateCounts()
if foreignAuth
providers = {}
Object.keys(foreignAuth).forEach (provider) ->
providers[provider] = yes
Tracker.identify user.username, { foreignAuth: providers }
JLog.log { type: 'login', username , success: yes }
next()
(next) ->
JUser.clearOauthFromSession session, next
]
async.series queue, (err) ->
return callback err if err
callback null, { account, replacementToken, returnUrl: session.returnUrl }
Tracker.track username, { subject : Tracker.types.LOGGED_IN }
@logout = secure (client, callback) ->
if 'string' is typeof client
sessionToken = client
else
{ sessionToken } = client
delete client.connection.delegate
delete client.sessionToken
# if sessionToken doesnt exist, safe to return
return callback null unless sessionToken
JSession.remove { clientId: sessionToken }, callback
@verifyEnrollmentEligibility = (options, callback) ->
{ email, invitationToken, groupName, skipAllowedDomainCheck } = options
# this is legacy but still in use, just checks if registeration is enabled or not
JRegistrationPreferences = require '../registrationpreferences'
JInvitation = require '../invitation'
JRegistrationPreferences.one {}, (err, prefs) ->
return callback err if err
unless prefs.isRegistrationEnabled
return callback new Error 'Registration is currently disabled!'
# return without checking domain if skipAllowedDomainCheck is true
return callback null, { isEligible : yes } if skipAllowedDomainCheck
# check if email domain is in allowed domains
return checkWithDomain groupName, email, callback unless invitationToken
JInvitation.byCode invitationToken, (err, invitation) ->
# check if invitation exists
if err or not invitation?
return callback new KodingError 'Invalid invitation code!'
# check if invitation is valid
if invitation.isValid() and invitation.groupName is groupName
return callback null, { isEligible: yes, invitation }
# last resort, check if email domain is under allowed domains
return checkWithDomain groupName, email, callback
@addToGroup = (account, slug, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
options.email = email
options.groupName = slug
options.invitationToken = invitation.code if invitation?.code
JUser.verifyEnrollmentEligibility options, (err, res) ->
return callback err if err
return callback new KodingError 'malformed response' if not res
return callback new KodingError 'can not join to group' if not res.isEligible
# fetch group that we are gonna add account in
JGroup.one { slug }, (err, group) ->
return callback err if err
return callback null if not group
roles = ['member']
if invitation?.role and slug isnt 'koding'
roles.push invitation.role
roles = uniq roles
group.approveMember account, roles, (err) ->
return callback err if err
if code = invitation?.code
groupUrl = "#{protocol}//#{slug}.#{hostname}"
properties =
groupName : slug
link : "#{groupUrl}/Invitation/#{encodeURIComponent code}"
options =
subject : Tracker.types.TEAMS_JOINED_TEAM
Tracker.identifyAndTrack email, options, properties
# do not forget to redeem invitation
redeemInvitation {
account, invitation, slug, email
}, callback
@addToGroups = (account, slugs, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
slugs.push invitation.groupName if invitation?.groupName
slugs = uniq slugs # clean up slugs
queue = slugs.map (slug) => (fin) =>
@addToGroup account, slug, email, invitation, options, fin
async.parallel queue, callback
@createGuestUsername = -> "guest-#{rack()}"
@fetchGuestUser = (callback) ->
username = @createGuestUsername()
account = new JAccount()
account.profile = { nickname: username }
account.type = 'unregistered'
callback null, { account, replacementToken: createId() }
@createUser = (userInfo, callback) ->
{ username, email, password, passwordStatus,
firstName, lastName, foreignAuth, silence, emailFrequency } = userInfo
if typeof username isnt 'string'
return callback new KodingError 'Username must be a string!'
# lower casing username is necessary to prevent conflicts with other JModels
username = username.toLowerCase()
email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
emailFrequencyDefaults = {
global : on
daily : off
privateMessage : on
followActions : off
comment : on
likeActivities : off
groupInvite : on
groupRequest : on
groupApproved : on
groupJoined : on
groupLeft : off
mention : on
marketing : on
}
# _.defaults doesnt handle undefined, extend handles correctly
emailFrequency = extend emailFrequencyDefaults, emailFrequency
slug =
slug : username
constructorName : 'JUser'
usedAsPath : 'username'
collectionName : 'jUsers'
JName.claim username, [slug], 'JUser', (err, nameDoc) ->
return callback err if err
salt = createSalt()
user = new JUser {
username
email
sanitizedEmail
salt
password : <PASSWORD>, <PASSWORD>
passwordStatus : passwordStatus or 'valid'
emailFrequency : emailFrequency
}
user.foreignAuth = foreignAuth if foreignAuth
user.save (err) ->
if err
nameDoc.remove?()
return if err.code is 11000
then callback new KodingError "Sorry, \"#{email}\" is already in use!"
else callback err
account = new JAccount
profile : {
nickname : username
hash : getHash email
firstName
lastName
}
account.save (err) ->
if err
user.remove?()
nameDoc.remove?()
callback err
else user.addOwnAccount account, (err) ->
if err then callback err
else callback null, user, account
@fetchUserByProvider = (provider, session, callback) ->
{ foreignAuth } = session
unless foreignAuth?[provider]?.foreignId
return callback new KodingError "No foreignAuth:#{provider} info in session"
query = {}
query["foreignAuth.#{provider}.foreignId"] = foreignAuth[provider].foreignId
JUser.one query, callback
@authenticateWithOauth = secure (client, resp, callback) ->
{ isUserLoggedIn, provider } = resp
{ sessionToken } = client
JSession.one { clientId: sessionToken }, (err, session) =>
return callback new KodingError err if err
unless session
{ connection: { delegate: { profile: { nickname } } } } = client
console.error 'authenticateWithOauth: session not found', nickname
return callback new KodingError 'Couldn\'t restore your session!'
kallback = (err, resp = {}) ->
{ account, replacementToken, returnUrl } = resp
callback err, {
isNewUser : false
userInfo : null
account
replacementToken
returnUrl
}
@fetchUserByProvider provider, session, (err, user) =>
return callback new KodingError err.message if err
if isUserLoggedIn
if user and user.username isnt client.connection.delegate.profile.nickname
@clearOauthFromSession session, ->
callback new KodingError '''
Account is already linked with another user.
'''
else
@fetchUser client, (err, user) =>
return callback new KodingError err.message if err
@persistOauthInfo user.username, sessionToken, kallback
else
if user
afterLogin user, sessionToken, session, kallback
else
return callback new KodingError 'Koding Solo registrations are closed!'
@validateAll = (userFormData, callback) ->
Validator = require './validators'
validator = new Validator
isError = no
errors = {}
queue = []
(key for key of validator).forEach (field) =>
queue.push (fin) => validator[field].call this, userFormData, (err) ->
if err?
errors[field] = err
isError = yes
fin()
async.parallel queue, ->
callback if isError
{ message: 'Errors were encountered during validation', errors }
else null
@changeEmailByUsername = (options, callback) ->
{ account, oldUsername, email } = options
# prevent from leading and trailing spaces
email = emailsanitize email
@update { username: oldUsername }, { $set: { email } }, (err, res) ->
return callback err if err
account.profile.hash = getHash email
account.save (err) -> console.error if err
callback null
@changeUsernameByAccount = (options, callback) ->
{ account, username, clientId, isRegistration, groupName } = options
account.changeUsername { username, isRegistration }, (err) ->
return callback err if err?
return callback null unless clientId?
newToken = createId()
JSession.one { clientId }, (err, session) ->
if err?
return callback new KodingError 'Could not update your session'
if session?
sessionUpdateOptions =
$set : { clientId : newToken, username, groupName }
$unset : { guestSessionBegan : 1 }
session.update sessionUpdateOptions, (err) ->
return callback err if err?
callback null, newToken
else
callback new KodingError 'Session not found!'
@removeFromGuestsGroup = (account, callback) ->
JGroup.one { slug: 'guests' }, (err, guestsGroup) ->
return callback err if err?
return callback new KodingError 'Guests group not found!' unless guestsGroup?
guestsGroup.removeMember account, callback
createGroupStack = (account, groupName, callback) ->
_client =
connection :
delegate : account
context :
group : groupName
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack for #{account.profile.nickname}:", err
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback()
verifyUser = (options, callback) ->
{ slug
email
recaptcha
disableCaptcha
userFormData
foreignAuthType } = options
queue = [
(next) ->
# verifying recaptcha if enabled
return next() if disableCaptcha or not KONFIG.recaptcha.enabled
JUser.verifyRecaptcha recaptcha, { foreignAuthType, slug }, next
(next) ->
JUser.validateAll userFormData, next
(next) ->
JUser.emailAvailable email, (err, res) ->
if err
return next new KodingError 'Something went wrong'
if res is no
return next new KodingError 'Email is already in use!'
next()
]
async.series queue, callback
createUser = (options, callback) ->
{ userInfo } = options
# creating a new user
JUser.createUser userInfo, (err, user, account) ->
return callback err if err
unless user? and account?
return callback new KodingError 'Failed to create user!'
callback null, { user, account }
updateUserInfo = (options, callback) ->
{ user, ip, country, region, username,
client, account, clientId, password } = options
newToken = null
queue = [
(next) ->
# updating user's location related info
return next() unless ip? and country? and region?
locationModifier =
$set :
'registeredFrom.ip' : ip
'registeredFrom.region' : region
'registeredFrom.country' : country
user.update locationModifier, ->
next()
(next) ->
JUser.persistOauthInfo username, client.sessionToken, next
(next) ->
return next() unless username?
_options =
account : account
username : username
clientId : clientId
groupName : client.context.group
isRegistration : yes
JUser.changeUsernameByAccount _options, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
user.setPassword password, next
]
async.series queue, (err) ->
return callback err if err
callback null, newToken
updateAccountInfo = (options, callback) ->
{ account, referrer, username } = options
queue = [
(next) ->
account.update { $set: { type: 'registered' } }, next
(next) ->
account.createSocialApiId next
(next) ->
# setting referrer
return next() unless referrer
if username is referrer
console.error "User (#{username}) tried to refer themself."
return next()
JUser.count { username: referrer }, (err, count) ->
if err? or count < 1
console.error 'Provided referrer not valid:', err
return next()
account.update { $set: { referrerUsername: referrer } }, (err) ->
if err?
then console.error err
else console.log "#{referrer} referred #{username}"
next()
]
async.series queue, callback
createDefaultStackForKodingGroup = (options, callback) ->
{ account } = options
# create default stack for koding group, when a user joins this is only
# required for koding group, not neeed for other teams
_client =
connection :
delegate : account
context :
group : 'koding'
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack
for #{account.profile.nickname}:#{err}"
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback null
confirmAccountIfNeeded = (options, callback) ->
{ user, email, username, group } = options
if KONFIG.autoConfirmAccounts or group isnt 'koding'
user.confirmEmail (err) ->
console.warn err if err?
return callback err
else
_options =
email : email
action : 'verify-account'
username : username
JVerificationToken = require '../verificationtoken'
JVerificationToken.createNewPin _options, (err, confirmation) ->
console.warn 'Failed to send verification token:', err if err
callback err, confirmation?.pin
validateConvert = (options, callback) ->
{ client, userFormData, foreignAuthType, skipAllowedDomainCheck } = options
{ slug, email, invitationToken, recaptcha, disableCaptcha } = userFormData
invitation = null
queue = [
(next) ->
params = { slug, email, recaptcha, disableCaptcha, userFormData, foreignAuthType }
verifyUser params, next
(next) ->
params = {
groupName : client.context.group
invitationToken, skipAllowedDomainCheck, email
}
JUser.verifyEnrollmentEligibility params, (err, res) ->
return next err if err
{ isEligible, invitation } = res
if not isEligible
return next new Error "you can not register to #{client.context.group}"
next()
]
async.series queue, (err) ->
return callback err if err
callback null, { invitation }
processConvert = (options, callback) ->
{ ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck } = options
{ sessionToken : clientId } = client
{ referrer, email, username, password,
emailFrequency, firstName, lastName } = userFormData
user = null
error = null
account = null
newToken = null
queue = [
(next) ->
userInfo = {
email, username, password, lastName, firstName, emailFrequency
}
createUser { userInfo }, (err, data) ->
return next err if err
{ user, account } = data
next()
(next) ->
params = {
user, ip, country, region, username
password, clientId, account, client
}
updateUserInfo params, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
updateAccountInfo { account, referrer, username }, next
(next) ->
groupNames = [client.context.group, 'koding']
options = { skipAllowedDomainCheck }
JUser.addToGroups account, groupNames, user.email, invitation, options, (err) ->
error = err
next()
(next) ->
createDefaultStackForKodingGroup { account }, next
]
async.series queue, (err) ->
return callback err if err
# passing "error" variable to be used as an argument in the callback func.
# that is being called after registration process is completed.
callback null, { error, newToken, user, account }
@convert = secure (client, userFormData, options, callback) ->
[options, callback] = [{}, options] unless callback
{ slug, email, agree, username, lastName, referrer,
password, firstName, recaptcha, emailFrequency,
invitationToken, passwordConfirm, disableCaptcha } = userFormData
{ skipAllowedDomainCheck } = options
{ clientIP, connection } = client
{ delegate : account } = connection
{ nickname : oldUsername } = account.profile
# if firstname is not received use username as firstname
userFormData.firstName = username unless firstName
userFormData.lastName = '' unless lastName
if error = validateConvertInput userFormData, client
return callback error
# lower casing username is necessary to prevent conflicts with other JModels
username = userFormData.username = username.toLowerCase()
email = userFormData.email = emailsanitize email
if clientIP
{ ip, country, region } = Regions.findLocation clientIP
pin = null
user = null
error = null
newToken = null
invitation = null
foreignAuthType = null
subscription = null
queue = [
(next) =>
@extractOauthFromSession client.sessionToken, (err, foreignAuthInfo) ->
if err
console.log 'Error while getting oauth data from session', err
return next()
return next() unless foreignAuthInfo
# Password is not required for GitHub users since they are authorized via GitHub.
# To prevent having the same password for all GitHub users since it may be
# a security hole, let's auto generate it if it's not provided in request
unless password
password = userFormData.password = <PASSWORD>()
passwordConfirm = userFormData.passwordConfirm = password
next()
(next) ->
options = { client, userFormData, foreignAuthType, skipAllowedDomainCheck }
validateConvert options, (err, data) ->
return next err if err
{ invitation } = data
next()
(next) ->
params = {
ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck
}
processConvert params, (err, data) ->
return next err if err
{ error, newToken, user, account } = data
next()
(next) ->
date = new Date 0
subscription =
accountId : account.getId()
planTitle : 'free'
planInterval : 'month'
state : 'active'
provider : 'koding'
expiredAt : date
canceledAt : date
currentPeriodStart : date
currentPeriodEnd : date
args = { user, account, subscription, pin, oldUsername }
identifyUserOnRegister disableCaptcha, args
JUser.emit 'UserRegistered', { user, account }
next()
(next) ->
# Auto confirm accounts for development environment or Teams ~ GG
args = { group : client.context.group, user, email, username }
confirmAccountIfNeeded args, (err, pin_) ->
pin = pin_
next err
]
async.series queue, (err) ->
return callback err if err
# don't block register
callback error, { account, newToken, user }
group = client.context.group
args = { user, group, pin, <NAME>, <NAME> }
trackUserOnRegister disableCaptcha, args
SiftScience = require '../siftscience'
SiftScience.createAccount client, referrer, ->
identifyUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
{ user, account, subscription, pin, oldUsername } = args
{ status, lastLoginDate, username, email } = user
{ createdAt, profile } = account.meta
{ <NAME>, <NAME> } = account.profile
jwtToken = JUser.createJWT { username }
sshKeysCount = user.sshKeys.length
emailFrequency =
global : user.emailFrequency.global
marketing : user.emailFrequency.marketing
traits = {
email
createdAt
lastLoginDate
status
<NAME>
<NAME>
subscription
sshKeysCount
emailFrequency
pin
jwtToken
}
Tracker.identify username, traits
Tracker.alias oldUsername, username
trackUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
subject = Tracker.types.START_REGISTER
{ user, group, pin, <NAME>, <NAME> } = args
{ username, email } = user
opts = { pin, group, user : { user_id : username, email, <NAME>, <NAME> } }
Tracker.track username, { to : email, subject }, opts
@createJWT: (data, options = {}) ->
{ secret, confirmExpiresInMinutes } = KONFIG.jwt
jwt = require 'jsonwebtoken'
# uses 'HS256' as default for signing
options.expiresInMinutes ?= confirmExpiresInMinutes
return jwt.sign data, secret, options
@removeUnsubscription:({ email }, callback) ->
JUnsubscribedMail = require '../unsubscribedmail'
JUnsubscribedMail.one { email }, (err, unsubscribed) ->
return callback err if err or not unsubscribed
unsubscribed.remove callback
@grantInitialInvitations = (username) ->
JInvitation.grant { 'profile.nickname': username }, 3, (err) ->
console.log 'An error granting invitations', err if err
@fetchUser = secure (client, callback) ->
JSession.one { clientId: client.sessionToken }, (err, session) ->
return callback err if err
noUserError = -> new KodingError \
'No user found! Not logged in or session expired'
if not session or not session.username
return callback noUserError()
JUser.one { username: session.username }, (err, user) ->
if err or not user
console.log '[JUser::fetchUser]', err if err?
callback noUserError()
else
callback null, user
@changePassword = secure (client, password, callback) ->
@fetchUser client, (err, user) ->
if err or not user
return callback new KodingError \
'Something went wrong please try again!'
if user.getAt('password') is hashPassword password, user.getAt('salt')
return callback new KodingError 'PasswordIsSame'
user.changePassword password, (err) ->
return callback err if err
account = client.connection.delegate
clientId = client.sessionToken
account.sendNotification 'SessionHasEnded', { clientId }
selector = { clientId: { $ne: client.sessionToken } }
user.killSessions selector, callback
sendChangedEmail = (username, <NAME>, to, type) ->
subject = if type is 'email' then Tracker.types.CHANGED_EMAIL
else Tracker.types.CHANGED_PASSWORD
Tracker.track username, { to, subject }, { firstName }
@changeEmail = secure (client, options, callback) ->
{ email } = options
email = options.email = emailsanitize email
account = client.connection.delegate
account.fetchUser (err, user) =>
return callback new KodingError 'Something went wrong please try again!' if err
return callback new KodingError 'EmailIsSameError' if email is user.email
@emailAvailable email, (err, res) ->
return callback new KodingError 'Something went wrong please try again!' if err
if res is no
callback new KodingError 'Email is already in use!'
else
user.changeEmail account, options, callback
@emailAvailable = (email, callback) ->
unless typeof email is 'string'
return callback new KodingError 'Not a valid email!'
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
@count { sanitizedEmail }, (err, count) ->
callback err, count is 0
@getValidUsernameLengthRange = -> { minLength : 4, maxLength : 25 }
@usernameAvailable = (username, callback) ->
JName = require '../name'
username += ''
res =
kodingUser : no
forbidden : yes
JName.count { name: username }, (err, count) =>
{ minLength, maxLength } = JUser.getValidUsernameLengthRange()
if err or username.length < minLength or username.length > maxLength
callback err, res
else
res.kodingUser = count is 1
res.forbidden = username in @bannedUserList
callback null, res
fetchAccount: (context, rest...) -> @fetchOwnAccount rest...
setPassword: (password, callback) ->
salt = createSalt()
@update {
$set :
salt : salt
password : <PASSWORD>, salt
passwordStatus : 'valid'
}, callback
changePassword: (newPassword, callback) ->
@setPassword newPassword, (err) =>
return callback err if err
@fetchAccount 'koding', (err, account) =>
return callback err if err
return callback new KodingError 'Account not found' unless account
{ firstName } = account.profile
sendChangedEmail @getAt('username'), firstName, @getAt('email'), 'password'
callback null
changeEmail: (account, options, callback) ->
JVerificationToken = require '../verificationtoken'
{ email, pin } = options
email = options.email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
if account.type is 'unregistered'
@update { $set: { email , sanitizedEmail } }, (err) ->
return callback err if err
callback null
return
action = 'update-email'
if not pin
options = {
email, action, user: this, resendIfExists: yes
}
JVerificationToken.requestNewPin options, callback
else
options = {
email, action, pin, username: @getAt 'username'
}
JVerificationToken.confirmByPin options, (err, confirmed) =>
return callback err if err
unless confirmed
return callback new KodingError 'PIN is not confirmed.'
oldEmail = @getAt 'email'
@update { $set: { email, sanitizedEmail } }, (err, res) =>
return callback err if err
account.profile.hash = getHash email
account.save (err) =>
return callback err if err
{ firstName } = account.profile
# send EmailChanged event
@constructor.emit 'EmailChanged', {
username: @getAt('username')
oldEmail: oldEmail
newEmail: email
}
sendChangedEmail @getAt('username'), firstName, oldEmail, 'email'
callback null
Tracker.identify @username, { email }
fetchHomepageView: (options, callback) ->
{ account, bongoModels } = options
@fetchAccount 'koding', (err, account) ->
return callback err if err
return callback new KodingError 'Account not found' unless account
account.fetchHomepageView options, callback
confirmEmail: (callback) ->
status = @getAt 'status'
username = @getAt 'username'
# for some reason status is sometimes 'undefined', so check for that
if status? and status isnt 'unconfirmed'
return callback null
modifier = { status: 'confirmed' }
@update { $set: modifier }, (err, res) =>
return callback err if err
JUser.emit 'EmailConfirmed', this
callback null
Tracker.identify username, modifier
Tracker.track username, { subject: Tracker.types.FINISH_REGISTER }
block: (blockedUntil, callback) ->
unless blockedUntil then return callback new KodingError 'Blocking date is not defined'
status = 'blocked'
@update { $set: { status, blockedUntil } }, (err) =>
return callback err if err
JUser.emit 'UserBlocked', this
console.log 'JUser#block JSession#remove', { @username, blockedUntil }
# clear all of the cookies of the blocked user
JSession.remove { username: @username }, callback
Tracker.identify @username, { status }
unblock: (callback) ->
status = 'confirmed'
op =
$set : { status }
$unset : { blockedUntil: yes }
@update op, (err) =>
return callback err if err
JUser.emit 'UserUnblocked', this
callback()
Tracker.identify @username, { status }
unlinkOAuths: (callback) ->
@update { $unset: { foreignAuth:1 , foreignAuthType:1 } }, (err) =>
return callback err if err
@fetchOwnAccount (err, account) ->
return callback err if err
account.unstoreAll callback
@persistOauthInfo: (username, clientId, callback) ->
@extractOauthFromSession clientId, (err, foreignAuthInfo) =>
return callback err if err
return callback null unless foreignAuthInfo
return callback null unless foreignAuthInfo.session
@saveOauthToUser foreignAuthInfo, username, (err) =>
return callback err if err
do (foreignAuth = {}) ->
{ foreignAuthType } = foreignAuthInfo
foreignAuth[foreignAuthType] = yes
Tracker.identify username, { foreignAuth }
@clearOauthFromSession foreignAuthInfo.session, (err) =>
return callback err if err
@copyPublicOauthToAccount username, foreignAuthInfo, (err, resp = {}) ->
return callback err if err
{ session: { returnUrl } } = foreignAuthInfo
resp.returnUrl = returnUrl if returnUrl
return callback null, resp
@extractOauthFromSession: (clientId, callback) ->
JSession.one { clientId: clientId }, (err, session) ->
return callback err if err
return callback null unless session
{ foreignAuth, foreignAuthType } = session
if foreignAuth and foreignAuthType
callback null, { foreignAuth, foreignAuthType, session }
else
callback null # WARNING: don't assume it's an error if there's no foreignAuth
@saveOauthToUser: ({ foreignAuth, foreignAuthType }, username, callback) ->
query = {}
query["foreignAuth.#{foreignAuthType}"] = foreignAuth[foreignAuthType]
@update { username }, { $set: query }, callback
@clearOauthFromSession: (session, callback) ->
session.update { $unset: { foreignAuth:1, foreignAuthType:1 } }, callback
@copyPublicOauthToAccount: (username, { foreignAuth, foreignAuthType }, callback) ->
JAccount.one { 'profile.nickname' : username }, (err, account) ->
return callback err if err
name = "ext|profile|#{foreignAuthType}"
content = foreignAuth[foreignAuthType].profile
account._store { name, content }, callback
@setSSHKeys: secure (client, sshKeys, callback) ->
@fetchUser client, (err, user) ->
user.sshKeys = sshKeys
user.save callback
Tracker.identify user.username, { sshKeysCount: sshKeys.length }
@getSSHKeys: secure (client, callback) ->
@fetchUser client, (err, user) ->
return callback user?.sshKeys or []
###*
* Compare provided password with JUser.password
*
* @param {string} password
###
checkPassword: (password) ->
# hash of given password and given user's salt should match with user's password
return @getAt('password') is hashPassword password, @getAt('salt')
###*
* Compare provided verification token with time
* based generated 2Factor code. If 2Factor not enabled returns true
*
* @param {string} verificationCode
###
check2FactorAuth: (verificationCode) ->
key = @getAt 'twofactorkey'
speakeasy = require 'speakeasy'
generatedKey = speakeasy.totp { key, encoding: 'base32' }
return generatedKey is verificationCode
###*
* Verify if `response` from client is valid by asking recaptcha servers.
* Check is disabled in dev mode or when user is authenticating via `github`.
*
* @param {string} response
* @param {string} foreignAuthType
* @param {function} callback
###
@verifyRecaptcha = (response, params, callback) ->
{ url, secret } = KONFIG.recaptcha
{ foreignAuthType, slug } = params
return callback null if foreignAuthType is 'github'
# TODO: temporarily disable recaptcha for groups
if slug? and slug isnt 'koding'
return callback null
request.post url, { form: { response, secret } }, (err, res, raw) ->
if err
console.log "Recaptcha: err validation captcha: #{err}"
if not err and res.statusCode is 200
try
if JSON.parse(raw)['success']
return callback null
catch e
console.log "Recaptcha: parsing response failed. #{raw}"
return callback new KodingError 'Captcha not valid. Please try again.'
###*
* Remove session documents matching selector object.
*
* @param {Object} [selector={}] - JSession query selector.
* @param {Function} - Callback.
###
killSessions: (selector = {}, callback) ->
selector.username = @username
JSession.remove selector, callback
| true | async = require 'async'
jraphical = require 'jraphical'
Regions = require 'koding-regions'
request = require 'request'
KONFIG = require 'koding-config-manager'
Flaggable = require '../../traits/flaggable'
KodingError = require '../../error'
emailsanitize = require './emailsanitize'
{ extend, uniq } = require 'underscore'
{ protocol, hostname } = KONFIG
module.exports = class JUser extends jraphical.Module
{ v4: createId } = require 'node-uuid'
{ Relationship } = jraphical
{ secure, signature } = require 'bongo'
JAccount = require '../account'
JSession = require '../session'
JInvitation = require '../invitation'
JName = require '../name'
JGroup = require '../group'
JLog = require '../log'
ComputeProvider = require '../computeproviders/computeprovider'
Tracker = require '../tracker'
Payment = require '../payment'
@bannedUserList = ['abrt', 'amykhailov', 'apache', 'about', 'visa', 'shared-',
'cthorn', 'daemon', 'dbus', 'dyasar', 'ec2-user', 'http',
'games', 'ggoksel', 'gopher', 'haldaemon', 'halt', 'mail',
'nfsnobody', 'nginx', 'nobody', 'node', 'operator', 'https',
'root', 'rpcuser', 'saslauth', 'shutdown', 'sinanlocal',
'sshd', 'sync', 'tcpdump', 'uucp', 'vcsa', 'zabbix',
'search', 'blog', 'activity', 'guest', 'credits', 'about',
'kodingen', 'alias', 'backup', 'bin', 'bind', 'daemon',
'Debian-exim', 'dhcp', 'drweb', 'games', 'gnats', 'klog',
'kluser', 'libuuid', 'list', 'mhandlers-user', 'more',
'mysql', 'nagios', 'news', 'nobody', 'popuser', 'postgres',
'proxy', 'psaadm', 'psaftp', 'qmaild', 'qmaill', 'qmailp',
'qmailq', 'qmailr', 'qmails', 'sshd', 'statd', 'sw-cp-server',
'sync', 'syslog', 'tomcat', 'tomcat55', 'uucp', 'what',
'www-data', 'fuck', 'porn', 'p0rn', 'porno', 'fucking',
'fucker', 'admin', 'postfix', 'puppet', 'main', 'invite',
'administrator', 'members', 'register', 'activate', 'shared',
'groups', 'blogs', 'forums', 'topics', 'develop', 'terminal',
'term', 'twitter', 'facebook', 'google', 'framework', 'kite',
'landing', 'hello', 'dev', 'sandbox', 'latest',
'all', 'channel', 'admins', 'group', 'team'
]
hashPassword = (value, salt) ->
require('crypto').createHash('sha1').update(salt + value).digest('hex')
createSalt = require 'hat'
rack = createSalt.rack 64
@share()
@trait __dirname, '../../traits/flaggable'
@getFlagRole = -> 'owner'
@set
softDelete : yes
broadcastable : no
indexes :
username : 'unique'
email : 'unique'
sanitizedEmail: ['unique', 'sparse']
'foreignAuth.github.foreignId' : 'ascending'
'foreignAuth.facebook.foreignId' : 'ascending'
'foreignAuth.google.foreignId' : 'ascending'
'foreignAuth.linkedin.foreignId' : 'ascending'
'foreignAuth.twitter.foreignId' : 'ascending'
sharedEvents :
# do not share any events
static : []
instance : []
sharedMethods :
# do not share any instance methods
# instances :
static :
login : (signature Object, Function)
whoami : (signature Function)
logout : (signature Function)
convert : (signature Object, Function)
fetchUser : (signature Function)
setSSHKeys : (signature [Object], Function)
getSSHKeys : (signature Function)
unregister : (signature String, Function)
verifyByPin : (signature Object, Function)
changeEmail : (signature Object, Function)
verifyPassword : (signature Object, Function)
emailAvailable : (signature String, Function)
changePassword : (signature String, Function)
usernameAvailable : (signature String, Function)
authenticateWithOauth : (signature Object, Function)
isRegistrationEnabled : (signature Function)
schema :
username :
type : String
validate : JName.validateName
set : (value) -> value.toLowerCase()
oldUsername : String
uid :
type : Number
set : Math.floor
email :
type : String
validate : JName.validateEmail
set : emailsanitize
sanitizedEmail:
type : String
validate : JName.validateEmail
set : (value) ->
return unless typeof value is 'string'
emailsanitize value, { excludeDots: yes, excludePlus: yes }
password : String
salt : String
twofactorkey : String
blockedUntil : Date
blockedReason : String
status :
type : String
enum : [
'invalid status type', [
'unconfirmed', 'confirmed', 'blocked', 'deleted'
]
]
default : 'unconfirmed'
passwordStatus:
type : String
enum : [
'invalid password status type', [
'needs reset', 'needs set', 'valid', 'autogenerated'
]
]
default : 'valid'
registeredAt :
type : Date
default : -> new Date
registeredFrom:
ip : String
country : String
region : String
lastLoginDate :
type : Date
default : -> new Date
# store fields for janitor worker. see go/src/koding/db/models/user.go for more details.
inactive : Object
# stores user preference for how often email should be sent.
# see go/src/koding/db/models/user.go for more details.
emailFrequency: Object
onlineStatus :
actual :
type : String
enum : ['invalid status', ['online', 'offline']]
default : 'online'
userPreference:
type : String
# enum : ['invalid status',['online','offline','away','busy']]
sshKeys :
type : Object
default : []
foreignAuth :
github :
foreignId : String
username : String
token : String
firstName : String
lastName : String
email : String
scope : String
facebook :
foreignId : String
username : String
token : String
linkedin :
foreignId : String
relationships :
ownAccount :
targetType : JAccount
as : 'owner'
sessions = {}
users = {}
guests = {}
@unregister = secure (client, toBeDeletedUsername, callback) ->
{ delegate } = client.connection
{ nickname } = delegate.profile
console.log "#{nickname} requested to delete: #{toBeDeletedUsername}"
# deleter should be registered one
if delegate.type is 'unregistered'
return callback new KodingError 'You are not registered!'
# only owner and the dummy admins can delete a user
unless toBeDeletedUsername is nickname or
delegate.can 'administer accounts'
return callback new KodingError 'You must confirm this action!'
username = @createGuestUsername()
# Adding -rm suffix to separate them from real guests
# -rm was intentional otherwise we are exceeding the max username length
username = "#{username}-rm"
# Why we do have such thing? ~ GG
email = PI:EMAIL:<EMAIL>END_PI"
@one { username: toBeDeletedUsername }, (err, user) ->
return callback err if err?
unless user
return callback new KodingError \
"User not found #{toBeDeletedUsername}"
userValues = {
email : email
sanitizedEmail : email
# here we have a trick, emailBeforeDeletion is not in the schema but we
# are setting it to the db. it is not in the schema because we dont want
# it to be seen in the codebase and it wont be mapped to a JUser
emailBeforeDeletion : user.email
status : 'deleted'
sshKeys : []
username : username
password : createId()
foreignAuth : {}
onlineStatus : 'offline'
registeredAt : new Date 0
lastLoginDate : new Date 0
passwordStatus : 'PI:PASSWORD:<PASSWORD>END_PI'
emailFrequency : {}
}
modifier = { $set: userValues, $unset: { oldUsername: 1 } }
# update the user with empty data
user.update modifier, updateUnregisteredUserAccount({
user, username, toBeDeletedUsername, client
}, callback)
@isRegistrationEnabled = (callback) ->
JRegistrationPreferences = require '../registrationpreferences'
JRegistrationPreferences.one {}, (err, prefs) ->
callback err? or prefs?.isRegistrationEnabled or no
@authenticateClient: (clientId, callback) ->
logError = (message, rest...) ->
console.error "[JUser::authenticateClient] #{message}", rest...
logout = (reason, clientId, callback) =>
@logout clientId, (err) ->
logError reason, clientId
callback new KodingError reason
# Let's try to lookup provided session first
JSession.one { clientId }, (err, session) ->
if err
# This is a very rare state here
logError 'error finding session', { err, clientId }
callback new KodingError err
else unless session?
# We couldn't find the session with given token
# so we are creating a new one now.
JSession.createSession (err, { session, account }) ->
if err?
logError 'failed to create session', { err }
callback err
else
# Voila session created and sent back, scenario #1
callback null, { session, account }
else
# So we have a session, let's check it out if its a valid one
checkSessionValidity { session, logout, clientId }, callback
@getHash = getHash = (value) ->
require('crypto').createHash('md5').update(value.toLowerCase()).digest('hex')
@whoami = secure ({ connection:{ delegate } }, callback) -> callback null, delegate
@getBlockedMessage = (toDate) ->
return """
This account has been put on suspension due to a violation of our acceptable use policy. The ban will be in effect until <b>#{toDate}.</b><br><br>
If you have any questions, please email <a class="ban" href='mailto:PI:EMAIL:<EMAIL>END_PI}'>PI:EMAIL:<EMAIL>END_PI}</a> and allow 2-3 business days for a reply. Even though your account is banned, all your data is safe.<br><br>
Please note, repeated violations of our acceptable use policy will result in the permanent deletion of your account.<br><br>
PI:NAME:<NAME>END_PI
"""
checkBlockedStatus = (user, callback) ->
return callback null if user.status isnt 'blocked'
if user.blockedUntil and user.blockedUntil > new Date
toDate = user.blockedUntil.toUTCString()
message = JUser.getBlockedMessage toDate
callback new KodingError message
else
user.unblock callback
@normalizeLoginId = (loginId, callback) ->
if /@/.test loginId
email = emailsanitize loginId
JUser.someData { email }, { username: 1 }, (err, cursor) ->
return callback err if err
cursor.nextObject (err, data) ->
return callback err if err?
return callback new KodingError 'Unrecognized email' unless data?
callback null, data.username
else
process.nextTick -> callback null, loginId
@login$ = secure (client, credentials, callback) ->
{ sessionToken : clientId, connection } = client
@login clientId, credentials, (err, response) ->
return callback err if err
connection.delegate = response.account
callback null, response
fetchSession = (options, callback) ->
{ clientId, username } = options
# fetch session of the current requester
JSession.fetchSession clientId, (err, { session: fetchedSession }) ->
return callback err if err
session = fetchedSession
unless session
console.error "login: session not found #{username}"
return callback new KodingError 'Couldn\'t restore your session!'
callback null, session
validateLoginCredentials = (options, callback) ->
{ username, password, tfcode } = options
# check credential validity
JUser.one { username }, (err, user) ->
return logAndReturnLoginError username, err.message, callback if err
# if user not found it means we dont know about given username
unless user?
return logAndReturnLoginError username, 'Unknown user name', callback
# if password is autogenerated return error
if user.getAt('passwordStatus') is 'needs reset'
return logAndReturnLoginError username, \
'You should reset your password in order to continue!', callback
# check if provided password is correct
unless user.checkPassword password
return logAndReturnLoginError username, 'Access denied!', callback
# check if user is using 2factor auth and provided key is ok
if !!(user.getAt 'twofactorkey')
unless tfcode
return callback new KodingError \
'TwoFactor auth Enabled', 'VERIFICATION_CODE_NEEDED'
unless user.check2FactorAuth tfcode
return logAndReturnLoginError username, 'Access denied!', callback
# if everything is fine, just continue
callback null, user
fetchInvitationByCode = (invitationToken, callback) ->
JInvitation = require '../invitation'
JInvitation.byCode invitationToken, (err, invitation) ->
return callback err if err
return callback new KodingError 'invitation is not valid' unless invitation
callback null, invitation
fetchInvitationByData = (options, callback) ->
{ user, groupName } = options
selector = { email: user.email, groupName }
JInvitation = require '../invitation'
JInvitation.one selector, {}, (err, invitation) ->
callback err, invitation
validateLogin = (options, callback) ->
{ loginId, clientId, password, tfcode } = options
username = null
async.series {
username: (next) ->
JUser.normalizeLoginId loginId, (err, username_) ->
username = username_?.toLowerCase?() or ''
next err, username
# fetch session and check for brute force attack
session: (next) ->
fetchSession { clientId, username }, (err, session) ->
return next err if err
bruteForceControlData =
ip : session.clientIP
username : username
# todo add alert support(mail, log etc)
JLog.checkLoginBruteForce bruteForceControlData, (res) ->
unless res
return next new KodingError \
"Your login access is blocked for #{JLog.timeLimit()} minutes."
next null, session
user: (next) ->
validateLoginCredentials { username, password, tfcode }, (err, user) ->
next err, user
}, callback
@login = (clientId, credentials, callback) ->
{ username: loginId, password, groupIsBeingCreated
groupName, tfcode, invitationToken } = credentials
user = null
session = null
account = null
username = null
groupName ?= 'koding'
invitation = null
queue = [
(next) ->
args = { loginId, clientId, password, tfcode }
validateLogin args, (err, data) ->
return next err if err
{ username, user, session } = data
next()
(next) ->
# fetch account of the user, we will use it later
JAccount.one { 'profile.nickname' : username }, (err, account_) ->
return next new KodingError 'couldn\'t find account!' if err
account = account_
next()
(next) ->
{ isSoloAccessible } = require './validators'
opts =
groupName: groupName
account: account
env: KONFIG.environment
return next() if isSoloAccessible opts
next new Error 'You can not login to koding team, please use your own team'
(next) ->
# if we dont have an invitation code, do not continue
return next() unless invitationToken
# check if user can access to group
#
# there can be two cases here
# # user is member, check validity
# # user is not member, and trying to access with invitationToken
# both should succeed
fetchInvitationByCode invitationToken, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) ->
# check if user has pending invitation
return next() if invitationToken
fetchInvitationByData { user, groupName }, (err, invitation_) ->
return next err if err
invitation = invitation_
next()
(next) =>
return next() if groupIsBeingCreated
@addToGroupByInvitation { groupName, account, user, invitation }, next
(next) ->
return next() if groupIsBeingCreated
# we are sure that user can access to the group, set group name into
# cookie while logging in
session.update { $set : { groupName } }, next
]
async.series queue, (err) ->
return callback err if err
# continue login
afterLogin user, clientId, session, (err, response) ->
return callback err if err
callback err, response
@verifyPassword = secure (client, options, callback) ->
{ password, email } = options
{ connection : { delegate } } = client
email = emailsanitize email if email
# handles error and decide to invalidate pin or not
# depending on email and user variables
handleError = (err, user) ->
if email and user
# when email and user is set, we need to invalidate verification token
params =
email : email
action : 'update-email'
username : user.username
JVerificationToken = require '../verificationtoken'
JVerificationToken.invalidatePin params, (err) ->
return console.error 'Pin invalidation error occurred', err if err
callback err, no
# fetch user for invalidating created token
@fetchUser client, (err, user) ->
return handleError err if err
if not password or password is ''
return handleError new KodingError('Password cannot be empty!'), user
confirmed = user.getAt('password') is hashPassword password, user.getAt('salt')
return callback null, yes if confirmed
return handleError null, user
verifyByPin: (options, callback) ->
if (@getAt 'status') is 'confirmed'
return callback null
JVerificationToken = require '../verificationtoken'
{ pin, resendIfExists } = options
email = @getAt 'email'
username = @getAt 'username'
options = {
user : this
action : 'verify-account'
resendIfExists, pin, username, email
}
unless pin?
JVerificationToken.requestNewPin options, (err) -> callback err
else
JVerificationToken.confirmByPin options, (err, confirmed) =>
if err
callback err
else if confirmed
@confirmEmail callback
else
callback new KodingError 'PIN is not confirmed.'
@verifyByPin = secure (client, options, callback) ->
account = client.connection.delegate
account.fetchUser (err, user) ->
return callback new Error 'User not found' unless user
user.verifyByPin options, callback
@addToGroupByInvitation = (options, callback) ->
{ groupName, account, user, invitation } = options
# check for membership
JGroup.one { slug: groupName }, (err, group) ->
return callback new KodingError err if err
return callback new KodingError 'group doesnt exist' if not group
group.isMember account, (err, isMember) ->
return callback err if err
return callback null if isMember # if user is already member, we can continue
# addGroup will check all prerequistes about joining to a group
JUser.addToGroup account, groupName, user.email, invitation, callback
redeemInvitation = (options, callback) ->
{ account, invitation, slug, email } = options
return invitation.accept account, callback if invitation
JInvitation.one { email, groupName : slug }, (err, invitation_) ->
# if we got error or invitation doesnt exist, just return
return callback null if err or not invitation_
return invitation_.accept account, callback
# check if user's email domain is in allowed domains
checkWithDomain = (groupName, email, callback) ->
JGroup.one { slug: groupName }, (err, group) ->
return callback err if err
# yes weird, but we are creating user before creating group
return callback null, { isEligible: yes } if not group
unless group.isInAllowedDomain email
domainErr = 'Your email domain is not in allowed domains for this group'
return callback new KodingError domainErr if group.allowedDomains?.length > 0
return callback new KodingError 'You are not allowed to access this team'
return callback null, { isEligible: yes }
checkSessionValidity = (options, callback) ->
{ session, logout, clientId } = options
{ username } = session
unless username?
# A session without a username is nothing, let's kill it
# and logout the user, this is also a rare condition
logout 'no username found', clientId, callback
return
# If we are dealing with a guest session we know that we need to
# use fake guest user
if /^guest-/.test username
JUser.fetchGuestUser (err, response) ->
return logout 'error fetching guest account' if err
{ account } = response
return logout 'guest account not found' if not response?.account
account.profile.nickname = username
return callback null, { account, session }
return
JUser.one { username }, (err, user) ->
if err?
logout 'error finding user with username', clientId, callback
else unless user?
logout "no user found with #{username} and sessionId", clientId, callback
else
context = { group: session?.groupName ? 'koding' }
user.fetchAccount context, (err, account) ->
if err?
logout 'error fetching account', clientId, callback
else
# A valid session, a valid user attached to
# it voila, scenario #2
callback null, { session, account }
updateUnregisteredUserAccount = (options, callback) ->
{ username : usernameAfterDelete, toBeDeletedUsername, user, client } = options
return (err, docs) ->
return callback err if err?
accountValues = {
type : 'deleted'
skillTags : []
ircNickame : ''
globalFlags : ['deleted']
locationTags : []
onlineStatus : 'offline'
'profile.about' : ''
'profile.hash' : getHash createId()
'profile.avatar' : ''
'profile.nickname' : usernameAfterDelete
'profile.lastName' : 'PI:NAME:<NAME>END_PI'
'profile.firstName' : 'PI:NAME:<NAME>END_PI'
'profile.experience' : ''
'profile.experiencePoints': 0
'profile.lastStatusUpdate': ''
}
params = { 'profile.nickname' : toBeDeletedUsername }
JAccount.one params, (err, account) ->
return callback err if err?
unless account
return callback new KodingError \
"Account not found #{toBeDeletedUsername}"
# update the account to be deleted with empty data
account.update { $set: accountValues }, (err) ->
return callback err if err?
JName.release toBeDeletedUsername, (err) ->
return callback err if err?
JAccount.emit 'UsernameChanged', {
oldUsername : toBeDeletedUsername
isRegistration : false
username : usernameAfterDelete
}
user.unlinkOAuths ->
Payment = require '../payment'
deletedClient = { connection: { delegate: account } }
Payment.deleteAccount deletedClient, (err) ->
account.leaveFromAllGroups client, ->
JUser.logout deletedClient, callback
validateConvertInput = (userFormData, client) ->
{ username
password
passwordConfirm } = userFormData
{ connection } = client
{ delegate : account } = connection
# only unregistered accounts can be "converted"
if account.type is 'registered'
return new KodingError 'This account is already registered.'
if /^guest-/.test username
return new KodingError 'Reserved username!'
if username is 'guestuser'
return new KodingError 'Reserved username: \'guestuser\'!'
if password isnt passwordConfirm
return new KodingError 'Passwords must match!'
unless typeof username is 'string'
return new KodingError 'Username must be a string!'
return null
logAndReturnLoginError = (username, error, callback) ->
JLog.log { type: 'login', username: username, success: no }, ->
callback new KodingError error
updateUserPasswordStatus = (user, callback) ->
# let user log in for the first time, than set password status
# as 'needs reset'
if user.passwordStatus is 'needs set'
user.update { $set : { passwordStatus : 'needs reset' } }, callback
else
callback null
afterLogin = (user, clientId, session, callback) ->
{ username } = user
account = null
replacementToken = null
queue = [
(next) ->
# fetching account, will be used to check login constraints of user
user.fetchOwnAccount (err, account_) ->
return next err if err
account = account_
next()
(next) ->
# checking login constraints
checkBlockedStatus user, next
(next) ->
# updating user passwordStatus if necessary
updateUserPasswordStatus user, (err) ->
return next err if err
replacementToken = createId()
next()
(next) ->
# updating session data after login
sessionUpdateOptions =
$set :
username : username
clientId : replacementToken
lastLoginDate : lastLoginDate = new Date
$unset :
guestId : 1
guestSessionBegan : 1
guestUsername = session.username
session.update sessionUpdateOptions, (err) ->
return next err if err
Tracker.identify username, { lastLoginDate }
Tracker.alias guestUsername, username
next()
(next) ->
# updating user data after login
userUpdateData = { lastLoginDate : new Date }
if session.foreignAuth
{ foreignAuth } = user
foreignAuth or= {}
foreignAuth = extend foreignAuth, session.foreignAuth
userUpdateData.foreignAuth = foreignAuth
userUpdateOptions =
$set : userUpdateData
$unset :
inactive : 1
user.update userUpdateOptions, (err) ->
return next err if err
# This should be called after login and this
# is not correct place to do it, FIXME GG
# p.s. we could do that in workers
account.updateCounts()
if foreignAuth
providers = {}
Object.keys(foreignAuth).forEach (provider) ->
providers[provider] = yes
Tracker.identify user.username, { foreignAuth: providers }
JLog.log { type: 'login', username , success: yes }
next()
(next) ->
JUser.clearOauthFromSession session, next
]
async.series queue, (err) ->
return callback err if err
callback null, { account, replacementToken, returnUrl: session.returnUrl }
Tracker.track username, { subject : Tracker.types.LOGGED_IN }
@logout = secure (client, callback) ->
if 'string' is typeof client
sessionToken = client
else
{ sessionToken } = client
delete client.connection.delegate
delete client.sessionToken
# if sessionToken doesnt exist, safe to return
return callback null unless sessionToken
JSession.remove { clientId: sessionToken }, callback
@verifyEnrollmentEligibility = (options, callback) ->
{ email, invitationToken, groupName, skipAllowedDomainCheck } = options
# this is legacy but still in use, just checks if registeration is enabled or not
JRegistrationPreferences = require '../registrationpreferences'
JInvitation = require '../invitation'
JRegistrationPreferences.one {}, (err, prefs) ->
return callback err if err
unless prefs.isRegistrationEnabled
return callback new Error 'Registration is currently disabled!'
# return without checking domain if skipAllowedDomainCheck is true
return callback null, { isEligible : yes } if skipAllowedDomainCheck
# check if email domain is in allowed domains
return checkWithDomain groupName, email, callback unless invitationToken
JInvitation.byCode invitationToken, (err, invitation) ->
# check if invitation exists
if err or not invitation?
return callback new KodingError 'Invalid invitation code!'
# check if invitation is valid
if invitation.isValid() and invitation.groupName is groupName
return callback null, { isEligible: yes, invitation }
# last resort, check if email domain is under allowed domains
return checkWithDomain groupName, email, callback
@addToGroup = (account, slug, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
options.email = email
options.groupName = slug
options.invitationToken = invitation.code if invitation?.code
JUser.verifyEnrollmentEligibility options, (err, res) ->
return callback err if err
return callback new KodingError 'malformed response' if not res
return callback new KodingError 'can not join to group' if not res.isEligible
# fetch group that we are gonna add account in
JGroup.one { slug }, (err, group) ->
return callback err if err
return callback null if not group
roles = ['member']
if invitation?.role and slug isnt 'koding'
roles.push invitation.role
roles = uniq roles
group.approveMember account, roles, (err) ->
return callback err if err
if code = invitation?.code
groupUrl = "#{protocol}//#{slug}.#{hostname}"
properties =
groupName : slug
link : "#{groupUrl}/Invitation/#{encodeURIComponent code}"
options =
subject : Tracker.types.TEAMS_JOINED_TEAM
Tracker.identifyAndTrack email, options, properties
# do not forget to redeem invitation
redeemInvitation {
account, invitation, slug, email
}, callback
@addToGroups = (account, slugs, email, invitation, options, callback) ->
[options, callback] = [{}, options] unless callback
slugs.push invitation.groupName if invitation?.groupName
slugs = uniq slugs # clean up slugs
queue = slugs.map (slug) => (fin) =>
@addToGroup account, slug, email, invitation, options, fin
async.parallel queue, callback
@createGuestUsername = -> "guest-#{rack()}"
@fetchGuestUser = (callback) ->
username = @createGuestUsername()
account = new JAccount()
account.profile = { nickname: username }
account.type = 'unregistered'
callback null, { account, replacementToken: createId() }
@createUser = (userInfo, callback) ->
{ username, email, password, passwordStatus,
firstName, lastName, foreignAuth, silence, emailFrequency } = userInfo
if typeof username isnt 'string'
return callback new KodingError 'Username must be a string!'
# lower casing username is necessary to prevent conflicts with other JModels
username = username.toLowerCase()
email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
emailFrequencyDefaults = {
global : on
daily : off
privateMessage : on
followActions : off
comment : on
likeActivities : off
groupInvite : on
groupRequest : on
groupApproved : on
groupJoined : on
groupLeft : off
mention : on
marketing : on
}
# _.defaults doesnt handle undefined, extend handles correctly
emailFrequency = extend emailFrequencyDefaults, emailFrequency
slug =
slug : username
constructorName : 'JUser'
usedAsPath : 'username'
collectionName : 'jUsers'
JName.claim username, [slug], 'JUser', (err, nameDoc) ->
return callback err if err
salt = createSalt()
user = new JUser {
username
email
sanitizedEmail
salt
password : PI:PASSWORD:<PASSWORD>END_PI, PI:PASSWORD:<PASSWORD>END_PI
passwordStatus : passwordStatus or 'valid'
emailFrequency : emailFrequency
}
user.foreignAuth = foreignAuth if foreignAuth
user.save (err) ->
if err
nameDoc.remove?()
return if err.code is 11000
then callback new KodingError "Sorry, \"#{email}\" is already in use!"
else callback err
account = new JAccount
profile : {
nickname : username
hash : getHash email
firstName
lastName
}
account.save (err) ->
if err
user.remove?()
nameDoc.remove?()
callback err
else user.addOwnAccount account, (err) ->
if err then callback err
else callback null, user, account
@fetchUserByProvider = (provider, session, callback) ->
{ foreignAuth } = session
unless foreignAuth?[provider]?.foreignId
return callback new KodingError "No foreignAuth:#{provider} info in session"
query = {}
query["foreignAuth.#{provider}.foreignId"] = foreignAuth[provider].foreignId
JUser.one query, callback
@authenticateWithOauth = secure (client, resp, callback) ->
{ isUserLoggedIn, provider } = resp
{ sessionToken } = client
JSession.one { clientId: sessionToken }, (err, session) =>
return callback new KodingError err if err
unless session
{ connection: { delegate: { profile: { nickname } } } } = client
console.error 'authenticateWithOauth: session not found', nickname
return callback new KodingError 'Couldn\'t restore your session!'
kallback = (err, resp = {}) ->
{ account, replacementToken, returnUrl } = resp
callback err, {
isNewUser : false
userInfo : null
account
replacementToken
returnUrl
}
@fetchUserByProvider provider, session, (err, user) =>
return callback new KodingError err.message if err
if isUserLoggedIn
if user and user.username isnt client.connection.delegate.profile.nickname
@clearOauthFromSession session, ->
callback new KodingError '''
Account is already linked with another user.
'''
else
@fetchUser client, (err, user) =>
return callback new KodingError err.message if err
@persistOauthInfo user.username, sessionToken, kallback
else
if user
afterLogin user, sessionToken, session, kallback
else
return callback new KodingError 'Koding Solo registrations are closed!'
@validateAll = (userFormData, callback) ->
Validator = require './validators'
validator = new Validator
isError = no
errors = {}
queue = []
(key for key of validator).forEach (field) =>
queue.push (fin) => validator[field].call this, userFormData, (err) ->
if err?
errors[field] = err
isError = yes
fin()
async.parallel queue, ->
callback if isError
{ message: 'Errors were encountered during validation', errors }
else null
@changeEmailByUsername = (options, callback) ->
{ account, oldUsername, email } = options
# prevent from leading and trailing spaces
email = emailsanitize email
@update { username: oldUsername }, { $set: { email } }, (err, res) ->
return callback err if err
account.profile.hash = getHash email
account.save (err) -> console.error if err
callback null
@changeUsernameByAccount = (options, callback) ->
{ account, username, clientId, isRegistration, groupName } = options
account.changeUsername { username, isRegistration }, (err) ->
return callback err if err?
return callback null unless clientId?
newToken = createId()
JSession.one { clientId }, (err, session) ->
if err?
return callback new KodingError 'Could not update your session'
if session?
sessionUpdateOptions =
$set : { clientId : newToken, username, groupName }
$unset : { guestSessionBegan : 1 }
session.update sessionUpdateOptions, (err) ->
return callback err if err?
callback null, newToken
else
callback new KodingError 'Session not found!'
@removeFromGuestsGroup = (account, callback) ->
JGroup.one { slug: 'guests' }, (err, guestsGroup) ->
return callback err if err?
return callback new KodingError 'Guests group not found!' unless guestsGroup?
guestsGroup.removeMember account, callback
createGroupStack = (account, groupName, callback) ->
_client =
connection :
delegate : account
context :
group : groupName
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack for #{account.profile.nickname}:", err
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback()
verifyUser = (options, callback) ->
{ slug
email
recaptcha
disableCaptcha
userFormData
foreignAuthType } = options
queue = [
(next) ->
# verifying recaptcha if enabled
return next() if disableCaptcha or not KONFIG.recaptcha.enabled
JUser.verifyRecaptcha recaptcha, { foreignAuthType, slug }, next
(next) ->
JUser.validateAll userFormData, next
(next) ->
JUser.emailAvailable email, (err, res) ->
if err
return next new KodingError 'Something went wrong'
if res is no
return next new KodingError 'Email is already in use!'
next()
]
async.series queue, callback
createUser = (options, callback) ->
{ userInfo } = options
# creating a new user
JUser.createUser userInfo, (err, user, account) ->
return callback err if err
unless user? and account?
return callback new KodingError 'Failed to create user!'
callback null, { user, account }
updateUserInfo = (options, callback) ->
{ user, ip, country, region, username,
client, account, clientId, password } = options
newToken = null
queue = [
(next) ->
# updating user's location related info
return next() unless ip? and country? and region?
locationModifier =
$set :
'registeredFrom.ip' : ip
'registeredFrom.region' : region
'registeredFrom.country' : country
user.update locationModifier, ->
next()
(next) ->
JUser.persistOauthInfo username, client.sessionToken, next
(next) ->
return next() unless username?
_options =
account : account
username : username
clientId : clientId
groupName : client.context.group
isRegistration : yes
JUser.changeUsernameByAccount _options, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
user.setPassword password, next
]
async.series queue, (err) ->
return callback err if err
callback null, newToken
updateAccountInfo = (options, callback) ->
{ account, referrer, username } = options
queue = [
(next) ->
account.update { $set: { type: 'registered' } }, next
(next) ->
account.createSocialApiId next
(next) ->
# setting referrer
return next() unless referrer
if username is referrer
console.error "User (#{username}) tried to refer themself."
return next()
JUser.count { username: referrer }, (err, count) ->
if err? or count < 1
console.error 'Provided referrer not valid:', err
return next()
account.update { $set: { referrerUsername: referrer } }, (err) ->
if err?
then console.error err
else console.log "#{referrer} referred #{username}"
next()
]
async.series queue, callback
createDefaultStackForKodingGroup = (options, callback) ->
{ account } = options
# create default stack for koding group, when a user joins this is only
# required for koding group, not neeed for other teams
_client =
connection :
delegate : account
context :
group : 'koding'
ComputeProvider.createGroupStack _client, (err) ->
if err?
console.warn "Failed to create group stack
for #{account.profile.nickname}:#{err}"
# We are not returning error here on purpose, even stack template
# not created for a user we don't want to break registration process
# at all ~ GG
callback null
confirmAccountIfNeeded = (options, callback) ->
{ user, email, username, group } = options
if KONFIG.autoConfirmAccounts or group isnt 'koding'
user.confirmEmail (err) ->
console.warn err if err?
return callback err
else
_options =
email : email
action : 'verify-account'
username : username
JVerificationToken = require '../verificationtoken'
JVerificationToken.createNewPin _options, (err, confirmation) ->
console.warn 'Failed to send verification token:', err if err
callback err, confirmation?.pin
validateConvert = (options, callback) ->
{ client, userFormData, foreignAuthType, skipAllowedDomainCheck } = options
{ slug, email, invitationToken, recaptcha, disableCaptcha } = userFormData
invitation = null
queue = [
(next) ->
params = { slug, email, recaptcha, disableCaptcha, userFormData, foreignAuthType }
verifyUser params, next
(next) ->
params = {
groupName : client.context.group
invitationToken, skipAllowedDomainCheck, email
}
JUser.verifyEnrollmentEligibility params, (err, res) ->
return next err if err
{ isEligible, invitation } = res
if not isEligible
return next new Error "you can not register to #{client.context.group}"
next()
]
async.series queue, (err) ->
return callback err if err
callback null, { invitation }
processConvert = (options, callback) ->
{ ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck } = options
{ sessionToken : clientId } = client
{ referrer, email, username, password,
emailFrequency, firstName, lastName } = userFormData
user = null
error = null
account = null
newToken = null
queue = [
(next) ->
userInfo = {
email, username, password, lastName, firstName, emailFrequency
}
createUser { userInfo }, (err, data) ->
return next err if err
{ user, account } = data
next()
(next) ->
params = {
user, ip, country, region, username
password, clientId, account, client
}
updateUserInfo params, (err, newToken_) ->
return next err if err
newToken = newToken_
next()
(next) ->
updateAccountInfo { account, referrer, username }, next
(next) ->
groupNames = [client.context.group, 'koding']
options = { skipAllowedDomainCheck }
JUser.addToGroups account, groupNames, user.email, invitation, options, (err) ->
error = err
next()
(next) ->
createDefaultStackForKodingGroup { account }, next
]
async.series queue, (err) ->
return callback err if err
# passing "error" variable to be used as an argument in the callback func.
# that is being called after registration process is completed.
callback null, { error, newToken, user, account }
@convert = secure (client, userFormData, options, callback) ->
[options, callback] = [{}, options] unless callback
{ slug, email, agree, username, lastName, referrer,
password, firstName, recaptcha, emailFrequency,
invitationToken, passwordConfirm, disableCaptcha } = userFormData
{ skipAllowedDomainCheck } = options
{ clientIP, connection } = client
{ delegate : account } = connection
{ nickname : oldUsername } = account.profile
# if firstname is not received use username as firstname
userFormData.firstName = username unless firstName
userFormData.lastName = '' unless lastName
if error = validateConvertInput userFormData, client
return callback error
# lower casing username is necessary to prevent conflicts with other JModels
username = userFormData.username = username.toLowerCase()
email = userFormData.email = emailsanitize email
if clientIP
{ ip, country, region } = Regions.findLocation clientIP
pin = null
user = null
error = null
newToken = null
invitation = null
foreignAuthType = null
subscription = null
queue = [
(next) =>
@extractOauthFromSession client.sessionToken, (err, foreignAuthInfo) ->
if err
console.log 'Error while getting oauth data from session', err
return next()
return next() unless foreignAuthInfo
# Password is not required for GitHub users since they are authorized via GitHub.
# To prevent having the same password for all GitHub users since it may be
# a security hole, let's auto generate it if it's not provided in request
unless password
password = userFormData.password = PI:PASSWORD:<PASSWORD>END_PI()
passwordConfirm = userFormData.passwordConfirm = password
next()
(next) ->
options = { client, userFormData, foreignAuthType, skipAllowedDomainCheck }
validateConvert options, (err, data) ->
return next err if err
{ invitation } = data
next()
(next) ->
params = {
ip, country, region, client, invitation
userFormData, skipAllowedDomainCheck
}
processConvert params, (err, data) ->
return next err if err
{ error, newToken, user, account } = data
next()
(next) ->
date = new Date 0
subscription =
accountId : account.getId()
planTitle : 'free'
planInterval : 'month'
state : 'active'
provider : 'koding'
expiredAt : date
canceledAt : date
currentPeriodStart : date
currentPeriodEnd : date
args = { user, account, subscription, pin, oldUsername }
identifyUserOnRegister disableCaptcha, args
JUser.emit 'UserRegistered', { user, account }
next()
(next) ->
# Auto confirm accounts for development environment or Teams ~ GG
args = { group : client.context.group, user, email, username }
confirmAccountIfNeeded args, (err, pin_) ->
pin = pin_
next err
]
async.series queue, (err) ->
return callback err if err
# don't block register
callback error, { account, newToken, user }
group = client.context.group
args = { user, group, pin, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }
trackUserOnRegister disableCaptcha, args
SiftScience = require '../siftscience'
SiftScience.createAccount client, referrer, ->
identifyUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
{ user, account, subscription, pin, oldUsername } = args
{ status, lastLoginDate, username, email } = user
{ createdAt, profile } = account.meta
{ PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } = account.profile
jwtToken = JUser.createJWT { username }
sshKeysCount = user.sshKeys.length
emailFrequency =
global : user.emailFrequency.global
marketing : user.emailFrequency.marketing
traits = {
email
createdAt
lastLoginDate
status
PI:NAME:<NAME>END_PI
PI:NAME:<NAME>END_PI
subscription
sshKeysCount
emailFrequency
pin
jwtToken
}
Tracker.identify username, traits
Tracker.alias oldUsername, username
trackUserOnRegister = (disableCaptcha, args) ->
return if disableCaptcha
subject = Tracker.types.START_REGISTER
{ user, group, pin, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } = args
{ username, email } = user
opts = { pin, group, user : { user_id : username, email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } }
Tracker.track username, { to : email, subject }, opts
@createJWT: (data, options = {}) ->
{ secret, confirmExpiresInMinutes } = KONFIG.jwt
jwt = require 'jsonwebtoken'
# uses 'HS256' as default for signing
options.expiresInMinutes ?= confirmExpiresInMinutes
return jwt.sign data, secret, options
@removeUnsubscription:({ email }, callback) ->
JUnsubscribedMail = require '../unsubscribedmail'
JUnsubscribedMail.one { email }, (err, unsubscribed) ->
return callback err if err or not unsubscribed
unsubscribed.remove callback
@grantInitialInvitations = (username) ->
JInvitation.grant { 'profile.nickname': username }, 3, (err) ->
console.log 'An error granting invitations', err if err
@fetchUser = secure (client, callback) ->
JSession.one { clientId: client.sessionToken }, (err, session) ->
return callback err if err
noUserError = -> new KodingError \
'No user found! Not logged in or session expired'
if not session or not session.username
return callback noUserError()
JUser.one { username: session.username }, (err, user) ->
if err or not user
console.log '[JUser::fetchUser]', err if err?
callback noUserError()
else
callback null, user
@changePassword = secure (client, password, callback) ->
@fetchUser client, (err, user) ->
if err or not user
return callback new KodingError \
'Something went wrong please try again!'
if user.getAt('password') is hashPassword password, user.getAt('salt')
return callback new KodingError 'PasswordIsSame'
user.changePassword password, (err) ->
return callback err if err
account = client.connection.delegate
clientId = client.sessionToken
account.sendNotification 'SessionHasEnded', { clientId }
selector = { clientId: { $ne: client.sessionToken } }
user.killSessions selector, callback
sendChangedEmail = (username, PI:NAME:<NAME>END_PI, to, type) ->
subject = if type is 'email' then Tracker.types.CHANGED_EMAIL
else Tracker.types.CHANGED_PASSWORD
Tracker.track username, { to, subject }, { firstName }
@changeEmail = secure (client, options, callback) ->
{ email } = options
email = options.email = emailsanitize email
account = client.connection.delegate
account.fetchUser (err, user) =>
return callback new KodingError 'Something went wrong please try again!' if err
return callback new KodingError 'EmailIsSameError' if email is user.email
@emailAvailable email, (err, res) ->
return callback new KodingError 'Something went wrong please try again!' if err
if res is no
callback new KodingError 'Email is already in use!'
else
user.changeEmail account, options, callback
@emailAvailable = (email, callback) ->
unless typeof email is 'string'
return callback new KodingError 'Not a valid email!'
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
@count { sanitizedEmail }, (err, count) ->
callback err, count is 0
@getValidUsernameLengthRange = -> { minLength : 4, maxLength : 25 }
@usernameAvailable = (username, callback) ->
JName = require '../name'
username += ''
res =
kodingUser : no
forbidden : yes
JName.count { name: username }, (err, count) =>
{ minLength, maxLength } = JUser.getValidUsernameLengthRange()
if err or username.length < minLength or username.length > maxLength
callback err, res
else
res.kodingUser = count is 1
res.forbidden = username in @bannedUserList
callback null, res
fetchAccount: (context, rest...) -> @fetchOwnAccount rest...
setPassword: (password, callback) ->
salt = createSalt()
@update {
$set :
salt : salt
password : PI:PASSWORD:<PASSWORD>END_PI, salt
passwordStatus : 'valid'
}, callback
changePassword: (newPassword, callback) ->
@setPassword newPassword, (err) =>
return callback err if err
@fetchAccount 'koding', (err, account) =>
return callback err if err
return callback new KodingError 'Account not found' unless account
{ firstName } = account.profile
sendChangedEmail @getAt('username'), firstName, @getAt('email'), 'password'
callback null
changeEmail: (account, options, callback) ->
JVerificationToken = require '../verificationtoken'
{ email, pin } = options
email = options.email = emailsanitize email
sanitizedEmail = emailsanitize email, { excludeDots: yes, excludePlus: yes }
if account.type is 'unregistered'
@update { $set: { email , sanitizedEmail } }, (err) ->
return callback err if err
callback null
return
action = 'update-email'
if not pin
options = {
email, action, user: this, resendIfExists: yes
}
JVerificationToken.requestNewPin options, callback
else
options = {
email, action, pin, username: @getAt 'username'
}
JVerificationToken.confirmByPin options, (err, confirmed) =>
return callback err if err
unless confirmed
return callback new KodingError 'PIN is not confirmed.'
oldEmail = @getAt 'email'
@update { $set: { email, sanitizedEmail } }, (err, res) =>
return callback err if err
account.profile.hash = getHash email
account.save (err) =>
return callback err if err
{ firstName } = account.profile
# send EmailChanged event
@constructor.emit 'EmailChanged', {
username: @getAt('username')
oldEmail: oldEmail
newEmail: email
}
sendChangedEmail @getAt('username'), firstName, oldEmail, 'email'
callback null
Tracker.identify @username, { email }
fetchHomepageView: (options, callback) ->
{ account, bongoModels } = options
@fetchAccount 'koding', (err, account) ->
return callback err if err
return callback new KodingError 'Account not found' unless account
account.fetchHomepageView options, callback
confirmEmail: (callback) ->
status = @getAt 'status'
username = @getAt 'username'
# for some reason status is sometimes 'undefined', so check for that
if status? and status isnt 'unconfirmed'
return callback null
modifier = { status: 'confirmed' }
@update { $set: modifier }, (err, res) =>
return callback err if err
JUser.emit 'EmailConfirmed', this
callback null
Tracker.identify username, modifier
Tracker.track username, { subject: Tracker.types.FINISH_REGISTER }
block: (blockedUntil, callback) ->
unless blockedUntil then return callback new KodingError 'Blocking date is not defined'
status = 'blocked'
@update { $set: { status, blockedUntil } }, (err) =>
return callback err if err
JUser.emit 'UserBlocked', this
console.log 'JUser#block JSession#remove', { @username, blockedUntil }
# clear all of the cookies of the blocked user
JSession.remove { username: @username }, callback
Tracker.identify @username, { status }
unblock: (callback) ->
status = 'confirmed'
op =
$set : { status }
$unset : { blockedUntil: yes }
@update op, (err) =>
return callback err if err
JUser.emit 'UserUnblocked', this
callback()
Tracker.identify @username, { status }
unlinkOAuths: (callback) ->
@update { $unset: { foreignAuth:1 , foreignAuthType:1 } }, (err) =>
return callback err if err
@fetchOwnAccount (err, account) ->
return callback err if err
account.unstoreAll callback
@persistOauthInfo: (username, clientId, callback) ->
@extractOauthFromSession clientId, (err, foreignAuthInfo) =>
return callback err if err
return callback null unless foreignAuthInfo
return callback null unless foreignAuthInfo.session
@saveOauthToUser foreignAuthInfo, username, (err) =>
return callback err if err
do (foreignAuth = {}) ->
{ foreignAuthType } = foreignAuthInfo
foreignAuth[foreignAuthType] = yes
Tracker.identify username, { foreignAuth }
@clearOauthFromSession foreignAuthInfo.session, (err) =>
return callback err if err
@copyPublicOauthToAccount username, foreignAuthInfo, (err, resp = {}) ->
return callback err if err
{ session: { returnUrl } } = foreignAuthInfo
resp.returnUrl = returnUrl if returnUrl
return callback null, resp
@extractOauthFromSession: (clientId, callback) ->
JSession.one { clientId: clientId }, (err, session) ->
return callback err if err
return callback null unless session
{ foreignAuth, foreignAuthType } = session
if foreignAuth and foreignAuthType
callback null, { foreignAuth, foreignAuthType, session }
else
callback null # WARNING: don't assume it's an error if there's no foreignAuth
@saveOauthToUser: ({ foreignAuth, foreignAuthType }, username, callback) ->
query = {}
query["foreignAuth.#{foreignAuthType}"] = foreignAuth[foreignAuthType]
@update { username }, { $set: query }, callback
@clearOauthFromSession: (session, callback) ->
session.update { $unset: { foreignAuth:1, foreignAuthType:1 } }, callback
@copyPublicOauthToAccount: (username, { foreignAuth, foreignAuthType }, callback) ->
JAccount.one { 'profile.nickname' : username }, (err, account) ->
return callback err if err
name = "ext|profile|#{foreignAuthType}"
content = foreignAuth[foreignAuthType].profile
account._store { name, content }, callback
@setSSHKeys: secure (client, sshKeys, callback) ->
@fetchUser client, (err, user) ->
user.sshKeys = sshKeys
user.save callback
Tracker.identify user.username, { sshKeysCount: sshKeys.length }
@getSSHKeys: secure (client, callback) ->
@fetchUser client, (err, user) ->
return callback user?.sshKeys or []
###*
* Compare provided password with JUser.password
*
* @param {string} password
###
checkPassword: (password) ->
# hash of given password and given user's salt should match with user's password
return @getAt('password') is hashPassword password, @getAt('salt')
###*
* Compare provided verification token with time
* based generated 2Factor code. If 2Factor not enabled returns true
*
* @param {string} verificationCode
###
check2FactorAuth: (verificationCode) ->
key = @getAt 'twofactorkey'
speakeasy = require 'speakeasy'
generatedKey = speakeasy.totp { key, encoding: 'base32' }
return generatedKey is verificationCode
###*
* Verify if `response` from client is valid by asking recaptcha servers.
* Check is disabled in dev mode or when user is authenticating via `github`.
*
* @param {string} response
* @param {string} foreignAuthType
* @param {function} callback
###
@verifyRecaptcha = (response, params, callback) ->
{ url, secret } = KONFIG.recaptcha
{ foreignAuthType, slug } = params
return callback null if foreignAuthType is 'github'
# TODO: temporarily disable recaptcha for groups
if slug? and slug isnt 'koding'
return callback null
request.post url, { form: { response, secret } }, (err, res, raw) ->
if err
console.log "Recaptcha: err validation captcha: #{err}"
if not err and res.statusCode is 200
try
if JSON.parse(raw)['success']
return callback null
catch e
console.log "Recaptcha: parsing response failed. #{raw}"
return callback new KodingError 'Captcha not valid. Please try again.'
###*
* Remove session documents matching selector object.
*
* @param {Object} [selector={}] - JSession query selector.
* @param {Function} - Callback.
###
killSessions: (selector = {}, callback) ->
selector.username = @username
JSession.remove selector, callback
|
[
{
"context": "y \" + entry.meta.name)\n console.log(\"Name \" + @name)\n if (entry.meta.name == @name) && (entr",
"end": 2709,
"score": 0.48010051250457764,
"start": 2709,
"tag": "NAME",
"value": ""
},
{
"context": "\" + entry.meta.name)\n console.log(\"Name \" + @name... | tree-view/lib/file.coffee | sebischair/cc-annotator-dev-tools | 0 | path = require 'path'
fs = require 'fs-plus'
{CompositeDisposable, Emitter} = require 'event-kit'
{repoForPath} = require './helpers'
module.exports =
class File
constructor: ({@name, fullPath, @symlink, realpathCache, useSyncFS, @stats}) ->
@destroyed = false
@emitter = new Emitter()
@subscriptions = new CompositeDisposable()
@path = fullPath
@realPath = @path
@subscribeToRepo()
@updateStatus()
if useSyncFS
@realPath = fs.realpathSync(@path)
else
fs.realpath @path, realpathCache, (error, realPath) =>
return if @destroyed
if realPath and realPath isnt @path
@realPath = realPath
@updateStatus()
directoryPath = path.dirname(@path)
annotatorFile = path.join(directoryPath, ".annotator")
console.log(directoryPath)
try
fs.accessSync(annotatorFile)
@isAnnotated = @getAnnotationsinFile(annotatorFile)
console.log("Is Annotated: " + @isAnnotated)
catch error
@isAnnotated = false
console.log(error)
destroy: ->
@destroyed = true
@subscriptions.dispose()
@emitter.emit('did-destroy')
onDidDestroy: (callback) ->
@emitter.on('did-destroy', callback)
onDidStatusChange: (callback) ->
@emitter.on('did-status-change', callback)
# Subscribe to the project's repo for changes to the Git status of this file.
subscribeToRepo: ->
repo = repoForPath(@path)
return unless repo?
@subscriptions.add repo.onDidChangeStatus (event) =>
@updateStatus(repo) if @isPathEqual(event.path)
@subscriptions.add repo.onDidChangeStatuses =>
@updateStatus(repo)
setAnnotated: (hasAnnotation) ->
@isAnnotated = hasAnnotation
getAnnotated: ->
@isAnnotated
# Update the status property of this directory using the repo.
updateStatus: ->
repo = repoForPath(@path)
return unless repo?
newStatus = null
if repo.isPathIgnored(@path)
newStatus = 'ignored'
else
status = repo.getCachedPathStatus(@path)
if repo.isStatusModified(status)
newStatus = 'modified'
else if repo.isStatusNew(status)
newStatus = 'added'
if newStatus isnt @status
@status = newStatus
@emitter.emit('did-status-change', newStatus)
isPathEqual: (pathToCompare) ->
@path is pathToCompare or @realPath is pathToCompare
getAnnotationsinFile: (fileName) ->
fileHasAnnotatations = false
json = fs.readFileSync(fileName)
data = JSON.parse(json)
annotatedFiles = data.annotated_files
filesList = []
console.log("Getting annotations...")
for entry in annotatedFiles
console.log("Entry " + entry.meta.name)
console.log("Name " + @name)
if (entry.meta.name == @name) && (entry.annotations.length > 0)
fileHasAnnotatations = true
return fileHasAnnotatations
| 53620 | path = require 'path'
fs = require 'fs-plus'
{CompositeDisposable, Emitter} = require 'event-kit'
{repoForPath} = require './helpers'
module.exports =
class File
constructor: ({@name, fullPath, @symlink, realpathCache, useSyncFS, @stats}) ->
@destroyed = false
@emitter = new Emitter()
@subscriptions = new CompositeDisposable()
@path = fullPath
@realPath = @path
@subscribeToRepo()
@updateStatus()
if useSyncFS
@realPath = fs.realpathSync(@path)
else
fs.realpath @path, realpathCache, (error, realPath) =>
return if @destroyed
if realPath and realPath isnt @path
@realPath = realPath
@updateStatus()
directoryPath = path.dirname(@path)
annotatorFile = path.join(directoryPath, ".annotator")
console.log(directoryPath)
try
fs.accessSync(annotatorFile)
@isAnnotated = @getAnnotationsinFile(annotatorFile)
console.log("Is Annotated: " + @isAnnotated)
catch error
@isAnnotated = false
console.log(error)
destroy: ->
@destroyed = true
@subscriptions.dispose()
@emitter.emit('did-destroy')
onDidDestroy: (callback) ->
@emitter.on('did-destroy', callback)
onDidStatusChange: (callback) ->
@emitter.on('did-status-change', callback)
# Subscribe to the project's repo for changes to the Git status of this file.
subscribeToRepo: ->
repo = repoForPath(@path)
return unless repo?
@subscriptions.add repo.onDidChangeStatus (event) =>
@updateStatus(repo) if @isPathEqual(event.path)
@subscriptions.add repo.onDidChangeStatuses =>
@updateStatus(repo)
setAnnotated: (hasAnnotation) ->
@isAnnotated = hasAnnotation
getAnnotated: ->
@isAnnotated
# Update the status property of this directory using the repo.
updateStatus: ->
repo = repoForPath(@path)
return unless repo?
newStatus = null
if repo.isPathIgnored(@path)
newStatus = 'ignored'
else
status = repo.getCachedPathStatus(@path)
if repo.isStatusModified(status)
newStatus = 'modified'
else if repo.isStatusNew(status)
newStatus = 'added'
if newStatus isnt @status
@status = newStatus
@emitter.emit('did-status-change', newStatus)
isPathEqual: (pathToCompare) ->
@path is pathToCompare or @realPath is pathToCompare
getAnnotationsinFile: (fileName) ->
fileHasAnnotatations = false
json = fs.readFileSync(fileName)
data = JSON.parse(json)
annotatedFiles = data.annotated_files
filesList = []
console.log("Getting annotations...")
for entry in annotatedFiles
console.log("Entry " + entry.meta.name)
console.log("Name " +<NAME> @name)
if (entry.meta.name ==<NAME> @name) && (entry.annotations.length > 0)
fileHasAnnotatations = true
return fileHasAnnotatations
| true | path = require 'path'
fs = require 'fs-plus'
{CompositeDisposable, Emitter} = require 'event-kit'
{repoForPath} = require './helpers'
module.exports =
class File
constructor: ({@name, fullPath, @symlink, realpathCache, useSyncFS, @stats}) ->
@destroyed = false
@emitter = new Emitter()
@subscriptions = new CompositeDisposable()
@path = fullPath
@realPath = @path
@subscribeToRepo()
@updateStatus()
if useSyncFS
@realPath = fs.realpathSync(@path)
else
fs.realpath @path, realpathCache, (error, realPath) =>
return if @destroyed
if realPath and realPath isnt @path
@realPath = realPath
@updateStatus()
directoryPath = path.dirname(@path)
annotatorFile = path.join(directoryPath, ".annotator")
console.log(directoryPath)
try
fs.accessSync(annotatorFile)
@isAnnotated = @getAnnotationsinFile(annotatorFile)
console.log("Is Annotated: " + @isAnnotated)
catch error
@isAnnotated = false
console.log(error)
destroy: ->
@destroyed = true
@subscriptions.dispose()
@emitter.emit('did-destroy')
onDidDestroy: (callback) ->
@emitter.on('did-destroy', callback)
onDidStatusChange: (callback) ->
@emitter.on('did-status-change', callback)
# Subscribe to the project's repo for changes to the Git status of this file.
subscribeToRepo: ->
repo = repoForPath(@path)
return unless repo?
@subscriptions.add repo.onDidChangeStatus (event) =>
@updateStatus(repo) if @isPathEqual(event.path)
@subscriptions.add repo.onDidChangeStatuses =>
@updateStatus(repo)
setAnnotated: (hasAnnotation) ->
@isAnnotated = hasAnnotation
getAnnotated: ->
@isAnnotated
# Update the status property of this directory using the repo.
updateStatus: ->
repo = repoForPath(@path)
return unless repo?
newStatus = null
if repo.isPathIgnored(@path)
newStatus = 'ignored'
else
status = repo.getCachedPathStatus(@path)
if repo.isStatusModified(status)
newStatus = 'modified'
else if repo.isStatusNew(status)
newStatus = 'added'
if newStatus isnt @status
@status = newStatus
@emitter.emit('did-status-change', newStatus)
isPathEqual: (pathToCompare) ->
@path is pathToCompare or @realPath is pathToCompare
getAnnotationsinFile: (fileName) ->
fileHasAnnotatations = false
json = fs.readFileSync(fileName)
data = JSON.parse(json)
annotatedFiles = data.annotated_files
filesList = []
console.log("Getting annotations...")
for entry in annotatedFiles
console.log("Entry " + entry.meta.name)
console.log("Name " +PI:NAME:<NAME>END_PI @name)
if (entry.meta.name ==PI:NAME:<NAME>END_PI @name) && (entry.annotations.length > 0)
fileHasAnnotatations = true
return fileHasAnnotatations
|
[
{
"context": "cope prop is only used on <th> elements.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------",
"end": 116,
"score": 0.9998589754104614,
"start": 105,
"tag": "NAME",
"value": "Ethan Cohen"
}
] | src/tests/rules/scope.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce scope prop is only used on <th> elements.
# @author Ethan Cohen
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/scope'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'The scope prop can only be used on <th> elements.'
type: 'JSXAttribute'
ruleTester.run 'scope', rule,
valid: [
code: '<div />'
,
code: '<div foo />'
,
code: '<th scope />'
,
code: '<th scope="row" />'
,
code: '<th scope={foo} />'
,
code: '<th scope={"col"} {...props} />'
,
code: '<Foo scope="bar" {...props} />'
].map parserOptionsMapper
invalid: [code: '<div scope />', errors: [expectedError]].map(
parserOptionsMapper
)
| 171628 | ### eslint-env jest ###
###*
# @fileoverview Enforce scope prop is only used on <th> elements.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/scope'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'The scope prop can only be used on <th> elements.'
type: 'JSXAttribute'
ruleTester.run 'scope', rule,
valid: [
code: '<div />'
,
code: '<div foo />'
,
code: '<th scope />'
,
code: '<th scope="row" />'
,
code: '<th scope={foo} />'
,
code: '<th scope={"col"} {...props} />'
,
code: '<Foo scope="bar" {...props} />'
].map parserOptionsMapper
invalid: [code: '<div scope />', errors: [expectedError]].map(
parserOptionsMapper
)
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce scope prop is only used on <th> elements.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/scope'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message: 'The scope prop can only be used on <th> elements.'
type: 'JSXAttribute'
ruleTester.run 'scope', rule,
valid: [
code: '<div />'
,
code: '<div foo />'
,
code: '<th scope />'
,
code: '<th scope="row" />'
,
code: '<th scope={foo} />'
,
code: '<th scope={"col"} {...props} />'
,
code: '<Foo scope="bar" {...props} />'
].map parserOptionsMapper
invalid: [code: '<div scope />', errors: [expectedError]].map(
parserOptionsMapper
)
|
[
{
"context": "tusCode\" : 200}, JSON.stringify\n user_id :\"userGuid\"\n user_name : \"userName\"\n )\n else ",
"end": 1721,
"score": 0.9985779523849487,
"start": 1713,
"tag": "USERNAME",
"value": "userGuid"
},
{
"context": "\n user_id :\"userGuid\"\n ... | test/routes/cfapiSpec.coffee | MonsantoCo/cf-users | 14 | chai = require('chai')
chai.use(require('chai-string'));
expect = chai.expect
sinon = require('sinon')
mock = require 'mock-require'
equal = require 'deep-equal'
Promise = require 'promise'
describe 'cfapi ', ->
requestjs = (options,callback)->
if(options.url=="https://api.domain.com/v2/spaces?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 1
total_pages : 1
resources : [
metadata :
guid : "space1Guid"
entity :
name : "space1"
organization_guid : "org1Guid"
space_quota_definition_guid : "spaceQuotaGuid"
disk_quota : 1024
memory : 2048
space_guid : "space1Guid"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org1Guid"
entity :
name : "org1"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org2Guid"
entity :
name : "org2"
]
)
else if(options.url=="https://uaa.domain.com/userinfo")
callback(null,{ "statusCode" : 200}, JSON.stringify
user_id :"userGuid"
user_name : "userName"
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=1")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=2")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user2Guid"
entity :
name : "user2"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr1Guid"
entity :
name : "mgr1"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr2Guid"
entity :
name : "mgr2"
]
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="DELETE" && options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "deleted"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space2Guid/developers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space1Guid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space3Guid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/users/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="POST"&& options.url=="https://uaa.domain.com/Users")
ldapRequest =
"schemas": ["urn:scim:schemas:core:1.0" ]
"userName": "user@email.domain.com"
"name":
"familyName": "email.domain.com"
"givenName": "user"
"emails": [
"value": "user@email.domain.com"
]
"approvals": []
"active": true
"verified": true
"origin": "ldap"
uaaRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "user"
"name":
"familyName": "user",
"givenName": "user"
"emails": [
{
"value": "user"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "uaa",
"password": "thePassword"
samlRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "user@email.domain.com"
"name":
"familyName": "email.domain.com",
"givenName": "user"
"emails": [
{
"value": "user@email.domain.com"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "saml",
"externalId" : "user@email.domain.com"
if(equal(options.json,ldapRequest)||equal(options.json,uaaRequest)||equal(options.json,samlRequest))
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
else if(options.method=="POST" && options.url=="https://api.domain.com/v2/users"&&options.json.guid=="userGuid")
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else if(options.method=="GET" && options.url=="https://api.domain.com/v2/users/userGuid/managed_spaces?q=organization_guid:orgGuid")
callback( null,{"statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
mock('request',requestjs)
adminOauth = require "../../routes/AdminOauth"
cfapi = require("../../routes/cfapi")
serviceBindings = require "../../routes/serviceBindings"
serviceBindings["cloud_foundry_api-portal-admin-id"] = { b64 : "portal-admin-id-value"}
serviceBindings["cloud_foundry_api-portal-admin-pw"] = { b64 : "portal-admin-pw-value"}
serviceBindings["cloud_foundry_api-uaa-client-id"] = { b64 : "uaa-client-id-value"}
serviceBindings["cloud_foundry_api-uaa-client-secret"] = { b64 : "uaa-client-secret-value"}
serviceBindings["cloud_foundry_api-uaa-domain"] = { value:"uaa.domain.com"}
serviceBindings["cloud_foundry_api-domain"] = { value:"api.domain.com"}
serviceBindings["cloud_foundry_api-default-email-domain"] = { value: "email.domain.com"}
refreshToken = (method) ->
method
token:
access_token : "tokenvalue"
beforeEach ()->
adminOauth.refreshToken = refreshToken
it 'allOrganizations retrieves all organizations',(done)->
res =
json : (organizations) ->
expect(organizations.resources.length).to.equal(2)
expect(organizations.resources[0].entity.name).to.equal("org1")
expect(organizations.resources[0].metadata.guid).to.equal("org1Guid")
expect(organizations.resources[1].entity.name).to.equal("org2")
expect(organizations.resources[1].metadata.guid).to.equal("org2Guid")
done()
cfapi.allOrganizations
headers :
authorization : "Bearer oauthtoken"
,res
it 'userInfo retrieves currentUser Information', (done)->
res =
json : (userInfo) ->
expect(userInfo.user_id).to.equal("userGuid")
expect(userInfo.user_name).to.equal("userName")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.userInfo
headers :
authorization : "Bearer oauthtoken"
,res
it 'allUsers retrieves all users',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("user1")
expect(users.resources[0].metadata.guid).to.equal("user1Guid")
expect(users.resources[1].entity.name).to.equal("user2")
expect(users.resources[1].metadata.guid).to.equal("user2Guid")
done()
cfapi.allUsers
headers :
authorization : "Bearer oauthtoken"
,res
it 'listCfRequest retrieves all stuff to list (very generic)',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("mgr1")
expect(users.resources[0].metadata.guid).to.equal("mgr1Guid")
expect(users.resources[1].entity.name).to.equal("mgr2")
expect(users.resources[1].metadata.guid).to.equal("mgr2Guid")
done()
cfapi.listCfRequest
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
,res
it 'putRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("added")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.putRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'deleteRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("deleted")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.deleteRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'create user creates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "user@domain.com"
identityProvider : "ldap"
org :
guid : "orgGuid"
manager : true
auditor : true
spaces : [
guid : "space1Guid"
manager : true
developer : false
auditor : false
,
guid : "space2Guid"
manager : false
developer : true
auditor : false
,
guid : "space3Guid"
manager : false
developer : false
auditor : true
]
,res
it 'create user uaa usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "user@domain.com"
password : "thePassword"
identityProvider : "uaa"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res
it 'create user saml usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "user@domain.com"
password : "thePassword"
identityProvider : "saml"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res | 112700 | chai = require('chai')
chai.use(require('chai-string'));
expect = chai.expect
sinon = require('sinon')
mock = require 'mock-require'
equal = require 'deep-equal'
Promise = require 'promise'
describe 'cfapi ', ->
requestjs = (options,callback)->
if(options.url=="https://api.domain.com/v2/spaces?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 1
total_pages : 1
resources : [
metadata :
guid : "space1Guid"
entity :
name : "space1"
organization_guid : "org1Guid"
space_quota_definition_guid : "spaceQuotaGuid"
disk_quota : 1024
memory : 2048
space_guid : "space1Guid"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org1Guid"
entity :
name : "org1"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org2Guid"
entity :
name : "org2"
]
)
else if(options.url=="https://uaa.domain.com/userinfo")
callback(null,{ "statusCode" : 200}, JSON.stringify
user_id :"userGuid"
user_name : "userName"
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=1")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=2")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user2Guid"
entity :
name : "user2"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr1Guid"
entity :
name : "mgr1"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr2Guid"
entity :
name : "mgr2"
]
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="DELETE" && options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "deleted"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space2Guid/developers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space1Guid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space3Guid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/users/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="POST"&& options.url=="https://uaa.domain.com/Users")
ldapRequest =
"schemas": ["urn:scim:schemas:core:1.0" ]
"userName": "<EMAIL>"
"name":
"familyName": "email.domain.com"
"givenName": "<NAME>"
"emails": [
"value": "<EMAIL>"
]
"approvals": []
"active": true
"verified": true
"origin": "ldap"
uaaRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "user"
"name":
"familyName": "<NAME>",
"givenName": "<NAME>"
"emails": [
{
"value": "user"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "uaa",
"password": "<PASSWORD>"
samlRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "<EMAIL>"
"name":
"familyName": "<EMAIL>",
"givenName": "<NAME>"
"emails": [
{
"value": "<EMAIL>"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "saml",
"externalId" : "<EMAIL>"
if(equal(options.json,ldapRequest)||equal(options.json,uaaRequest)||equal(options.json,samlRequest))
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
else if(options.method=="POST" && options.url=="https://api.domain.com/v2/users"&&options.json.guid=="userGuid")
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else if(options.method=="GET" && options.url=="https://api.domain.com/v2/users/userGuid/managed_spaces?q=organization_guid:orgGuid")
callback( null,{"statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
mock('request',requestjs)
adminOauth = require "../../routes/AdminOauth"
cfapi = require("../../routes/cfapi")
serviceBindings = require "../../routes/serviceBindings"
serviceBindings["cloud_foundry_api-portal-admin-id"] = { b64 : "portal-admin-id-value"}
serviceBindings["cloud_foundry_api-portal-admin-pw"] = { b64 : "portal-admin-pw-value"}
serviceBindings["cloud_foundry_api-uaa-client-id"] = { b64 : "uaa-client-id-value"}
serviceBindings["cloud_foundry_api-uaa-client-secret"] = { b64 : "uaa-client-secret-value"}
serviceBindings["cloud_foundry_api-uaa-domain"] = { value:"uaa.domain.com"}
serviceBindings["cloud_foundry_api-domain"] = { value:"api.domain.com"}
serviceBindings["cloud_foundry_api-default-email-domain"] = { value: "email.domain.com"}
refreshToken = (method) ->
method
token:
access_token : "<PASSWORD>"
beforeEach ()->
adminOauth.refreshToken = refreshToken
it 'allOrganizations retrieves all organizations',(done)->
res =
json : (organizations) ->
expect(organizations.resources.length).to.equal(2)
expect(organizations.resources[0].entity.name).to.equal("org1")
expect(organizations.resources[0].metadata.guid).to.equal("org1Guid")
expect(organizations.resources[1].entity.name).to.equal("org2")
expect(organizations.resources[1].metadata.guid).to.equal("org2Guid")
done()
cfapi.allOrganizations
headers :
authorization : "Bearer oauthtoken"
,res
it 'userInfo retrieves currentUser Information', (done)->
res =
json : (userInfo) ->
expect(userInfo.user_id).to.equal("userGuid")
expect(userInfo.user_name).to.equal("userName")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.userInfo
headers :
authorization : "Bearer oauthtoken"
,res
it 'allUsers retrieves all users',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("user1")
expect(users.resources[0].metadata.guid).to.equal("user1Guid")
expect(users.resources[1].entity.name).to.equal("user2")
expect(users.resources[1].metadata.guid).to.equal("user2Guid")
done()
cfapi.allUsers
headers :
authorization : "Bearer oauthtoken"
,res
it 'listCfRequest retrieves all stuff to list (very generic)',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("mgr1")
expect(users.resources[0].metadata.guid).to.equal("mgr1Guid")
expect(users.resources[1].entity.name).to.equal("mgr2")
expect(users.resources[1].metadata.guid).to.equal("mgr2Guid")
done()
cfapi.listCfRequest
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
,res
it 'putRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("added")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.putRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'deleteRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("deleted")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.deleteRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'create user creates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "<EMAIL>"
identityProvider : "ldap"
org :
guid : "orgGuid"
manager : true
auditor : true
spaces : [
guid : "space1Guid"
manager : true
developer : false
auditor : false
,
guid : "space2Guid"
manager : false
developer : true
auditor : false
,
guid : "space3Guid"
manager : false
developer : false
auditor : true
]
,res
it 'create user uaa usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "<EMAIL>"
password : "<PASSWORD>"
identityProvider : "uaa"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res
it 'create user saml usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "<EMAIL>"
password : "<PASSWORD>"
identityProvider : "saml"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res | true | chai = require('chai')
chai.use(require('chai-string'));
expect = chai.expect
sinon = require('sinon')
mock = require 'mock-require'
equal = require 'deep-equal'
Promise = require 'promise'
describe 'cfapi ', ->
requestjs = (options,callback)->
if(options.url=="https://api.domain.com/v2/spaces?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 1
total_pages : 1
resources : [
metadata :
guid : "space1Guid"
entity :
name : "space1"
organization_guid : "org1Guid"
space_quota_definition_guid : "spaceQuotaGuid"
disk_quota : 1024
memory : 2048
space_guid : "space1Guid"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org1Guid"
entity :
name : "org1"
]
)
else if(options.url=="https://api.domain.com/v2/organizations?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "org2Guid"
entity :
name : "org2"
]
)
else if(options.url=="https://uaa.domain.com/userinfo")
callback(null,{ "statusCode" : 200}, JSON.stringify
user_id :"userGuid"
user_name : "userName"
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=1")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else if(options.url=="https://api.domain.com/v2/users?order-direction=asc&results-per-page=50&page=2")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user2Guid"
entity :
name : "user2"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=1&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr1Guid"
entity :
name : "mgr1"
]
)
else if(options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager?order-direction=asc&page=2&results-per-page=50")
callback(null,{ "statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "mgr2Guid"
entity :
name : "mgr2"
]
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="DELETE" && options.url=="https://api.domain.com/v2/spaces/spaceGuid/manager/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "deleted"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space2Guid/developers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space1Guid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/spaces/space3Guid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/users/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/managers/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="PUT"&& options.url=="https://api.domain.com/v2/organizations/orgGuid/auditors/userGuid")
callback(null,{ "statusCode" : 201}, JSON.stringify
result : "added"
)
else if(options.method=="POST"&& options.url=="https://uaa.domain.com/Users")
ldapRequest =
"schemas": ["urn:scim:schemas:core:1.0" ]
"userName": "PI:EMAIL:<EMAIL>END_PI"
"name":
"familyName": "email.domain.com"
"givenName": "PI:NAME:<NAME>END_PI"
"emails": [
"value": "PI:EMAIL:<EMAIL>END_PI"
]
"approvals": []
"active": true
"verified": true
"origin": "ldap"
uaaRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "user"
"name":
"familyName": "PI:NAME:<NAME>END_PI",
"givenName": "PI:NAME:<NAME>END_PI"
"emails": [
{
"value": "user"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "uaa",
"password": "PI:PASSWORD:<PASSWORD>END_PI"
samlRequest =
"schemas": [
"urn:scim:schemas:core:1.0"
]
"userName": "PI:EMAIL:<EMAIL>END_PI"
"name":
"familyName": "PI:EMAIL:<EMAIL>END_PI",
"givenName": "PI:NAME:<NAME>END_PI"
"emails": [
{
"value": "PI:EMAIL:<EMAIL>END_PI"
}
],
"approvals": [],
"active": true,
"verified": true,
"origin": "saml",
"externalId" : "PI:EMAIL:<EMAIL>END_PI"
if(equal(options.json,ldapRequest)||equal(options.json,uaaRequest)||equal(options.json,samlRequest))
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
else if(options.method=="POST" && options.url=="https://api.domain.com/v2/users"&&options.json.guid=="userGuid")
callback(null,{ "statusCode" : 201},
id : "userGuid"
)
else if(options.method=="GET" && options.url=="https://api.domain.com/v2/users/userGuid/managed_spaces?q=organization_guid:orgGuid")
callback( null,{"statusCode" : 200}, JSON.stringify
total_results : 2
total_pages : 2
resources : [
metadata :
guid : "user1Guid"
entity :
name : "user1"
]
)
else
console.log("failed to respond to request #{JSON.stringify(options,0,2)}")
mock('request',requestjs)
adminOauth = require "../../routes/AdminOauth"
cfapi = require("../../routes/cfapi")
serviceBindings = require "../../routes/serviceBindings"
serviceBindings["cloud_foundry_api-portal-admin-id"] = { b64 : "portal-admin-id-value"}
serviceBindings["cloud_foundry_api-portal-admin-pw"] = { b64 : "portal-admin-pw-value"}
serviceBindings["cloud_foundry_api-uaa-client-id"] = { b64 : "uaa-client-id-value"}
serviceBindings["cloud_foundry_api-uaa-client-secret"] = { b64 : "uaa-client-secret-value"}
serviceBindings["cloud_foundry_api-uaa-domain"] = { value:"uaa.domain.com"}
serviceBindings["cloud_foundry_api-domain"] = { value:"api.domain.com"}
serviceBindings["cloud_foundry_api-default-email-domain"] = { value: "email.domain.com"}
refreshToken = (method) ->
method
token:
access_token : "PI:PASSWORD:<PASSWORD>END_PI"
beforeEach ()->
adminOauth.refreshToken = refreshToken
it 'allOrganizations retrieves all organizations',(done)->
res =
json : (organizations) ->
expect(organizations.resources.length).to.equal(2)
expect(organizations.resources[0].entity.name).to.equal("org1")
expect(organizations.resources[0].metadata.guid).to.equal("org1Guid")
expect(organizations.resources[1].entity.name).to.equal("org2")
expect(organizations.resources[1].metadata.guid).to.equal("org2Guid")
done()
cfapi.allOrganizations
headers :
authorization : "Bearer oauthtoken"
,res
it 'userInfo retrieves currentUser Information', (done)->
res =
json : (userInfo) ->
expect(userInfo.user_id).to.equal("userGuid")
expect(userInfo.user_name).to.equal("userName")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.userInfo
headers :
authorization : "Bearer oauthtoken"
,res
it 'allUsers retrieves all users',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("user1")
expect(users.resources[0].metadata.guid).to.equal("user1Guid")
expect(users.resources[1].entity.name).to.equal("user2")
expect(users.resources[1].metadata.guid).to.equal("user2Guid")
done()
cfapi.allUsers
headers :
authorization : "Bearer oauthtoken"
,res
it 'listCfRequest retrieves all stuff to list (very generic)',(done)->
res =
json : (users) ->
expect(users.resources.length).to.equal(2)
expect(users.resources[0].entity.name).to.equal("mgr1")
expect(users.resources[0].metadata.guid).to.equal("mgr1Guid")
expect(users.resources[1].entity.name).to.equal("mgr2")
expect(users.resources[1].metadata.guid).to.equal("mgr2Guid")
done()
cfapi.listCfRequest
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
,res
it 'putRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("added")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.putRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'deleteRole delegates properly' ,(done)->
res =
json : (userInfo) ->
expect(userInfo.result).to.equal("deleted")
expect(res.statusCode).to.equal(201)
done()
res.status = (status)->
res.statusCode = status
res
cfapi.deleteRole
headers :
authorization : "Bearer oauthtoken"
params :
level : "spaces"
levelGuid : "spaceGuid"
associationType : "manager"
associationGuid : "userGuid"
,res
it 'create user creates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "PI:EMAIL:<EMAIL>END_PI"
identityProvider : "ldap"
org :
guid : "orgGuid"
manager : true
auditor : true
spaces : [
guid : "space1Guid"
manager : true
developer : false
auditor : false
,
guid : "space2Guid"
manager : false
developer : true
auditor : false
,
guid : "space3Guid"
manager : false
developer : false
auditor : true
]
,res
it 'create user uaa usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "PI:EMAIL:<EMAIL>END_PI"
password : "PI:PASSWORD:<PASSWORD>END_PI"
identityProvider : "uaa"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res
it 'create user saml usercreates correct requests' ,(done)->
res = {}
res.send = (message) ->
res.message = message
expect(res.statusCode).to.equal(201)
expect(res.message).to.equal("user created")
done()
res.status = (status)->
res.statusCode = status
res
cfapi.createUser
headers :
authorization : "Bearer oauthtoken"
body :
userId : "PI:EMAIL:<EMAIL>END_PI"
password : "PI:PASSWORD:<PASSWORD>END_PI"
identityProvider : "saml"
org :
guid : "orgGuid"
manager : false
auditor : true
spaces : [
]
,res |
[
{
"context": "n false else undefined)\n API.mail.send {to: 'alert@cottagelabs.com', subject: 'Sherpa Romeo index complete', text: '",
"end": 2453,
"score": 0.9999319911003113,
"start": 2432,
"tag": "EMAIL",
"value": "alert@cottagelabs.com"
},
{
"context": "ON.stringify(data,\"\"... | server/use/sherpa.coffee | leviathanindustries/noddy | 2 |
# docs http://www.sherpa.ac.uk/romeo/apimanual.php?la=en&fIDnum=|&mode=simple
# has an api key set in settings and should be appended as query param "ak"
# A romeo query for an issn is what is immediately required:
# http://www.sherpa.ac.uk/romeo/api29.php?issn=1444-1586
# returns an object in which <romeoapi version="2.9.9"><journals><journal> confirms the journal
# and <romeoapi version="2.9.9"><publishers><publisher><romeocolour> gives the romeo colour
# (interestingly Elsevier is green...)
import moment from 'moment'
import fs from 'fs'
sherpa_romeo = new API.collection {index:"sherpa",type:"romeo"}
API.use ?= {}
API.use.sherpa = {romeo:{}}
# searches the actual romeo API, and if find then if found, saves it to local sherpa_romeo index
# the local index can be populated using routes below, and the local index can be searched using the route below without /search
API.add 'use/sherpa/romeo/search',
get: () ->
xml = false
format = true
if this.queryParams.xml?
xml = true
delete this.queryParams.xml
if this.queryParams.format?
format = false
delete this.queryParams.format
if xml
this.response.writeHead(200, {'Content-type': 'text/xml; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.use.sherpa.romeo.search this.queryParams, xml
else
return API.use.sherpa.romeo.search this.queryParams, xml, format
API.add 'use/sherpa/romeo/find', get: () -> return API.use.sherpa.romeo.find this.queryParams
API.add 'use/sherpa/romeo/issn/:issn', get: () -> return API.use.sherpa.romeo.search {issn:this.urlParams.issn}
API.add 'use/sherpa/romeo/colour/:issn', get: () -> return API.use.sherpa.romeo.colour this.urlParams.issn
API.add 'use/sherpa/romeo/updated', get: () -> return API.use.sherpa.romeo.updated()
API.add 'use/sherpa/romeo/download',
get:
roleRequired:'root'
action: () ->
return API.use.sherpa.romeo.download(this.queryParams.local)
API.add 'use/sherpa/romeo/download.csv',
get:
roleRequired:'root'
action: () ->
API.convert.json2csv2response(this,API.use.sherpa.romeo.download(this.queryParams.disk).data)
API.add 'use/sherpa/romeo/index',
get:
roleRequired:'root'
action: () ->
res = API.use.sherpa.romeo.index (if this.queryParams.update? then true else undefined), (if this.queryParams.local? then false else undefined)
API.mail.send {to: 'alert@cottagelabs.com', subject: 'Sherpa Romeo index complete', text: 'Done'}
return res
delete:
roleRequired:'root'
action: () ->
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
return true
# INFO: sherpa romeo is one dataset, and fact and ref are built from it. Opendoar is the repo directory, a separate dataset
API.add 'use/sherpa/romeo', () -> return sherpa_romeo.search this
API.use.sherpa.romeo.search = (params,xml=false,format=true) ->
if params.title?
params.jtitle = params.title
delete params.title
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/romeo/api29.php?ak=' + apikey + '&'
url += q + '=' + params[q] + '&' for q of params
API.log 'Using sherpa romeo for ' + url
try
res = HTTP.call 'GET', url
if res.statusCode is 200
if xml
return res.content
else
result = API.convert.xml2json res.content, undefined, false
if format
return API.use.sherpa.romeo.format {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.find = (q) ->
found = sherpa_romeo.find q
if not found
rem = API.use.sherpa.romeo.search q
if rem? and typeof rem is 'object' and rem.status isnt 'error'
sherpa_romeo.insert rem
found = rem
return found
API.use.sherpa.romeo.colour = (issn) ->
if rec = sherpa_romeo.find({issn: issn}) and rec.publisher?.colour?
return rec.publisher.colour
else
resp = API.use.sherpa.romeo.search {issn:issn}
try
return resp.publishers[0].publisher[0].romeocolour[0]
catch err
return { status: 'error', data: resp, error: err}
API.use.sherpa.romeo.updated = () ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/downloads/download-dates.php?ak=' + apikey
try
res = HTTP.call 'GET', url
if res.statusCode is 200
result = API.convert.xml2json res.content
ret =
publishers:
added: result['download-dates'].publisherspolicies[0].latestaddition[0]
updated: result['download-dates'].publisherspolicies[0].latestupdate[0]
journals:
added: result['download-dates'].journals[0].latestaddition[0]
updated: result['download-dates'].journals[0].latestupdate[0]
ret.latest = if moment(ret.publishers.added).valueOf() > moment(ret.publishers.updated).valueOf() then ret.publishers.added else ret.publishers.updated
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.added).valueOf() then ret.latest else ret.journals.added
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.updated).valueOf() then ret.latest else ret.journals.updated
try ret.last = sherpa_romeo.find('*', true).created_date
ret.new = not ret.last? or moment(ret.latest).valueOf() > moment(ret.last,'YYYY-MM-DD HHmm.ss').valueOf()
return ret
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.format = (res, romeoID) ->
rec = {journal:{},publisher:{}}
rec.romeoID = romeoID if romeoID
if res.journals? and res.journals.length and res.journals[0].journal? and res.journals[0].journal.length
for j of res.journals[0].journal[0]
rec.journal[j] = res.journals[0].journal[0][j][0] if res.journals[0].journal[0][j].length and res.journals[0].journal[0][j][0]
rec.journal.title = rec.journal.jtitle if rec.journal.jtitle? and not rec.journal.title?
if res.publishers? and res.publishers.length and res.publishers[0].publisher? and res.publishers[0].publisher.length
publisher = res.publishers[0].publisher[0]
for p of publisher
if p is '$'
rec.publisher.sherpa_id = publisher[p].id
rec.publisher.sherpa_parent_id = publisher[p].parentid
else if p in ['preprints','postprints','pdfversion']
if publisher[p].length
rec.publisher[p] = {}
for ps of publisher[p][0]
if publisher[p][0][ps].length
if publisher[p][0][ps].length > 1
rec.publisher[p][ps] = []
for psr of publisher[p][0][ps]
rec.publisher[p][ps].push(publisher[p][0][ps][psr].replace(/<.*?>/g,'')) if typeof publisher[p][0][ps][psr] is 'string' and publisher[p][0][ps][psr].replace(/<.*?>/g,'')
else
rec.publisher[p][ps] = publisher[p][0][ps][0].replace(/<.*?>/g,'') if typeof publisher[p][0][ps][0] is 'string' and publisher[p][0][ps][0].replace(/<.*?>/g,'')
rec.publisher[p][ps] = [] if not rec.publisher[p][ps]? and ps.indexOf('restrictions') isnt -1
else if ps.indexOf('restrictions') isnt -1
rec.publisher[p][ps] = []
else if p is 'conditions' and publisher[p].length and typeof publisher[p][0] is 'object' and publisher[p][0].condition? and publisher[p][0].condition.length
rec.publisher.conditions = []
for c in publisher[p][0].condition
rec.publisher.conditions.push(c.replace(/<.*?>/g,'')) if typeof c is 'string' and c.replace(/<.*?>/g,'')
else if p is 'mandates' and publisher[p].length
rec.publisher.mandates = []
if typeof publisher[p][0] is 'string'
for pm in publisher[p]
rec.publisher.mandates.push(pm) if pm
else if typeof publisher[p][0] is 'object' and publisher[p][0].mandate? and publisher[p][0].mandate.length
for pm in publisher[p][0].mandate
rec.publisher.mandates.push(pm) if pm
else if p is 'paidaccess'
for pm of publisher[p][0]
rec.publisher[pm] = publisher[p][0][pm][0] if publisher[p][0][pm].length and publisher[p][0][pm][0]
else if p is 'copyrightlinks'
if publisher[p][0].copyrightlink
rec.publisher.copyright = []
for pc of publisher[p][0].copyrightlink
rec.publisher.copyright.push {url: publisher[p][0].copyrightlink[pc].copyrightlinkurl[0], text: publisher[p][0].copyrightlink[pc].copyrightlinktext[0]}
else if p is 'romeocolour'
rec.publisher.colour = publisher[p][0]
rec.colour = rec.publisher.colour
rec.color = rec.colour
else if p in ['dateadded','dateupdated']
rec.publisher['sherpa_' + p.replace('date','') + '_date'] = publisher[p][0] #.replace(':','').replace(':','.')
else
rec.publisher[p] = publisher[p][0]
rec.publisher.url = rec.publisher[p] if p is 'homeurl'
return rec
API.use.sherpa.romeo.download = (local=true) ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
updated = API.use.sherpa.romeo.updated()
localcopy = '.sherpa_romeo_data.csv'
if fs.existsSync(localcopy) and local and moment(updated.latest).valueOf() < fs.statSync(localcopy).mtime
try
local = JSON.parse fs.readFileSync localcopy
if local.length
return {total: local.length, data: local}
try
url = 'http://www.sherpa.ac.uk/downloads/journal-issns.php?format=csv&ak=' + apikey
res = HTTP.call 'GET', url # gets a list of journal ISSNs
if res.statusCode is 200
js = API.convert.csv2json res.content
#js = js.slice(50,70)
issns = [] # we seem to get dups from the sherpa lists...
dups = []
data = []
for r in js
try
issn = r.ISSN.trim().replace(' ','-')
if issn not in issns
res = API.use.sherpa.romeo.search {issn:issn}
try res.journal?.issn ?= issn # some ISSNs in the sherpa download never resolve to anything, so store an empty record with just the ISSN
try res.romeoID = r['RoMEO Record ID']
data.push res
issns.push res.journal.issn
else
dups.push issn
fs.writeFileSync localcopy, JSON.stringify(data,"",2)
API.mail.send {to: 'alert@cottagelabs.com', subject: 'Sherpa Romeo download complete', text: 'Done, with ' + data.length + ' records and ' + dups.length + ' duplicates'}
return { total: data.length, duplicates: dups.length, data: data}
else
return { status: 'error', data: res}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.index = (update=API.use.sherpa.romeo.updated().new,local) ->
if update
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
try
return sherpa_romeo.import API.use.sherpa.romeo.download(local).data
catch err
return {status: 'error', err: err}
else
return 'Already up to date'
API.use.sherpa.test = (verbose) ->
console.log('Starting sherpa test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.sherpa = API.use.sherpa.romeo.search {issn: '1748-4995'}
return _.isEqual result.sherpa, API.use.sherpa.test._examples.record
() ->
result.colour = API.use.sherpa.romeo.colour '1748-4995'
return result.colour is 'green'
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending sherpa test') if API.settings.dev
return result
API.use.sherpa.test._examples = {
record: {
"journals": [
{
"journal": [
{
"jtitle": [
"Annals of Actuarial Science"
],
"issn": [
"1748-4995"
],
"zetocpub": [
"Cambridge University Press (CUP): PDF Allowed SR / Cambridge University Press (CUP)"
],
"romeopub": [
"Cambridge University Press (CUP)"
]
}
]
}
],
"publishers": [
{
"publisher": [
{
"$": {
"id": "27"
},
"name": [
"Cambridge University Press"
],
"alias": [
"CUP"
],
"homeurl": [
"http://www.cambridge.org/uk/"
],
"preprints": [
{
"prearchiving": [
"can"
],
"prerestrictions": [
""
]
}
],
"postprints": [
{
"postarchiving": [
"can"
],
"postrestrictions": [
""
]
}
],
"pdfversion": [
{
"pdfarchiving": [
"cannot"
],
"pdfrestrictions": [
""
]
}
],
"conditions": [
{
"condition": [
"Author's Pre-print on author's personal website, departmental website, social media websites, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv",
"Author's post-print for HSS journals, on author's personal website, departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, on acceptance of publication",
"Author's post-print for STM journals, on author's personal website on acceptance of publication",
"Author's post-print for STM journals, on departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, after a <num>6</num> <period units=\"month\">months</period> embargo",
"Publisher's version/PDF cannot be used",
"Published abstract may be deposited",
"Pre-print to record acceptance for publication",
"Publisher copyright and source must be acknowledged",
"Must link to publisher version or journal website",
"Publisher last reviewed on 07/10/2014"
]
}
],
"mandates": [
""
],
"paidaccess": [
{
"paidaccessurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4576"
],
"paidaccessname": [
"Cambridge Open"
],
"paidaccessnotes": [
"A paid open access option is available for this journal."
]
}
],
"copyrightlinks": [
{
"copyrightlink": [
{
"copyrightlinktext": [
"Open Access Options"
],
"copyrightlinkurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4608"
]
}
]
}
],
"romeocolour": [
"green"
],
"dateadded": [
"2004-01-10 00:00:00"
],
"dateupdated": [
"2014-10-07 15:16:19"
]
}
]
}
]
}
} | 225776 |
# docs http://www.sherpa.ac.uk/romeo/apimanual.php?la=en&fIDnum=|&mode=simple
# has an api key set in settings and should be appended as query param "ak"
# A romeo query for an issn is what is immediately required:
# http://www.sherpa.ac.uk/romeo/api29.php?issn=1444-1586
# returns an object in which <romeoapi version="2.9.9"><journals><journal> confirms the journal
# and <romeoapi version="2.9.9"><publishers><publisher><romeocolour> gives the romeo colour
# (interestingly Elsevier is green...)
import moment from 'moment'
import fs from 'fs'
sherpa_romeo = new API.collection {index:"sherpa",type:"romeo"}
API.use ?= {}
API.use.sherpa = {romeo:{}}
# searches the actual romeo API, and if find then if found, saves it to local sherpa_romeo index
# the local index can be populated using routes below, and the local index can be searched using the route below without /search
API.add 'use/sherpa/romeo/search',
get: () ->
xml = false
format = true
if this.queryParams.xml?
xml = true
delete this.queryParams.xml
if this.queryParams.format?
format = false
delete this.queryParams.format
if xml
this.response.writeHead(200, {'Content-type': 'text/xml; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.use.sherpa.romeo.search this.queryParams, xml
else
return API.use.sherpa.romeo.search this.queryParams, xml, format
API.add 'use/sherpa/romeo/find', get: () -> return API.use.sherpa.romeo.find this.queryParams
API.add 'use/sherpa/romeo/issn/:issn', get: () -> return API.use.sherpa.romeo.search {issn:this.urlParams.issn}
API.add 'use/sherpa/romeo/colour/:issn', get: () -> return API.use.sherpa.romeo.colour this.urlParams.issn
API.add 'use/sherpa/romeo/updated', get: () -> return API.use.sherpa.romeo.updated()
API.add 'use/sherpa/romeo/download',
get:
roleRequired:'root'
action: () ->
return API.use.sherpa.romeo.download(this.queryParams.local)
API.add 'use/sherpa/romeo/download.csv',
get:
roleRequired:'root'
action: () ->
API.convert.json2csv2response(this,API.use.sherpa.romeo.download(this.queryParams.disk).data)
API.add 'use/sherpa/romeo/index',
get:
roleRequired:'root'
action: () ->
res = API.use.sherpa.romeo.index (if this.queryParams.update? then true else undefined), (if this.queryParams.local? then false else undefined)
API.mail.send {to: '<EMAIL>', subject: 'Sherpa Romeo index complete', text: 'Done'}
return res
delete:
roleRequired:'root'
action: () ->
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
return true
# INFO: sherpa romeo is one dataset, and fact and ref are built from it. Opendoar is the repo directory, a separate dataset
API.add 'use/sherpa/romeo', () -> return sherpa_romeo.search this
API.use.sherpa.romeo.search = (params,xml=false,format=true) ->
if params.title?
params.jtitle = params.title
delete params.title
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/romeo/api29.php?ak=' + apikey + '&'
url += q + '=' + params[q] + '&' for q of params
API.log 'Using sherpa romeo for ' + url
try
res = HTTP.call 'GET', url
if res.statusCode is 200
if xml
return res.content
else
result = API.convert.xml2json res.content, undefined, false
if format
return API.use.sherpa.romeo.format {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.find = (q) ->
found = sherpa_romeo.find q
if not found
rem = API.use.sherpa.romeo.search q
if rem? and typeof rem is 'object' and rem.status isnt 'error'
sherpa_romeo.insert rem
found = rem
return found
API.use.sherpa.romeo.colour = (issn) ->
if rec = sherpa_romeo.find({issn: issn}) and rec.publisher?.colour?
return rec.publisher.colour
else
resp = API.use.sherpa.romeo.search {issn:issn}
try
return resp.publishers[0].publisher[0].romeocolour[0]
catch err
return { status: 'error', data: resp, error: err}
API.use.sherpa.romeo.updated = () ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/downloads/download-dates.php?ak=' + apikey
try
res = HTTP.call 'GET', url
if res.statusCode is 200
result = API.convert.xml2json res.content
ret =
publishers:
added: result['download-dates'].publisherspolicies[0].latestaddition[0]
updated: result['download-dates'].publisherspolicies[0].latestupdate[0]
journals:
added: result['download-dates'].journals[0].latestaddition[0]
updated: result['download-dates'].journals[0].latestupdate[0]
ret.latest = if moment(ret.publishers.added).valueOf() > moment(ret.publishers.updated).valueOf() then ret.publishers.added else ret.publishers.updated
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.added).valueOf() then ret.latest else ret.journals.added
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.updated).valueOf() then ret.latest else ret.journals.updated
try ret.last = sherpa_romeo.find('*', true).created_date
ret.new = not ret.last? or moment(ret.latest).valueOf() > moment(ret.last,'YYYY-MM-DD HHmm.ss').valueOf()
return ret
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.format = (res, romeoID) ->
rec = {journal:{},publisher:{}}
rec.romeoID = romeoID if romeoID
if res.journals? and res.journals.length and res.journals[0].journal? and res.journals[0].journal.length
for j of res.journals[0].journal[0]
rec.journal[j] = res.journals[0].journal[0][j][0] if res.journals[0].journal[0][j].length and res.journals[0].journal[0][j][0]
rec.journal.title = rec.journal.jtitle if rec.journal.jtitle? and not rec.journal.title?
if res.publishers? and res.publishers.length and res.publishers[0].publisher? and res.publishers[0].publisher.length
publisher = res.publishers[0].publisher[0]
for p of publisher
if p is '$'
rec.publisher.sherpa_id = publisher[p].id
rec.publisher.sherpa_parent_id = publisher[p].parentid
else if p in ['preprints','postprints','pdfversion']
if publisher[p].length
rec.publisher[p] = {}
for ps of publisher[p][0]
if publisher[p][0][ps].length
if publisher[p][0][ps].length > 1
rec.publisher[p][ps] = []
for psr of publisher[p][0][ps]
rec.publisher[p][ps].push(publisher[p][0][ps][psr].replace(/<.*?>/g,'')) if typeof publisher[p][0][ps][psr] is 'string' and publisher[p][0][ps][psr].replace(/<.*?>/g,'')
else
rec.publisher[p][ps] = publisher[p][0][ps][0].replace(/<.*?>/g,'') if typeof publisher[p][0][ps][0] is 'string' and publisher[p][0][ps][0].replace(/<.*?>/g,'')
rec.publisher[p][ps] = [] if not rec.publisher[p][ps]? and ps.indexOf('restrictions') isnt -1
else if ps.indexOf('restrictions') isnt -1
rec.publisher[p][ps] = []
else if p is 'conditions' and publisher[p].length and typeof publisher[p][0] is 'object' and publisher[p][0].condition? and publisher[p][0].condition.length
rec.publisher.conditions = []
for c in publisher[p][0].condition
rec.publisher.conditions.push(c.replace(/<.*?>/g,'')) if typeof c is 'string' and c.replace(/<.*?>/g,'')
else if p is 'mandates' and publisher[p].length
rec.publisher.mandates = []
if typeof publisher[p][0] is 'string'
for pm in publisher[p]
rec.publisher.mandates.push(pm) if pm
else if typeof publisher[p][0] is 'object' and publisher[p][0].mandate? and publisher[p][0].mandate.length
for pm in publisher[p][0].mandate
rec.publisher.mandates.push(pm) if pm
else if p is 'paidaccess'
for pm of publisher[p][0]
rec.publisher[pm] = publisher[p][0][pm][0] if publisher[p][0][pm].length and publisher[p][0][pm][0]
else if p is 'copyrightlinks'
if publisher[p][0].copyrightlink
rec.publisher.copyright = []
for pc of publisher[p][0].copyrightlink
rec.publisher.copyright.push {url: publisher[p][0].copyrightlink[pc].copyrightlinkurl[0], text: publisher[p][0].copyrightlink[pc].copyrightlinktext[0]}
else if p is 'romeocolour'
rec.publisher.colour = publisher[p][0]
rec.colour = rec.publisher.colour
rec.color = rec.colour
else if p in ['dateadded','dateupdated']
rec.publisher['sherpa_' + p.replace('date','') + '_date'] = publisher[p][0] #.replace(':','').replace(':','.')
else
rec.publisher[p] = publisher[p][0]
rec.publisher.url = rec.publisher[p] if p is 'homeurl'
return rec
API.use.sherpa.romeo.download = (local=true) ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
updated = API.use.sherpa.romeo.updated()
localcopy = '.sherpa_romeo_data.csv'
if fs.existsSync(localcopy) and local and moment(updated.latest).valueOf() < fs.statSync(localcopy).mtime
try
local = JSON.parse fs.readFileSync localcopy
if local.length
return {total: local.length, data: local}
try
url = 'http://www.sherpa.ac.uk/downloads/journal-issns.php?format=csv&ak=' + apikey
res = HTTP.call 'GET', url # gets a list of journal ISSNs
if res.statusCode is 200
js = API.convert.csv2json res.content
#js = js.slice(50,70)
issns = [] # we seem to get dups from the sherpa lists...
dups = []
data = []
for r in js
try
issn = r.ISSN.trim().replace(' ','-')
if issn not in issns
res = API.use.sherpa.romeo.search {issn:issn}
try res.journal?.issn ?= issn # some ISSNs in the sherpa download never resolve to anything, so store an empty record with just the ISSN
try res.romeoID = r['RoMEO Record ID']
data.push res
issns.push res.journal.issn
else
dups.push issn
fs.writeFileSync localcopy, JSON.stringify(data,"",2)
API.mail.send {to: '<EMAIL>', subject: 'Sherpa Romeo download complete', text: 'Done, with ' + data.length + ' records and ' + dups.length + ' duplicates'}
return { total: data.length, duplicates: dups.length, data: data}
else
return { status: 'error', data: res}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.index = (update=API.use.sherpa.romeo.updated().new,local) ->
if update
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
try
return sherpa_romeo.import API.use.sherpa.romeo.download(local).data
catch err
return {status: 'error', err: err}
else
return 'Already up to date'
API.use.sherpa.test = (verbose) ->
console.log('Starting sherpa test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.sherpa = API.use.sherpa.romeo.search {issn: '1748-4995'}
return _.isEqual result.sherpa, API.use.sherpa.test._examples.record
() ->
result.colour = API.use.sherpa.romeo.colour '1748-4995'
return result.colour is 'green'
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending sherpa test') if API.settings.dev
return result
API.use.sherpa.test._examples = {
record: {
"journals": [
{
"journal": [
{
"jtitle": [
"Annals of Actuarial Science"
],
"issn": [
"1748-4995"
],
"zetocpub": [
"Cambridge University Press (CUP): PDF Allowed SR / Cambridge University Press (CUP)"
],
"romeopub": [
"Cambridge University Press (CUP)"
]
}
]
}
],
"publishers": [
{
"publisher": [
{
"$": {
"id": "27"
},
"name": [
"Cambridge University Press"
],
"alias": [
"CUP"
],
"homeurl": [
"http://www.cambridge.org/uk/"
],
"preprints": [
{
"prearchiving": [
"can"
],
"prerestrictions": [
""
]
}
],
"postprints": [
{
"postarchiving": [
"can"
],
"postrestrictions": [
""
]
}
],
"pdfversion": [
{
"pdfarchiving": [
"cannot"
],
"pdfrestrictions": [
""
]
}
],
"conditions": [
{
"condition": [
"Author's Pre-print on author's personal website, departmental website, social media websites, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv",
"Author's post-print for HSS journals, on author's personal website, departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, on acceptance of publication",
"Author's post-print for STM journals, on author's personal website on acceptance of publication",
"Author's post-print for STM journals, on departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, after a <num>6</num> <period units=\"month\">months</period> embargo",
"Publisher's version/PDF cannot be used",
"Published abstract may be deposited",
"Pre-print to record acceptance for publication",
"Publisher copyright and source must be acknowledged",
"Must link to publisher version or journal website",
"Publisher last reviewed on 07/10/2014"
]
}
],
"mandates": [
""
],
"paidaccess": [
{
"paidaccessurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4576"
],
"paidaccessname": [
"Cambridge Open"
],
"paidaccessnotes": [
"A paid open access option is available for this journal."
]
}
],
"copyrightlinks": [
{
"copyrightlink": [
{
"copyrightlinktext": [
"Open Access Options"
],
"copyrightlinkurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4608"
]
}
]
}
],
"romeocolour": [
"green"
],
"dateadded": [
"2004-01-10 00:00:00"
],
"dateupdated": [
"2014-10-07 15:16:19"
]
}
]
}
]
}
} | true |
# docs http://www.sherpa.ac.uk/romeo/apimanual.php?la=en&fIDnum=|&mode=simple
# has an api key set in settings and should be appended as query param "ak"
# A romeo query for an issn is what is immediately required:
# http://www.sherpa.ac.uk/romeo/api29.php?issn=1444-1586
# returns an object in which <romeoapi version="2.9.9"><journals><journal> confirms the journal
# and <romeoapi version="2.9.9"><publishers><publisher><romeocolour> gives the romeo colour
# (interestingly Elsevier is green...)
import moment from 'moment'
import fs from 'fs'
sherpa_romeo = new API.collection {index:"sherpa",type:"romeo"}
API.use ?= {}
API.use.sherpa = {romeo:{}}
# searches the actual romeo API, and if find then if found, saves it to local sherpa_romeo index
# the local index can be populated using routes below, and the local index can be searched using the route below without /search
API.add 'use/sherpa/romeo/search',
get: () ->
xml = false
format = true
if this.queryParams.xml?
xml = true
delete this.queryParams.xml
if this.queryParams.format?
format = false
delete this.queryParams.format
if xml
this.response.writeHead(200, {'Content-type': 'text/xml; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.use.sherpa.romeo.search this.queryParams, xml
else
return API.use.sherpa.romeo.search this.queryParams, xml, format
API.add 'use/sherpa/romeo/find', get: () -> return API.use.sherpa.romeo.find this.queryParams
API.add 'use/sherpa/romeo/issn/:issn', get: () -> return API.use.sherpa.romeo.search {issn:this.urlParams.issn}
API.add 'use/sherpa/romeo/colour/:issn', get: () -> return API.use.sherpa.romeo.colour this.urlParams.issn
API.add 'use/sherpa/romeo/updated', get: () -> return API.use.sherpa.romeo.updated()
API.add 'use/sherpa/romeo/download',
get:
roleRequired:'root'
action: () ->
return API.use.sherpa.romeo.download(this.queryParams.local)
API.add 'use/sherpa/romeo/download.csv',
get:
roleRequired:'root'
action: () ->
API.convert.json2csv2response(this,API.use.sherpa.romeo.download(this.queryParams.disk).data)
API.add 'use/sherpa/romeo/index',
get:
roleRequired:'root'
action: () ->
res = API.use.sherpa.romeo.index (if this.queryParams.update? then true else undefined), (if this.queryParams.local? then false else undefined)
API.mail.send {to: 'PI:EMAIL:<EMAIL>END_PI', subject: 'Sherpa Romeo index complete', text: 'Done'}
return res
delete:
roleRequired:'root'
action: () ->
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
return true
# INFO: sherpa romeo is one dataset, and fact and ref are built from it. Opendoar is the repo directory, a separate dataset
API.add 'use/sherpa/romeo', () -> return sherpa_romeo.search this
API.use.sherpa.romeo.search = (params,xml=false,format=true) ->
if params.title?
params.jtitle = params.title
delete params.title
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/romeo/api29.php?ak=' + apikey + '&'
url += q + '=' + params[q] + '&' for q of params
API.log 'Using sherpa romeo for ' + url
try
res = HTTP.call 'GET', url
if res.statusCode is 200
if xml
return res.content
else
result = API.convert.xml2json res.content, undefined, false
if format
return API.use.sherpa.romeo.format {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return {journals: result.romeoapi.journals, publishers: result.romeoapi.publishers}
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.find = (q) ->
found = sherpa_romeo.find q
if not found
rem = API.use.sherpa.romeo.search q
if rem? and typeof rem is 'object' and rem.status isnt 'error'
sherpa_romeo.insert rem
found = rem
return found
API.use.sherpa.romeo.colour = (issn) ->
if rec = sherpa_romeo.find({issn: issn}) and rec.publisher?.colour?
return rec.publisher.colour
else
resp = API.use.sherpa.romeo.search {issn:issn}
try
return resp.publishers[0].publisher[0].romeocolour[0]
catch err
return { status: 'error', data: resp, error: err}
API.use.sherpa.romeo.updated = () ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
url = 'http://www.sherpa.ac.uk/downloads/download-dates.php?ak=' + apikey
try
res = HTTP.call 'GET', url
if res.statusCode is 200
result = API.convert.xml2json res.content
ret =
publishers:
added: result['download-dates'].publisherspolicies[0].latestaddition[0]
updated: result['download-dates'].publisherspolicies[0].latestupdate[0]
journals:
added: result['download-dates'].journals[0].latestaddition[0]
updated: result['download-dates'].journals[0].latestupdate[0]
ret.latest = if moment(ret.publishers.added).valueOf() > moment(ret.publishers.updated).valueOf() then ret.publishers.added else ret.publishers.updated
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.added).valueOf() then ret.latest else ret.journals.added
ret.latest = if moment(ret.latest).valueOf() > moment(ret.journals.updated).valueOf() then ret.latest else ret.journals.updated
try ret.last = sherpa_romeo.find('*', true).created_date
ret.new = not ret.last? or moment(ret.latest).valueOf() > moment(ret.last,'YYYY-MM-DD HHmm.ss').valueOf()
return ret
else
return { status: 'error', data: result}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.format = (res, romeoID) ->
rec = {journal:{},publisher:{}}
rec.romeoID = romeoID if romeoID
if res.journals? and res.journals.length and res.journals[0].journal? and res.journals[0].journal.length
for j of res.journals[0].journal[0]
rec.journal[j] = res.journals[0].journal[0][j][0] if res.journals[0].journal[0][j].length and res.journals[0].journal[0][j][0]
rec.journal.title = rec.journal.jtitle if rec.journal.jtitle? and not rec.journal.title?
if res.publishers? and res.publishers.length and res.publishers[0].publisher? and res.publishers[0].publisher.length
publisher = res.publishers[0].publisher[0]
for p of publisher
if p is '$'
rec.publisher.sherpa_id = publisher[p].id
rec.publisher.sherpa_parent_id = publisher[p].parentid
else if p in ['preprints','postprints','pdfversion']
if publisher[p].length
rec.publisher[p] = {}
for ps of publisher[p][0]
if publisher[p][0][ps].length
if publisher[p][0][ps].length > 1
rec.publisher[p][ps] = []
for psr of publisher[p][0][ps]
rec.publisher[p][ps].push(publisher[p][0][ps][psr].replace(/<.*?>/g,'')) if typeof publisher[p][0][ps][psr] is 'string' and publisher[p][0][ps][psr].replace(/<.*?>/g,'')
else
rec.publisher[p][ps] = publisher[p][0][ps][0].replace(/<.*?>/g,'') if typeof publisher[p][0][ps][0] is 'string' and publisher[p][0][ps][0].replace(/<.*?>/g,'')
rec.publisher[p][ps] = [] if not rec.publisher[p][ps]? and ps.indexOf('restrictions') isnt -1
else if ps.indexOf('restrictions') isnt -1
rec.publisher[p][ps] = []
else if p is 'conditions' and publisher[p].length and typeof publisher[p][0] is 'object' and publisher[p][0].condition? and publisher[p][0].condition.length
rec.publisher.conditions = []
for c in publisher[p][0].condition
rec.publisher.conditions.push(c.replace(/<.*?>/g,'')) if typeof c is 'string' and c.replace(/<.*?>/g,'')
else if p is 'mandates' and publisher[p].length
rec.publisher.mandates = []
if typeof publisher[p][0] is 'string'
for pm in publisher[p]
rec.publisher.mandates.push(pm) if pm
else if typeof publisher[p][0] is 'object' and publisher[p][0].mandate? and publisher[p][0].mandate.length
for pm in publisher[p][0].mandate
rec.publisher.mandates.push(pm) if pm
else if p is 'paidaccess'
for pm of publisher[p][0]
rec.publisher[pm] = publisher[p][0][pm][0] if publisher[p][0][pm].length and publisher[p][0][pm][0]
else if p is 'copyrightlinks'
if publisher[p][0].copyrightlink
rec.publisher.copyright = []
for pc of publisher[p][0].copyrightlink
rec.publisher.copyright.push {url: publisher[p][0].copyrightlink[pc].copyrightlinkurl[0], text: publisher[p][0].copyrightlink[pc].copyrightlinktext[0]}
else if p is 'romeocolour'
rec.publisher.colour = publisher[p][0]
rec.colour = rec.publisher.colour
rec.color = rec.colour
else if p in ['dateadded','dateupdated']
rec.publisher['sherpa_' + p.replace('date','') + '_date'] = publisher[p][0] #.replace(':','').replace(':','.')
else
rec.publisher[p] = publisher[p][0]
rec.publisher.url = rec.publisher[p] if p is 'homeurl'
return rec
API.use.sherpa.romeo.download = (local=true) ->
apikey = API.settings.use?.romeo?.apikey
return { status: 'error', data: 'NO ROMEO API KEY PRESENT!'} if not apikey
updated = API.use.sherpa.romeo.updated()
localcopy = '.sherpa_romeo_data.csv'
if fs.existsSync(localcopy) and local and moment(updated.latest).valueOf() < fs.statSync(localcopy).mtime
try
local = JSON.parse fs.readFileSync localcopy
if local.length
return {total: local.length, data: local}
try
url = 'http://www.sherpa.ac.uk/downloads/journal-issns.php?format=csv&ak=' + apikey
res = HTTP.call 'GET', url # gets a list of journal ISSNs
if res.statusCode is 200
js = API.convert.csv2json res.content
#js = js.slice(50,70)
issns = [] # we seem to get dups from the sherpa lists...
dups = []
data = []
for r in js
try
issn = r.ISSN.trim().replace(' ','-')
if issn not in issns
res = API.use.sherpa.romeo.search {issn:issn}
try res.journal?.issn ?= issn # some ISSNs in the sherpa download never resolve to anything, so store an empty record with just the ISSN
try res.romeoID = r['RoMEO Record ID']
data.push res
issns.push res.journal.issn
else
dups.push issn
fs.writeFileSync localcopy, JSON.stringify(data,"",2)
API.mail.send {to: 'PI:EMAIL:<EMAIL>END_PI', subject: 'Sherpa Romeo download complete', text: 'Done, with ' + data.length + ' records and ' + dups.length + ' duplicates'}
return { total: data.length, duplicates: dups.length, data: data}
else
return { status: 'error', data: res}
catch err
return { status: 'error', error: err}
API.use.sherpa.romeo.index = (update=API.use.sherpa.romeo.updated().new,local) ->
if update
sherpa_romeo.remove('*') if sherpa_romeo.count() isnt 0
try
return sherpa_romeo.import API.use.sherpa.romeo.download(local).data
catch err
return {status: 'error', err: err}
else
return 'Already up to date'
API.use.sherpa.test = (verbose) ->
console.log('Starting sherpa test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.sherpa = API.use.sherpa.romeo.search {issn: '1748-4995'}
return _.isEqual result.sherpa, API.use.sherpa.test._examples.record
() ->
result.colour = API.use.sherpa.romeo.colour '1748-4995'
return result.colour is 'green'
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending sherpa test') if API.settings.dev
return result
API.use.sherpa.test._examples = {
record: {
"journals": [
{
"journal": [
{
"jtitle": [
"Annals of Actuarial Science"
],
"issn": [
"1748-4995"
],
"zetocpub": [
"Cambridge University Press (CUP): PDF Allowed SR / Cambridge University Press (CUP)"
],
"romeopub": [
"Cambridge University Press (CUP)"
]
}
]
}
],
"publishers": [
{
"publisher": [
{
"$": {
"id": "27"
},
"name": [
"Cambridge University Press"
],
"alias": [
"CUP"
],
"homeurl": [
"http://www.cambridge.org/uk/"
],
"preprints": [
{
"prearchiving": [
"can"
],
"prerestrictions": [
""
]
}
],
"postprints": [
{
"postarchiving": [
"can"
],
"postrestrictions": [
""
]
}
],
"pdfversion": [
{
"pdfarchiving": [
"cannot"
],
"pdfrestrictions": [
""
]
}
],
"conditions": [
{
"condition": [
"Author's Pre-print on author's personal website, departmental website, social media websites, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv",
"Author's post-print for HSS journals, on author's personal website, departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, on acceptance of publication",
"Author's post-print for STM journals, on author's personal website on acceptance of publication",
"Author's post-print for STM journals, on departmental website, institutional repository, non-commercial subject-based repositories, such as PubMed Central, Europe PMC or arXiv, after a <num>6</num> <period units=\"month\">months</period> embargo",
"Publisher's version/PDF cannot be used",
"Published abstract may be deposited",
"Pre-print to record acceptance for publication",
"Publisher copyright and source must be acknowledged",
"Must link to publisher version or journal website",
"Publisher last reviewed on 07/10/2014"
]
}
],
"mandates": [
""
],
"paidaccess": [
{
"paidaccessurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4576"
],
"paidaccessname": [
"Cambridge Open"
],
"paidaccessnotes": [
"A paid open access option is available for this journal."
]
}
],
"copyrightlinks": [
{
"copyrightlink": [
{
"copyrightlinktext": [
"Open Access Options"
],
"copyrightlinkurl": [
"http://journals.cambridge.org/action/displaySpecialPage?pageId=4608"
]
}
]
}
],
"romeocolour": [
"green"
],
"dateadded": [
"2004-01-10 00:00:00"
],
"dateupdated": [
"2014-10-07 15:16:19"
]
}
]
}
]
}
} |
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998444318771362,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/import/md5.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
The MD5 Model format written by ID Software for Doom3
http://www.3dgep.com/loading-and-animating-md5-models-with-opengl
###
{PXLWarning, PXLError, PXLLog} = require '../util/log'
{TriangleMesh, Triangle, Vertex} = require '../geometry/primitive'
{Vec4, Vec3, Vec2, Quaternion, Matrix4, Matrix3} = require '../math/math'
{Node} = require '../core/node'
{RGB, RGBA} = require '../colour/colour'
{Promise} = require '../util/promise'
{Request} = require '../util/request'
{PhongMaterial} = require '../material/phong'
{BasicColourMaterial} = require '../material/basic'
{Skeleton, Bone, Skin, SkinWeight, SkinIndex} = require '../animation/skeleton'
# ## MD5Model
# Loads an MD5 Model creating a set of nodes, materials and a skeleton
# MD5 is one of the widely used ID Software Model formats
# Regarding materials, for now we just load the nearest texture in the directory
class MD5Model extends Node
# **@constructor** for OBJ
# - **url** - a String - Required
# - **promise** - a Promise
# - **params** - NOT CURRENTLY USED
# TODO - We may wish to consider how this fits with queue and loading items :O
# TODO - Remove the queue once its finished with?
constructor : (@url, @promise, @params) ->
super()
@version = ""
@num_joints = ""
@num_meshes = ""
@add new Skeleton() # as this is a node, it ends up added at the node level
# Three promises, chained in order
promise_textures = new Promise()
promise_data = new Promise()
promise_main = new Promise()
# As Promise data is resolved after promise textures, we just have one here
promise_main.when(promise_data).then () =>
@promise.resolve()
promise_textures.then (text_data) =>
@_parse_data(text_data)
promise_data.resolve() # Assuming parse_data never goes wrong :P
load_data_promise = () =>
r = new Request(@url)
r.get (data) =>
@_parse_materials(data, promise_textures)
if @promise?
# Create a set of promises
load_data_promise()
else
# Make a synchronous get request
onerror = (result) =>
PXLError "Loading Model: " + url + " " + result
r = new Request(@url)
r.get( (data) =>
@_parse_materials_sync(data)
@_parse_data(data)
,onerror,true)
@
_computeW : (r0,r1,r2) ->
t = 1.0 - (r0 * r0) - (r1 * r1) - (r2 * r2)
if t < 0.0
return 0.0
t = -Math.sqrt(t)
t
_parse_materials_sync : (text_data) ->
@
# This function is tricky with all the promises it creates. It creates one master promise
# and then several sub promises with get requests in order to go and load the various images
# we need to create our materials.
_parse_materials : (text_data, promise_textures) ->
# Hunt fot any shader lines
lines = text_data.split("\n");
midx = 0
base_path = @url[0..@url.lastIndexOf("/")-1]
# Temporary, clean up later
_material_promises = []
@_material_by_name = {}
for midx in [0..lines.length-1]
line = lines[midx]
if line.indexOf("shader") != -1
lastquote = line.lastIndexOf('"')
firstquote = line.indexOf('"')
material_path = line[firstquote+1..lastquote-1]
# Cheat a bit here - assuming there is a tga of the same name as the shader, for now
# TODO - Will need to change this sooner
material_url = base_path + "/" + material_path[material_path.lastIndexOf("/")+1..] + ".png"
p = new Promise()
_material_promises.push p
# A closure with all the data we need to setup this material
onsuccess_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (_texture) =>
if PXL.Context.debug
PXLLog "MD5Model Loaded a Texture: " + _material_path
# default to phong with low specular
# TODO Eventually we'll do this properly
wh = new RGB.WHITE()
spec = new RGB.BLACK()
__material_by_name[_material_path] = new PhongMaterial wh, _texture, spec
_p.resolve()
# Closure for when we cant load our texture - default to a white texture
onerror_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (msg) =>
# ignore and use a normal material
if PXL.Context.debug
PXLLog "MD5Model Failed to load a Texture: " + _material_path
wh = new PXL.Colour.RGB 1.0,0.0,0.0
__material_by_name[_material_path] = new BasicColourMaterial wh
_p.resolve()
PXL.GL.textureFromURL material_url, onsuccess_closure(), onerror_closure()
# Grab all the textures we need - if they dont exist, replace with a
# white plain material for now. Eventually we'll check a material file
promise_materials = new Promise()
promise_materials.when.apply(promise_materials, _material_promises).then () =>
promise_textures.resolve(text_data)
@
_parse_data: (text_data) ->
# Could be heavy if the file is big :S
lines = text_data.split("\n");
midx = 0
# Create a temp joints array as we need to compute vertices with
# them at the end of each mesh
while midx < lines.length
line = lines[midx]
if line[0..9] == "MD5Version"
@version = line[11..]
if line[0..8] == "numJoints"
@num_joints = parseInt(line[10..])
if line[0..8] == "numMeshes"
@num_meshes == parseInt(line[10..])
# Start looping over the joints - the bones basically
if line[0..7] == "joints {"
for jidx in [0..@num_joints-1]
jline = lines[midx + jidx + 1]
lastquote = jline.lastIndexOf('"')
name = jline[jline.indexOf('"')+1..lastquote-1]
openbrace = jline.indexOf('(')
closebrace = jline.indexOf(')')
parent_idx = parseInt(jline[lastquote+1..openbrace-1])
parent = undefined
# I believe all parents are listed in MD5 before their children
if parent_idx > -1
parent = @skeleton.getBone parent_idx
tokens = jline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
position = new Vec3(p0,p1,p2)
openbrace = jline.lastIndexOf('(')
closebrace = jline.lastIndexOf(')')
tokens = jline[openbrace..closebrace].split(" ")
r0 = parseFloat tokens[1]
r1 = parseFloat tokens[2]
r2 = parseFloat tokens[3]
rotation = new Quaternion r0, r1, r2, @_computeW(r0,r1,r2)
rotation.normalize()
bone = new Bone name, jidx, parent, rotation, position
@skeleton.addBone bone
midx += @num_joints
# Now we actually create the seperate meshes (one material per mesh we suspect)
# MD5 format calls the material a shader which is probably correct ;)
# We ignore shader for now but this requires loading external files so thats
# definitely a pre-parse step :S
if line[0..5] == "mesh {"
tline = lines[midx]
# Find the mesh for this shader
while tline.indexOf("shader") == -1
midx += 1
tline = lines[midx]
material_path = tline[tline.indexOf('"')+1..tline.lastIndexOf('"')-1]
while tline.indexOf("numverts") == -1
midx +=1
tline = lines[midx]
num_verts = parseInt(tline[tline.indexOf("numverts")+8..] )
# Create a subnode for our geometry and material
current_mesh = new TriangleMesh true
current_node = new Node current_mesh
# We should have all the materials by this point
current_node.material = @_material_by_name[material_path] if @_material_by_name?
@add current_node
# Now loop over the verts, though these arent actual verts - they are indices
# into the data really. First pair is the tex coords - second is the start index
# the next is the count
temp_verts = []
for vidx in [0..num_verts-1]
tline = lines[midx + vidx + 1]
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
idx = parseInt(tline[tline.indexOf("vert")+1..openbrace-1])
tokens = tline[openbrace..closebrace].split(" ")
u = parseFloat tokens[1]
v = parseFloat tokens[2]
tokens = tline[closebrace..].split(" ")
idx = parseInt tokens[1]
count = parseInt tokens[2]
temp_vert_struct =
u : new Vec2 u, v
i : idx
c : count
temp_verts.push temp_vert_struct
midx += num_verts
# Now hunt for the number of triangles
tline = lines[midx]
while tline.indexOf("numtris") == -1
midx +=1
tline = lines[midx]
num_tris = parseInt(tline[tline.indexOf("numtris")+7..])
# Add enough indices for all the points
for i in [0..(num_tris*3)-1]
current_mesh.addIndex(0)
tidx = 0
for tidx in [0..num_tris-1]
tline = lines[midx + tidx + 1]
tri = tline.indexOf("tri")
tokens = tline[tri..].split(" ")
idx = parseInt tokens[1]
a = parseInt tokens[2]
b = parseInt tokens[3]
c = parseInt tokens[4]
# Consider the winding
current_mesh.setIndex idx * 3, c
current_mesh.setIndex idx * 3 + 1, b
current_mesh.setIndex idx * 3 + 2, a
midx += num_tris
# Now hunt for the weights
tline = lines[midx]
while tline.indexOf("numweights") == -1
midx +=1
tline = lines[midx]
num_weights = parseInt(tline[tline.indexOf("numweights")+10..])
# Again we need a temporary weights array like temp verts etc
temp_weights = []
# Create a skin which we add to the current node
current_skin = new Skin()
for widx in [0..num_weights-1]
tline = lines[midx + widx + 1]
ws = tline.indexOf("weight")
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
tokens = tline[ws..openbrace].split(" ")
idx = parseInt tokens[1]
bone_id = parseInt tokens[2]
bias = parseFloat tokens[3]
skinweight = new SkinWeight @skeleton.getBone(bone_id), bias
current_skin.addWeight skinweight
tokens = tline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
# Temporary weights array push - apparently for the GPU benefit
temp_weights.push
position : new Vec3(p0,p1,p2)
bias : bias
bone : bone_id
midx += num_weights
# Now we process the current mesh from all the temporary crap we've made
for i in [0..num_verts-1]
# create skin indices
si = new SkinIndex temp_verts[i].i, temp_verts[i].c
current_skin.addIndex si
# Now build the actual weights, chosen from the most biased
# This places a limit on the number of weights passed in to the shader
pos = new Vec3 0, 0, 0
actual_weights = []
for j in [0..si.count-1]
actual_weights.push temp_weights[si.index + j]
# Sort the weights keeping the most important ones
_compare_weight = (a, b) ->
return a.bias < b.bias
actual_weights.sort(_compare_weight)
if actual_weights.length > Skeleton.PXL_MAX_WEIGHTS
actual_weights.splice Skeleton.PXL_MAX_WEIGHTS-1, actual_weights.length-1
# Make sure all sum to 1.0
total = 0
for w in actual_weights
total += w.bias
total = 1.0 / total
for w in actual_weights
w.bias = w.bias * total
# Now we actually create our vertices as the positions are created from
# the bind pose of the skeleton and all the weights etc
tw = []
ti = []
for j in [0..Skeleton.PXL_MAX_WEIGHTS-1]
if j < actual_weights.length
w = actual_weights[j]
tw.push w.bias
ti.push w.bone
bp = w.position.clone()
# So inverting here seems to work which it really shouldnt ><
# I suspect this may or may not work with the animaion file :S
# Also, the rotation appears to be y and z reversed >< Not so good
Quaternion.invert(@skeleton.getBone(w.bone).rotation_pose).transVec3 bp
bp.add @skeleton.getBone(w.bone).position_pose
bp.multScalar w.bias
pos.add bp
else
tw.push 0
ti.push 0
# Create and add the actual first vertex, built from our bind pose
vertex = new Vertex(
p : pos
t : temp_verts[i].u.clone()
w : new Vec4 tw[0], tw[1], tw[2], tw[3]
i : new Vec4 ti[0], ti[1], ti[2], ti[3]
n : new Vec3 0, 0, 0
)
current_mesh.addVertex vertex
# As we are using a trimesh, finally create our triangles and normals
j = 0
while j < current_mesh.indices.length
p0 = current_mesh.vertices[current_mesh.indices[j]]
p1 = current_mesh.vertices[current_mesh.indices[j+1]]
p2 = current_mesh.vertices[current_mesh.indices[j+2]]
triangle = new Triangle p0, p1, p2
triangle.computeFaceNormal()
p0.n.add triangle.n
p1.n.add triangle.n
p2.n.add triangle.n
# We call push on faces directly as addTriangle builds up the
# indices table which we've already built. This is a bit naughty
current_mesh.faces.push triangle
j+=3
for vertex in current_mesh.vertices
vertex.n.normalize()
current_node.add current_skin
midx += 1
# Delete any temporary things on this node
@_material_by_name = undefined if @_material_by_name?
@
module.exports =
MD5Model : MD5Model
| 159456 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
The MD5 Model format written by ID Software for Doom3
http://www.3dgep.com/loading-and-animating-md5-models-with-opengl
###
{PXLWarning, PXLError, PXLLog} = require '../util/log'
{TriangleMesh, Triangle, Vertex} = require '../geometry/primitive'
{Vec4, Vec3, Vec2, Quaternion, Matrix4, Matrix3} = require '../math/math'
{Node} = require '../core/node'
{RGB, RGBA} = require '../colour/colour'
{Promise} = require '../util/promise'
{Request} = require '../util/request'
{PhongMaterial} = require '../material/phong'
{BasicColourMaterial} = require '../material/basic'
{Skeleton, Bone, Skin, SkinWeight, SkinIndex} = require '../animation/skeleton'
# ## MD5Model
# Loads an MD5 Model creating a set of nodes, materials and a skeleton
# MD5 is one of the widely used ID Software Model formats
# Regarding materials, for now we just load the nearest texture in the directory
class MD5Model extends Node
# **@constructor** for OBJ
# - **url** - a String - Required
# - **promise** - a Promise
# - **params** - NOT CURRENTLY USED
# TODO - We may wish to consider how this fits with queue and loading items :O
# TODO - Remove the queue once its finished with?
constructor : (@url, @promise, @params) ->
super()
@version = ""
@num_joints = ""
@num_meshes = ""
@add new Skeleton() # as this is a node, it ends up added at the node level
# Three promises, chained in order
promise_textures = new Promise()
promise_data = new Promise()
promise_main = new Promise()
# As Promise data is resolved after promise textures, we just have one here
promise_main.when(promise_data).then () =>
@promise.resolve()
promise_textures.then (text_data) =>
@_parse_data(text_data)
promise_data.resolve() # Assuming parse_data never goes wrong :P
load_data_promise = () =>
r = new Request(@url)
r.get (data) =>
@_parse_materials(data, promise_textures)
if @promise?
# Create a set of promises
load_data_promise()
else
# Make a synchronous get request
onerror = (result) =>
PXLError "Loading Model: " + url + " " + result
r = new Request(@url)
r.get( (data) =>
@_parse_materials_sync(data)
@_parse_data(data)
,onerror,true)
@
_computeW : (r0,r1,r2) ->
t = 1.0 - (r0 * r0) - (r1 * r1) - (r2 * r2)
if t < 0.0
return 0.0
t = -Math.sqrt(t)
t
_parse_materials_sync : (text_data) ->
@
# This function is tricky with all the promises it creates. It creates one master promise
# and then several sub promises with get requests in order to go and load the various images
# we need to create our materials.
_parse_materials : (text_data, promise_textures) ->
# Hunt fot any shader lines
lines = text_data.split("\n");
midx = 0
base_path = @url[0..@url.lastIndexOf("/")-1]
# Temporary, clean up later
_material_promises = []
@_material_by_name = {}
for midx in [0..lines.length-1]
line = lines[midx]
if line.indexOf("shader") != -1
lastquote = line.lastIndexOf('"')
firstquote = line.indexOf('"')
material_path = line[firstquote+1..lastquote-1]
# Cheat a bit here - assuming there is a tga of the same name as the shader, for now
# TODO - Will need to change this sooner
material_url = base_path + "/" + material_path[material_path.lastIndexOf("/")+1..] + ".png"
p = new Promise()
_material_promises.push p
# A closure with all the data we need to setup this material
onsuccess_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (_texture) =>
if PXL.Context.debug
PXLLog "MD5Model Loaded a Texture: " + _material_path
# default to phong with low specular
# TODO Eventually we'll do this properly
wh = new RGB.WHITE()
spec = new RGB.BLACK()
__material_by_name[_material_path] = new PhongMaterial wh, _texture, spec
_p.resolve()
# Closure for when we cant load our texture - default to a white texture
onerror_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (msg) =>
# ignore and use a normal material
if PXL.Context.debug
PXLLog "MD5Model Failed to load a Texture: " + _material_path
wh = new PXL.Colour.RGB 1.0,0.0,0.0
__material_by_name[_material_path] = new BasicColourMaterial wh
_p.resolve()
PXL.GL.textureFromURL material_url, onsuccess_closure(), onerror_closure()
# Grab all the textures we need - if they dont exist, replace with a
# white plain material for now. Eventually we'll check a material file
promise_materials = new Promise()
promise_materials.when.apply(promise_materials, _material_promises).then () =>
promise_textures.resolve(text_data)
@
_parse_data: (text_data) ->
# Could be heavy if the file is big :S
lines = text_data.split("\n");
midx = 0
# Create a temp joints array as we need to compute vertices with
# them at the end of each mesh
while midx < lines.length
line = lines[midx]
if line[0..9] == "MD5Version"
@version = line[11..]
if line[0..8] == "numJoints"
@num_joints = parseInt(line[10..])
if line[0..8] == "numMeshes"
@num_meshes == parseInt(line[10..])
# Start looping over the joints - the bones basically
if line[0..7] == "joints {"
for jidx in [0..@num_joints-1]
jline = lines[midx + jidx + 1]
lastquote = jline.lastIndexOf('"')
name = jline[jline.indexOf('"')+1..lastquote-1]
openbrace = jline.indexOf('(')
closebrace = jline.indexOf(')')
parent_idx = parseInt(jline[lastquote+1..openbrace-1])
parent = undefined
# I believe all parents are listed in MD5 before their children
if parent_idx > -1
parent = @skeleton.getBone parent_idx
tokens = jline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
position = new Vec3(p0,p1,p2)
openbrace = jline.lastIndexOf('(')
closebrace = jline.lastIndexOf(')')
tokens = jline[openbrace..closebrace].split(" ")
r0 = parseFloat tokens[1]
r1 = parseFloat tokens[2]
r2 = parseFloat tokens[3]
rotation = new Quaternion r0, r1, r2, @_computeW(r0,r1,r2)
rotation.normalize()
bone = new Bone name, jidx, parent, rotation, position
@skeleton.addBone bone
midx += @num_joints
# Now we actually create the seperate meshes (one material per mesh we suspect)
# MD5 format calls the material a shader which is probably correct ;)
# We ignore shader for now but this requires loading external files so thats
# definitely a pre-parse step :S
if line[0..5] == "mesh {"
tline = lines[midx]
# Find the mesh for this shader
while tline.indexOf("shader") == -1
midx += 1
tline = lines[midx]
material_path = tline[tline.indexOf('"')+1..tline.lastIndexOf('"')-1]
while tline.indexOf("numverts") == -1
midx +=1
tline = lines[midx]
num_verts = parseInt(tline[tline.indexOf("numverts")+8..] )
# Create a subnode for our geometry and material
current_mesh = new TriangleMesh true
current_node = new Node current_mesh
# We should have all the materials by this point
current_node.material = @_material_by_name[material_path] if @_material_by_name?
@add current_node
# Now loop over the verts, though these arent actual verts - they are indices
# into the data really. First pair is the tex coords - second is the start index
# the next is the count
temp_verts = []
for vidx in [0..num_verts-1]
tline = lines[midx + vidx + 1]
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
idx = parseInt(tline[tline.indexOf("vert")+1..openbrace-1])
tokens = tline[openbrace..closebrace].split(" ")
u = parseFloat tokens[1]
v = parseFloat tokens[2]
tokens = tline[closebrace..].split(" ")
idx = parseInt tokens[1]
count = parseInt tokens[2]
temp_vert_struct =
u : new Vec2 u, v
i : idx
c : count
temp_verts.push temp_vert_struct
midx += num_verts
# Now hunt for the number of triangles
tline = lines[midx]
while tline.indexOf("numtris") == -1
midx +=1
tline = lines[midx]
num_tris = parseInt(tline[tline.indexOf("numtris")+7..])
# Add enough indices for all the points
for i in [0..(num_tris*3)-1]
current_mesh.addIndex(0)
tidx = 0
for tidx in [0..num_tris-1]
tline = lines[midx + tidx + 1]
tri = tline.indexOf("tri")
tokens = tline[tri..].split(" ")
idx = parseInt tokens[1]
a = parseInt tokens[2]
b = parseInt tokens[3]
c = parseInt tokens[4]
# Consider the winding
current_mesh.setIndex idx * 3, c
current_mesh.setIndex idx * 3 + 1, b
current_mesh.setIndex idx * 3 + 2, a
midx += num_tris
# Now hunt for the weights
tline = lines[midx]
while tline.indexOf("numweights") == -1
midx +=1
tline = lines[midx]
num_weights = parseInt(tline[tline.indexOf("numweights")+10..])
# Again we need a temporary weights array like temp verts etc
temp_weights = []
# Create a skin which we add to the current node
current_skin = new Skin()
for widx in [0..num_weights-1]
tline = lines[midx + widx + 1]
ws = tline.indexOf("weight")
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
tokens = tline[ws..openbrace].split(" ")
idx = parseInt tokens[1]
bone_id = parseInt tokens[2]
bias = parseFloat tokens[3]
skinweight = new SkinWeight @skeleton.getBone(bone_id), bias
current_skin.addWeight skinweight
tokens = tline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
# Temporary weights array push - apparently for the GPU benefit
temp_weights.push
position : new Vec3(p0,p1,p2)
bias : bias
bone : bone_id
midx += num_weights
# Now we process the current mesh from all the temporary crap we've made
for i in [0..num_verts-1]
# create skin indices
si = new SkinIndex temp_verts[i].i, temp_verts[i].c
current_skin.addIndex si
# Now build the actual weights, chosen from the most biased
# This places a limit on the number of weights passed in to the shader
pos = new Vec3 0, 0, 0
actual_weights = []
for j in [0..si.count-1]
actual_weights.push temp_weights[si.index + j]
# Sort the weights keeping the most important ones
_compare_weight = (a, b) ->
return a.bias < b.bias
actual_weights.sort(_compare_weight)
if actual_weights.length > Skeleton.PXL_MAX_WEIGHTS
actual_weights.splice Skeleton.PXL_MAX_WEIGHTS-1, actual_weights.length-1
# Make sure all sum to 1.0
total = 0
for w in actual_weights
total += w.bias
total = 1.0 / total
for w in actual_weights
w.bias = w.bias * total
# Now we actually create our vertices as the positions are created from
# the bind pose of the skeleton and all the weights etc
tw = []
ti = []
for j in [0..Skeleton.PXL_MAX_WEIGHTS-1]
if j < actual_weights.length
w = actual_weights[j]
tw.push w.bias
ti.push w.bone
bp = w.position.clone()
# So inverting here seems to work which it really shouldnt ><
# I suspect this may or may not work with the animaion file :S
# Also, the rotation appears to be y and z reversed >< Not so good
Quaternion.invert(@skeleton.getBone(w.bone).rotation_pose).transVec3 bp
bp.add @skeleton.getBone(w.bone).position_pose
bp.multScalar w.bias
pos.add bp
else
tw.push 0
ti.push 0
# Create and add the actual first vertex, built from our bind pose
vertex = new Vertex(
p : pos
t : temp_verts[i].u.clone()
w : new Vec4 tw[0], tw[1], tw[2], tw[3]
i : new Vec4 ti[0], ti[1], ti[2], ti[3]
n : new Vec3 0, 0, 0
)
current_mesh.addVertex vertex
# As we are using a trimesh, finally create our triangles and normals
j = 0
while j < current_mesh.indices.length
p0 = current_mesh.vertices[current_mesh.indices[j]]
p1 = current_mesh.vertices[current_mesh.indices[j+1]]
p2 = current_mesh.vertices[current_mesh.indices[j+2]]
triangle = new Triangle p0, p1, p2
triangle.computeFaceNormal()
p0.n.add triangle.n
p1.n.add triangle.n
p2.n.add triangle.n
# We call push on faces directly as addTriangle builds up the
# indices table which we've already built. This is a bit naughty
current_mesh.faces.push triangle
j+=3
for vertex in current_mesh.vertices
vertex.n.normalize()
current_node.add current_skin
midx += 1
# Delete any temporary things on this node
@_material_by_name = undefined if @_material_by_name?
@
module.exports =
MD5Model : MD5Model
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
The MD5 Model format written by ID Software for Doom3
http://www.3dgep.com/loading-and-animating-md5-models-with-opengl
###
{PXLWarning, PXLError, PXLLog} = require '../util/log'
{TriangleMesh, Triangle, Vertex} = require '../geometry/primitive'
{Vec4, Vec3, Vec2, Quaternion, Matrix4, Matrix3} = require '../math/math'
{Node} = require '../core/node'
{RGB, RGBA} = require '../colour/colour'
{Promise} = require '../util/promise'
{Request} = require '../util/request'
{PhongMaterial} = require '../material/phong'
{BasicColourMaterial} = require '../material/basic'
{Skeleton, Bone, Skin, SkinWeight, SkinIndex} = require '../animation/skeleton'
# ## MD5Model
# Loads an MD5 Model creating a set of nodes, materials and a skeleton
# MD5 is one of the widely used ID Software Model formats
# Regarding materials, for now we just load the nearest texture in the directory
class MD5Model extends Node
# **@constructor** for OBJ
# - **url** - a String - Required
# - **promise** - a Promise
# - **params** - NOT CURRENTLY USED
# TODO - We may wish to consider how this fits with queue and loading items :O
# TODO - Remove the queue once its finished with?
constructor : (@url, @promise, @params) ->
super()
@version = ""
@num_joints = ""
@num_meshes = ""
@add new Skeleton() # as this is a node, it ends up added at the node level
# Three promises, chained in order
promise_textures = new Promise()
promise_data = new Promise()
promise_main = new Promise()
# As Promise data is resolved after promise textures, we just have one here
promise_main.when(promise_data).then () =>
@promise.resolve()
promise_textures.then (text_data) =>
@_parse_data(text_data)
promise_data.resolve() # Assuming parse_data never goes wrong :P
load_data_promise = () =>
r = new Request(@url)
r.get (data) =>
@_parse_materials(data, promise_textures)
if @promise?
# Create a set of promises
load_data_promise()
else
# Make a synchronous get request
onerror = (result) =>
PXLError "Loading Model: " + url + " " + result
r = new Request(@url)
r.get( (data) =>
@_parse_materials_sync(data)
@_parse_data(data)
,onerror,true)
@
_computeW : (r0,r1,r2) ->
t = 1.0 - (r0 * r0) - (r1 * r1) - (r2 * r2)
if t < 0.0
return 0.0
t = -Math.sqrt(t)
t
_parse_materials_sync : (text_data) ->
@
# This function is tricky with all the promises it creates. It creates one master promise
# and then several sub promises with get requests in order to go and load the various images
# we need to create our materials.
_parse_materials : (text_data, promise_textures) ->
# Hunt fot any shader lines
lines = text_data.split("\n");
midx = 0
base_path = @url[0..@url.lastIndexOf("/")-1]
# Temporary, clean up later
_material_promises = []
@_material_by_name = {}
for midx in [0..lines.length-1]
line = lines[midx]
if line.indexOf("shader") != -1
lastquote = line.lastIndexOf('"')
firstquote = line.indexOf('"')
material_path = line[firstquote+1..lastquote-1]
# Cheat a bit here - assuming there is a tga of the same name as the shader, for now
# TODO - Will need to change this sooner
material_url = base_path + "/" + material_path[material_path.lastIndexOf("/")+1..] + ".png"
p = new Promise()
_material_promises.push p
# A closure with all the data we need to setup this material
onsuccess_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (_texture) =>
if PXL.Context.debug
PXLLog "MD5Model Loaded a Texture: " + _material_path
# default to phong with low specular
# TODO Eventually we'll do this properly
wh = new RGB.WHITE()
spec = new RGB.BLACK()
__material_by_name[_material_path] = new PhongMaterial wh, _texture, spec
_p.resolve()
# Closure for when we cant load our texture - default to a white texture
onerror_closure = () =>
_p = p
_material_path = material_path
__material_by_name = @_material_by_name
return (msg) =>
# ignore and use a normal material
if PXL.Context.debug
PXLLog "MD5Model Failed to load a Texture: " + _material_path
wh = new PXL.Colour.RGB 1.0,0.0,0.0
__material_by_name[_material_path] = new BasicColourMaterial wh
_p.resolve()
PXL.GL.textureFromURL material_url, onsuccess_closure(), onerror_closure()
# Grab all the textures we need - if they dont exist, replace with a
# white plain material for now. Eventually we'll check a material file
promise_materials = new Promise()
promise_materials.when.apply(promise_materials, _material_promises).then () =>
promise_textures.resolve(text_data)
@
_parse_data: (text_data) ->
# Could be heavy if the file is big :S
lines = text_data.split("\n");
midx = 0
# Create a temp joints array as we need to compute vertices with
# them at the end of each mesh
while midx < lines.length
line = lines[midx]
if line[0..9] == "MD5Version"
@version = line[11..]
if line[0..8] == "numJoints"
@num_joints = parseInt(line[10..])
if line[0..8] == "numMeshes"
@num_meshes == parseInt(line[10..])
# Start looping over the joints - the bones basically
if line[0..7] == "joints {"
for jidx in [0..@num_joints-1]
jline = lines[midx + jidx + 1]
lastquote = jline.lastIndexOf('"')
name = jline[jline.indexOf('"')+1..lastquote-1]
openbrace = jline.indexOf('(')
closebrace = jline.indexOf(')')
parent_idx = parseInt(jline[lastquote+1..openbrace-1])
parent = undefined
# I believe all parents are listed in MD5 before their children
if parent_idx > -1
parent = @skeleton.getBone parent_idx
tokens = jline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
position = new Vec3(p0,p1,p2)
openbrace = jline.lastIndexOf('(')
closebrace = jline.lastIndexOf(')')
tokens = jline[openbrace..closebrace].split(" ")
r0 = parseFloat tokens[1]
r1 = parseFloat tokens[2]
r2 = parseFloat tokens[3]
rotation = new Quaternion r0, r1, r2, @_computeW(r0,r1,r2)
rotation.normalize()
bone = new Bone name, jidx, parent, rotation, position
@skeleton.addBone bone
midx += @num_joints
# Now we actually create the seperate meshes (one material per mesh we suspect)
# MD5 format calls the material a shader which is probably correct ;)
# We ignore shader for now but this requires loading external files so thats
# definitely a pre-parse step :S
if line[0..5] == "mesh {"
tline = lines[midx]
# Find the mesh for this shader
while tline.indexOf("shader") == -1
midx += 1
tline = lines[midx]
material_path = tline[tline.indexOf('"')+1..tline.lastIndexOf('"')-1]
while tline.indexOf("numverts") == -1
midx +=1
tline = lines[midx]
num_verts = parseInt(tline[tline.indexOf("numverts")+8..] )
# Create a subnode for our geometry and material
current_mesh = new TriangleMesh true
current_node = new Node current_mesh
# We should have all the materials by this point
current_node.material = @_material_by_name[material_path] if @_material_by_name?
@add current_node
# Now loop over the verts, though these arent actual verts - they are indices
# into the data really. First pair is the tex coords - second is the start index
# the next is the count
temp_verts = []
for vidx in [0..num_verts-1]
tline = lines[midx + vidx + 1]
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
idx = parseInt(tline[tline.indexOf("vert")+1..openbrace-1])
tokens = tline[openbrace..closebrace].split(" ")
u = parseFloat tokens[1]
v = parseFloat tokens[2]
tokens = tline[closebrace..].split(" ")
idx = parseInt tokens[1]
count = parseInt tokens[2]
temp_vert_struct =
u : new Vec2 u, v
i : idx
c : count
temp_verts.push temp_vert_struct
midx += num_verts
# Now hunt for the number of triangles
tline = lines[midx]
while tline.indexOf("numtris") == -1
midx +=1
tline = lines[midx]
num_tris = parseInt(tline[tline.indexOf("numtris")+7..])
# Add enough indices for all the points
for i in [0..(num_tris*3)-1]
current_mesh.addIndex(0)
tidx = 0
for tidx in [0..num_tris-1]
tline = lines[midx + tidx + 1]
tri = tline.indexOf("tri")
tokens = tline[tri..].split(" ")
idx = parseInt tokens[1]
a = parseInt tokens[2]
b = parseInt tokens[3]
c = parseInt tokens[4]
# Consider the winding
current_mesh.setIndex idx * 3, c
current_mesh.setIndex idx * 3 + 1, b
current_mesh.setIndex idx * 3 + 2, a
midx += num_tris
# Now hunt for the weights
tline = lines[midx]
while tline.indexOf("numweights") == -1
midx +=1
tline = lines[midx]
num_weights = parseInt(tline[tline.indexOf("numweights")+10..])
# Again we need a temporary weights array like temp verts etc
temp_weights = []
# Create a skin which we add to the current node
current_skin = new Skin()
for widx in [0..num_weights-1]
tline = lines[midx + widx + 1]
ws = tline.indexOf("weight")
openbrace = tline.indexOf("(")
closebrace = tline.indexOf(")")
tokens = tline[ws..openbrace].split(" ")
idx = parseInt tokens[1]
bone_id = parseInt tokens[2]
bias = parseFloat tokens[3]
skinweight = new SkinWeight @skeleton.getBone(bone_id), bias
current_skin.addWeight skinweight
tokens = tline[openbrace..closebrace].split(" ")
p0 = parseFloat tokens[1]
p1 = parseFloat tokens[2]
p2 = parseFloat tokens[3]
# Temporary weights array push - apparently for the GPU benefit
temp_weights.push
position : new Vec3(p0,p1,p2)
bias : bias
bone : bone_id
midx += num_weights
# Now we process the current mesh from all the temporary crap we've made
for i in [0..num_verts-1]
# create skin indices
si = new SkinIndex temp_verts[i].i, temp_verts[i].c
current_skin.addIndex si
# Now build the actual weights, chosen from the most biased
# This places a limit on the number of weights passed in to the shader
pos = new Vec3 0, 0, 0
actual_weights = []
for j in [0..si.count-1]
actual_weights.push temp_weights[si.index + j]
# Sort the weights keeping the most important ones
_compare_weight = (a, b) ->
return a.bias < b.bias
actual_weights.sort(_compare_weight)
if actual_weights.length > Skeleton.PXL_MAX_WEIGHTS
actual_weights.splice Skeleton.PXL_MAX_WEIGHTS-1, actual_weights.length-1
# Make sure all sum to 1.0
total = 0
for w in actual_weights
total += w.bias
total = 1.0 / total
for w in actual_weights
w.bias = w.bias * total
# Now we actually create our vertices as the positions are created from
# the bind pose of the skeleton and all the weights etc
tw = []
ti = []
for j in [0..Skeleton.PXL_MAX_WEIGHTS-1]
if j < actual_weights.length
w = actual_weights[j]
tw.push w.bias
ti.push w.bone
bp = w.position.clone()
# So inverting here seems to work which it really shouldnt ><
# I suspect this may or may not work with the animaion file :S
# Also, the rotation appears to be y and z reversed >< Not so good
Quaternion.invert(@skeleton.getBone(w.bone).rotation_pose).transVec3 bp
bp.add @skeleton.getBone(w.bone).position_pose
bp.multScalar w.bias
pos.add bp
else
tw.push 0
ti.push 0
# Create and add the actual first vertex, built from our bind pose
vertex = new Vertex(
p : pos
t : temp_verts[i].u.clone()
w : new Vec4 tw[0], tw[1], tw[2], tw[3]
i : new Vec4 ti[0], ti[1], ti[2], ti[3]
n : new Vec3 0, 0, 0
)
current_mesh.addVertex vertex
# As we are using a trimesh, finally create our triangles and normals
j = 0
while j < current_mesh.indices.length
p0 = current_mesh.vertices[current_mesh.indices[j]]
p1 = current_mesh.vertices[current_mesh.indices[j+1]]
p2 = current_mesh.vertices[current_mesh.indices[j+2]]
triangle = new Triangle p0, p1, p2
triangle.computeFaceNormal()
p0.n.add triangle.n
p1.n.add triangle.n
p2.n.add triangle.n
# We call push on faces directly as addTriangle builds up the
# indices table which we've already built. This is a bit naughty
current_mesh.faces.push triangle
j+=3
for vertex in current_mesh.vertices
vertex.n.normalize()
current_node.add current_skin
midx += 1
# Delete any temporary things on this node
@_material_by_name = undefined if @_material_by_name?
@
module.exports =
MD5Model : MD5Model
|
[
{
"context": "render 'diff',\n title: 'Diff'\n name: name\n diff: renderer.diff diff\n\nsearch = (req, ",
"end": 1807,
"score": 0.5557006597518921,
"start": 1803,
"tag": "NAME",
"value": "name"
}
] | wikiApp.coffee | madnite1/devnote | 11 | fs = require 'fs'
wiki = require './lib/wiki'
url = require 'url'
debug = (require 'debug')('main')
assert = require 'assert'
mailer = require './lib/mailer'
User = require('./lib/users').User
_ = require 'underscore'
util = require 'util'
__ = (require './lib/i18n').__
renderer = require './lib/renderer'
ROOT_PATH = '/wikis/'
HISTORY_LIMIT = 30
lastVisits = {}
subscribers = {}
exports.init = (wikiname) ->
ROOT_PATH += wikiname
wiki.init wikiname, (err) ->
if err
console.log err.message
else
data = fs.readFileSync 'frontpage.md'
wiki.writePage 'frontpage', data, null, (err) ->
throw err if err
error404 = (err, req, res, next) ->
console.log err
res.statusCode = 404
res.render '404.jade',
title: "404 Not Found",
error: err.message,
error500 = (err, req, res, next) ->
res.statusCode = 500
res.render '500.jade',
title: "Sorry, Error Occurred...",
error: err.message,
history = (name, req, res) ->
handler = (err, history) ->
if err
error404 err, req, res
else
res.render 'history',
title: name
history: history
limit: HISTORY_LIMIT
if req.query.until
offset = parseInt(req.query.offset or 0)
wiki.queryHistory
filename: name
until: req.query.until
offset: offset
limit: HISTORY_LIMIT
handler
else
wiki.getHistory name, HISTORY_LIMIT, handler
diff = (name, req, res) ->
[diffA, diffB] = [req.query.diffA, req.query.diffB].map (param) ->
index = param.lastIndexOf(',')
[param.substr(0, index), param.substr(index + 1)]
wiki.diff {filename: diffA[0], rev: diffA[1]}, {filename: diffB[0], rev: diffB[1]}, (err, diff) ->
if err
error404 err, req, res
else
res.render 'diff',
title: 'Diff'
name: name
diff: renderer.diff diff
search = (req, res) ->
keyword = req.query.keyword
if keyword
wiki.search keyword, (err, pages) ->
throw err if err
res.render 'search',
title: 'Search'
pages: renderer.search pages, keyword
else
res.render 'search',
title: 'Search'
pages: {}
exports.getPages = (req, res) ->
switch req.query.action
when 'search' then search req, res
else list req, res, req.query.selectedPageName
# get wikipage list
list = (req, res, selectedPageName) ->
wiki.getPages (err, pages) ->
if err
error404 err, req, res
else if pages.length == 0 then res.render 'nopage', {title: 'nopage'}
else
pageName = selectedPageName or req.query.page or pages[0].name
wiki.getPage pageName, (err, page) ->
if err
error404 err, req, res
else
subscribed = req.session.user and
subscribers[pageName] and
req.session.user.id in subscribers[pageName]
res.render 'pages',
title: 'Pages'
pages: pages
selectedPageName: pageName
selectedPageContent: renderer.markdown page.content
deletedPageName: req.query.deletedPageName
subscribed: subscribed
exports.getPage = (req, res) ->
name = req.params.name
switch req.query.action
when 'diff' then diff name, req, res
when 'history' then history name, req, res
when 'edit' then edit name, req, res
else view name, req, res
edit = (name, req, res) ->
wiki.getPage name, (err, page) ->
if err
error404 err, req, res
else
res.render 'new',
title: 'Edit Page'
pageName: name
attachDir: name
body: page.content
filelist: []
newPage: false
view = (name, req, res) ->
wiki.getPage name, req.query.rev, (err, page) ->
if err
return error404 err, req, res
subscribed = req.session.user and
subscribers[name] and
req.session.user.id in subscribers[name]
renderPage = (lastVisit) ->
options =
title: name
content: renderer.markdown page.content
page: page
subscribed: subscribed
loggedIn: !!req.session.user
lastVisit: lastVisit
res.render 'page', options
if not req.session.user
return renderPage()
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisitId = lastVisits[userId][name]
lastVisits[userId][name] = page.commitId
if not lastVisitId
return renderPage()
if lastVisitId != page.commitId
# something changed
return wiki.readCommit lastVisitId,
(err, commit) ->
lastVisit =
date: new Date commit.committer.unixtime * 1000
id: lastVisitId
return renderPage lastVisit
else
# nothing changed
return renderPage()
exports.getNew = (req, res) ->
res.render 'new',
title: 'New Page'
pageName: ''
attachDir: '__new_' + new Date().getTime()
filelist: []
newPage: true
exports.postNew = (req, res) ->
saveEditedPage = (name, body, callback) ->
wiki.writePage name, body, req.session.user, (err, commitId) ->
if req.session.user
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisits[userId][name] = commitId
if subscribers[name]
# send mail to subscribers of this page.
wiki.diff {filename: name, rev: commitId}, null, ['json', 'unified'], (err, diff) ->
user = req.session.user
subject = '[n4wiki] ' + name + ' was edited'
subject += (' by ' + user.id) if user
if user
ids = _.without subscribers[name], user.id
else
ids = subscribers[name]
to = (User.findUserById(id).email for id in ids)
mailer.send
to: to
subject: subject
text: diff['unified']
html: renderer.diff diff['json'], true
callback err
newPageName = req.body.name.trim()
originalPageName = req.body.originalName
body = req.body.body
if originalPageName and (originalPageName != newPageName)
wiki.renamePage originalPageName, newPageName, req.session.user, (err) ->
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
else
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
exports.postDelete = (req, res) ->
wiki.deletePage req.params.name, req.session.user, (err) ->
res.redirect ROOT_PATH + '/pages?deletedPageName=' + req.params.name
exports.postRollback = (req, res) ->
name = req.params.name
wiki.rollback name, req.body.id, (err) ->
wiki.getHistory name, HISTORY_LIMIT, (err, history) ->
if err
error404 err, req, res
else
res.contentType 'json'
res.send
history: history
name: name
ids: history.ids
exports.postSubscribe = (req, res) ->
name = req.params.name
if req.session.user
subscribers[name] = [] if not subscribers[name]
userId = req.session.user.id
if not (userId in subscribers[name])
subscribers[name].push userId
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
exports.postUnsubscribe = (req, res) ->
name = req.params.name
if req.session.user and subscribers[name]
subscribers[name] = _.without subscribers[name], req.session.user.id
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
| 222126 | fs = require 'fs'
wiki = require './lib/wiki'
url = require 'url'
debug = (require 'debug')('main')
assert = require 'assert'
mailer = require './lib/mailer'
User = require('./lib/users').User
_ = require 'underscore'
util = require 'util'
__ = (require './lib/i18n').__
renderer = require './lib/renderer'
ROOT_PATH = '/wikis/'
HISTORY_LIMIT = 30
lastVisits = {}
subscribers = {}
exports.init = (wikiname) ->
ROOT_PATH += wikiname
wiki.init wikiname, (err) ->
if err
console.log err.message
else
data = fs.readFileSync 'frontpage.md'
wiki.writePage 'frontpage', data, null, (err) ->
throw err if err
error404 = (err, req, res, next) ->
console.log err
res.statusCode = 404
res.render '404.jade',
title: "404 Not Found",
error: err.message,
error500 = (err, req, res, next) ->
res.statusCode = 500
res.render '500.jade',
title: "Sorry, Error Occurred...",
error: err.message,
history = (name, req, res) ->
handler = (err, history) ->
if err
error404 err, req, res
else
res.render 'history',
title: name
history: history
limit: HISTORY_LIMIT
if req.query.until
offset = parseInt(req.query.offset or 0)
wiki.queryHistory
filename: name
until: req.query.until
offset: offset
limit: HISTORY_LIMIT
handler
else
wiki.getHistory name, HISTORY_LIMIT, handler
diff = (name, req, res) ->
[diffA, diffB] = [req.query.diffA, req.query.diffB].map (param) ->
index = param.lastIndexOf(',')
[param.substr(0, index), param.substr(index + 1)]
wiki.diff {filename: diffA[0], rev: diffA[1]}, {filename: diffB[0], rev: diffB[1]}, (err, diff) ->
if err
error404 err, req, res
else
res.render 'diff',
title: 'Diff'
name: <NAME>
diff: renderer.diff diff
search = (req, res) ->
keyword = req.query.keyword
if keyword
wiki.search keyword, (err, pages) ->
throw err if err
res.render 'search',
title: 'Search'
pages: renderer.search pages, keyword
else
res.render 'search',
title: 'Search'
pages: {}
exports.getPages = (req, res) ->
switch req.query.action
when 'search' then search req, res
else list req, res, req.query.selectedPageName
# get wikipage list
list = (req, res, selectedPageName) ->
wiki.getPages (err, pages) ->
if err
error404 err, req, res
else if pages.length == 0 then res.render 'nopage', {title: 'nopage'}
else
pageName = selectedPageName or req.query.page or pages[0].name
wiki.getPage pageName, (err, page) ->
if err
error404 err, req, res
else
subscribed = req.session.user and
subscribers[pageName] and
req.session.user.id in subscribers[pageName]
res.render 'pages',
title: 'Pages'
pages: pages
selectedPageName: pageName
selectedPageContent: renderer.markdown page.content
deletedPageName: req.query.deletedPageName
subscribed: subscribed
exports.getPage = (req, res) ->
name = req.params.name
switch req.query.action
when 'diff' then diff name, req, res
when 'history' then history name, req, res
when 'edit' then edit name, req, res
else view name, req, res
edit = (name, req, res) ->
wiki.getPage name, (err, page) ->
if err
error404 err, req, res
else
res.render 'new',
title: 'Edit Page'
pageName: name
attachDir: name
body: page.content
filelist: []
newPage: false
view = (name, req, res) ->
wiki.getPage name, req.query.rev, (err, page) ->
if err
return error404 err, req, res
subscribed = req.session.user and
subscribers[name] and
req.session.user.id in subscribers[name]
renderPage = (lastVisit) ->
options =
title: name
content: renderer.markdown page.content
page: page
subscribed: subscribed
loggedIn: !!req.session.user
lastVisit: lastVisit
res.render 'page', options
if not req.session.user
return renderPage()
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisitId = lastVisits[userId][name]
lastVisits[userId][name] = page.commitId
if not lastVisitId
return renderPage()
if lastVisitId != page.commitId
# something changed
return wiki.readCommit lastVisitId,
(err, commit) ->
lastVisit =
date: new Date commit.committer.unixtime * 1000
id: lastVisitId
return renderPage lastVisit
else
# nothing changed
return renderPage()
exports.getNew = (req, res) ->
res.render 'new',
title: 'New Page'
pageName: ''
attachDir: '__new_' + new Date().getTime()
filelist: []
newPage: true
exports.postNew = (req, res) ->
saveEditedPage = (name, body, callback) ->
wiki.writePage name, body, req.session.user, (err, commitId) ->
if req.session.user
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisits[userId][name] = commitId
if subscribers[name]
# send mail to subscribers of this page.
wiki.diff {filename: name, rev: commitId}, null, ['json', 'unified'], (err, diff) ->
user = req.session.user
subject = '[n4wiki] ' + name + ' was edited'
subject += (' by ' + user.id) if user
if user
ids = _.without subscribers[name], user.id
else
ids = subscribers[name]
to = (User.findUserById(id).email for id in ids)
mailer.send
to: to
subject: subject
text: diff['unified']
html: renderer.diff diff['json'], true
callback err
newPageName = req.body.name.trim()
originalPageName = req.body.originalName
body = req.body.body
if originalPageName and (originalPageName != newPageName)
wiki.renamePage originalPageName, newPageName, req.session.user, (err) ->
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
else
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
exports.postDelete = (req, res) ->
wiki.deletePage req.params.name, req.session.user, (err) ->
res.redirect ROOT_PATH + '/pages?deletedPageName=' + req.params.name
exports.postRollback = (req, res) ->
name = req.params.name
wiki.rollback name, req.body.id, (err) ->
wiki.getHistory name, HISTORY_LIMIT, (err, history) ->
if err
error404 err, req, res
else
res.contentType 'json'
res.send
history: history
name: name
ids: history.ids
exports.postSubscribe = (req, res) ->
name = req.params.name
if req.session.user
subscribers[name] = [] if not subscribers[name]
userId = req.session.user.id
if not (userId in subscribers[name])
subscribers[name].push userId
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
exports.postUnsubscribe = (req, res) ->
name = req.params.name
if req.session.user and subscribers[name]
subscribers[name] = _.without subscribers[name], req.session.user.id
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
| true | fs = require 'fs'
wiki = require './lib/wiki'
url = require 'url'
debug = (require 'debug')('main')
assert = require 'assert'
mailer = require './lib/mailer'
User = require('./lib/users').User
_ = require 'underscore'
util = require 'util'
__ = (require './lib/i18n').__
renderer = require './lib/renderer'
ROOT_PATH = '/wikis/'
HISTORY_LIMIT = 30
lastVisits = {}
subscribers = {}
exports.init = (wikiname) ->
ROOT_PATH += wikiname
wiki.init wikiname, (err) ->
if err
console.log err.message
else
data = fs.readFileSync 'frontpage.md'
wiki.writePage 'frontpage', data, null, (err) ->
throw err if err
error404 = (err, req, res, next) ->
console.log err
res.statusCode = 404
res.render '404.jade',
title: "404 Not Found",
error: err.message,
error500 = (err, req, res, next) ->
res.statusCode = 500
res.render '500.jade',
title: "Sorry, Error Occurred...",
error: err.message,
history = (name, req, res) ->
handler = (err, history) ->
if err
error404 err, req, res
else
res.render 'history',
title: name
history: history
limit: HISTORY_LIMIT
if req.query.until
offset = parseInt(req.query.offset or 0)
wiki.queryHistory
filename: name
until: req.query.until
offset: offset
limit: HISTORY_LIMIT
handler
else
wiki.getHistory name, HISTORY_LIMIT, handler
diff = (name, req, res) ->
[diffA, diffB] = [req.query.diffA, req.query.diffB].map (param) ->
index = param.lastIndexOf(',')
[param.substr(0, index), param.substr(index + 1)]
wiki.diff {filename: diffA[0], rev: diffA[1]}, {filename: diffB[0], rev: diffB[1]}, (err, diff) ->
if err
error404 err, req, res
else
res.render 'diff',
title: 'Diff'
name: PI:NAME:<NAME>END_PI
diff: renderer.diff diff
search = (req, res) ->
keyword = req.query.keyword
if keyword
wiki.search keyword, (err, pages) ->
throw err if err
res.render 'search',
title: 'Search'
pages: renderer.search pages, keyword
else
res.render 'search',
title: 'Search'
pages: {}
exports.getPages = (req, res) ->
switch req.query.action
when 'search' then search req, res
else list req, res, req.query.selectedPageName
# get wikipage list
list = (req, res, selectedPageName) ->
wiki.getPages (err, pages) ->
if err
error404 err, req, res
else if pages.length == 0 then res.render 'nopage', {title: 'nopage'}
else
pageName = selectedPageName or req.query.page or pages[0].name
wiki.getPage pageName, (err, page) ->
if err
error404 err, req, res
else
subscribed = req.session.user and
subscribers[pageName] and
req.session.user.id in subscribers[pageName]
res.render 'pages',
title: 'Pages'
pages: pages
selectedPageName: pageName
selectedPageContent: renderer.markdown page.content
deletedPageName: req.query.deletedPageName
subscribed: subscribed
exports.getPage = (req, res) ->
name = req.params.name
switch req.query.action
when 'diff' then diff name, req, res
when 'history' then history name, req, res
when 'edit' then edit name, req, res
else view name, req, res
edit = (name, req, res) ->
wiki.getPage name, (err, page) ->
if err
error404 err, req, res
else
res.render 'new',
title: 'Edit Page'
pageName: name
attachDir: name
body: page.content
filelist: []
newPage: false
view = (name, req, res) ->
wiki.getPage name, req.query.rev, (err, page) ->
if err
return error404 err, req, res
subscribed = req.session.user and
subscribers[name] and
req.session.user.id in subscribers[name]
renderPage = (lastVisit) ->
options =
title: name
content: renderer.markdown page.content
page: page
subscribed: subscribed
loggedIn: !!req.session.user
lastVisit: lastVisit
res.render 'page', options
if not req.session.user
return renderPage()
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisitId = lastVisits[userId][name]
lastVisits[userId][name] = page.commitId
if not lastVisitId
return renderPage()
if lastVisitId != page.commitId
# something changed
return wiki.readCommit lastVisitId,
(err, commit) ->
lastVisit =
date: new Date commit.committer.unixtime * 1000
id: lastVisitId
return renderPage lastVisit
else
# nothing changed
return renderPage()
exports.getNew = (req, res) ->
res.render 'new',
title: 'New Page'
pageName: ''
attachDir: '__new_' + new Date().getTime()
filelist: []
newPage: true
exports.postNew = (req, res) ->
saveEditedPage = (name, body, callback) ->
wiki.writePage name, body, req.session.user, (err, commitId) ->
if req.session.user
userId = req.session.user.id
if not lastVisits[userId]
lastVisits[userId] = {}
lastVisits[userId][name] = commitId
if subscribers[name]
# send mail to subscribers of this page.
wiki.diff {filename: name, rev: commitId}, null, ['json', 'unified'], (err, diff) ->
user = req.session.user
subject = '[n4wiki] ' + name + ' was edited'
subject += (' by ' + user.id) if user
if user
ids = _.without subscribers[name], user.id
else
ids = subscribers[name]
to = (User.findUserById(id).email for id in ids)
mailer.send
to: to
subject: subject
text: diff['unified']
html: renderer.diff diff['json'], true
callback err
newPageName = req.body.name.trim()
originalPageName = req.body.originalName
body = req.body.body
if originalPageName and (originalPageName != newPageName)
wiki.renamePage originalPageName, newPageName, req.session.user, (err) ->
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
else
saveEditedPage newPageName, body, (err) ->
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(newPageName)
exports.postDelete = (req, res) ->
wiki.deletePage req.params.name, req.session.user, (err) ->
res.redirect ROOT_PATH + '/pages?deletedPageName=' + req.params.name
exports.postRollback = (req, res) ->
name = req.params.name
wiki.rollback name, req.body.id, (err) ->
wiki.getHistory name, HISTORY_LIMIT, (err, history) ->
if err
error404 err, req, res
else
res.contentType 'json'
res.send
history: history
name: name
ids: history.ids
exports.postSubscribe = (req, res) ->
name = req.params.name
if req.session.user
subscribers[name] = [] if not subscribers[name]
userId = req.session.user.id
if not (userId in subscribers[name])
subscribers[name].push userId
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
exports.postUnsubscribe = (req, res) ->
name = req.params.name
if req.session.user and subscribers[name]
subscribers[name] = _.without subscribers[name], req.session.user.id
res.redirect ROOT_PATH + '/pages/' + encodeURIComponent(name)
|
[
{
"context": "r for you.\n\nclient = Keen.configure\n projectId: '5252fe3d36bf5a4f54000008',\n writeKey: 'd4dff32fa0e23516cf4828d2a71219255e",
"end": 602,
"score": 0.9807454943656921,
"start": 578,
"tag": "KEY",
"value": "5252fe3d36bf5a4f54000008"
},
{
"context": "ojectId: '5252fe3... | lib/analytics.coffee | zhangyazheng-2020/roots | 416 | Keen = require 'keen.io'
global_config = require './global_config'
node = require 'when/node'
W = require('when')
# Yes, you can write analytics to our project. Please don't do this though.
# Roots is an open source project. We're over here working hard to bring you
# tools that will make your life easier, for free. We use these analytics to try
# to make roots even better for you. There's really no reason to be a douche and
# screw up the analytics we use to try to make this free thing better for you.
client = Keen.configure
projectId: '5252fe3d36bf5a4f54000008',
writeKey: 'd4dff32fa0e23516cf4828d2a71219255efd581f8ab3c1a0cc7081e8b1db6282' +
'5f83b0b5f9ec6417fd23fb877d082d1d5ce238ddc46d048b8ba6608557e87904a475f2a930' +
'e4903fc9872323fc120a4859dfb06919d9052e3b676e863a8f6332c21c5cb58be186457398' +
'780475dc62a5'
# Yes, this is global. Because it's used everywhere and is ridiculous to import
# the long path to this file in every other file. I know globals can be
# dangerous, but they exist for a reason, and this is pretty much that reason.
global.__track = (category, e) ->
enabled = global_config().get('analytics')
if enabled
return node.call(client.addEvent.bind(client), category, e).catch(->)
else
return W.resolve(false)
| 42530 | Keen = require 'keen.io'
global_config = require './global_config'
node = require 'when/node'
W = require('when')
# Yes, you can write analytics to our project. Please don't do this though.
# Roots is an open source project. We're over here working hard to bring you
# tools that will make your life easier, for free. We use these analytics to try
# to make roots even better for you. There's really no reason to be a douche and
# screw up the analytics we use to try to make this free thing better for you.
client = Keen.configure
projectId: '<KEY>',
writeKey: '<KEY>' +
'<KEY>' +
'e4903fc9872323fc120a4859dfb06919d9052e3b676e863a8f6332c21c5cb58be186457398' +
'780475dc62a5'
# Yes, this is global. Because it's used everywhere and is ridiculous to import
# the long path to this file in every other file. I know globals can be
# dangerous, but they exist for a reason, and this is pretty much that reason.
global.__track = (category, e) ->
enabled = global_config().get('analytics')
if enabled
return node.call(client.addEvent.bind(client), category, e).catch(->)
else
return W.resolve(false)
| true | Keen = require 'keen.io'
global_config = require './global_config'
node = require 'when/node'
W = require('when')
# Yes, you can write analytics to our project. Please don't do this though.
# Roots is an open source project. We're over here working hard to bring you
# tools that will make your life easier, for free. We use these analytics to try
# to make roots even better for you. There's really no reason to be a douche and
# screw up the analytics we use to try to make this free thing better for you.
client = Keen.configure
projectId: 'PI:KEY:<KEY>END_PI',
writeKey: 'PI:KEY:<KEY>END_PI' +
'PI:KEY:<KEY>END_PI' +
'e4903fc9872323fc120a4859dfb06919d9052e3b676e863a8f6332c21c5cb58be186457398' +
'780475dc62a5'
# Yes, this is global. Because it's used everywhere and is ridiculous to import
# the long path to this file in every other file. I know globals can be
# dangerous, but they exist for a reason, and this is pretty much that reason.
global.__track = (category, e) ->
enabled = global_config().get('analytics')
if enabled
return node.call(client.addEvent.bind(client), category, e).catch(->)
else
return W.resolve(false)
|
[
{
"context": " up roles and voices ---------------------------\n{Alex,Daniel,Kate,Oliver,Samantha,Serena,MeiJia,Sinji} ",
"end": 372,
"score": 0.9998544454574585,
"start": 368,
"tag": "NAME",
"value": "Alex"
},
{
"context": "oles and voices ---------------------------\n{Alex,Daniel,K... | class01.coffee | emptist/mac_speaker | 0 | Speaker = require './speaker'
lesson01 = require './lesson01'
# 清除之前還沒有播放完的內容,從新開始
Speaker.restart()
# --------------------------- prepare for materials --------------------------
{
text:{title,paragraph}
RD1
IR
RD2
CQs
AQT
PDs1
PDs2
PDs3
PDs4
OC
} = lesson01
# ---------------------- set up roles and voices ---------------------------
{Alex,Daniel,Kate,Oliver,Samantha,Serena,MeiJia,Sinji} = Speaker
T = [
Daniel
Serena
Kate
]
S = [
MeiJia
Oliver
#Alex
#Sinji
#Samantha
]
T.map((each,idx) -> each.role = 'trainer')
S.map((each,idx) -> each.role = 'trainee')
# --------------------------- process the contents ----------------------------
S[0].say "自從這樣學新概念,媽媽再也不用擔心我的英語辣"
Speaker.quiet(4)
T[0].intro()
T[1].intro()
T[2].intro()
Speaker.quiet(1)
S[1].intro()
S[0].intro()
#S[2].intro()
#S[3].intro()
#S[4].intro()
# Read for the first time
T[1].say RD1.introduction
T[2].say title
T[2].say paragraph
# Intensive Reading
T[1].say IR.introduction
for question,idx in IR.teacher
T[2].say question
Speaker.quiet(0.1)
S[idx % 2].say IR.student[idx]
T[1].say RD2.introduction
T[2].say title
T[2].say paragraph
### vvvvvvvvvvvvvvvvvv
# (moved down)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
###
# ========= Ask Questions on Text ===========
T[1].say AQT.introduction
Speaker.quiet()
for t1Text,idx in AQT.example.teacher1
T[2].say t1Text
Speaker.quiet(0.5)
T[1].say AQT.example.teacher2[idx]
for t, idx in AQT.teacher
T[2].say t
S[0].say AQT.student[idx]
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[idx % 2].say OC.student[idx]
# (moved here since I think it might be too hard for the students)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
# Pattern Drills 1
T[1].say PDs1.introduction
for t,idx in PDs1.example.teacher1
T[0].say t
T[2].say PDs1.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs1.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs1.student1[idx]
T[2].say PDs1.teacher2[idx]
Speaker.quiet(2)
S[0].say PDs1.student2[idx]
# Pattern Drills 2
T[1].say PDs2.introduction
T[0].say PDs2.example.teacher0
T[1].say PDs2.example.teacher1
T[2].say PDs2.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs2.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs2.student1[idx]
Speaker.quiet(2)
S[1].say PDs2.student2[idx]
# Pattern Drills 3
T[1].say PDs3.introduction
T[0].say PDs3.example.teacher1
T[2].say PDs3.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs3.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs3.student[idx]
# Pattern Drills 4
T[1].say PDs4.introduction
for t,idx in PDs4.example.teacher1
T[0].say t
T[1].say PDs4.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs4.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs4.student1[idx]
T[1].say PDs4.teacher2[idx]
Speaker.quiet(2)
S[1].say PDs4.student2[idx]
###^^^^^^^^^^^^^^^^^^
# (moved forward)
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[1].say OC.student[idx]
###
T[2].say "That's all for today"
for each in T.concat(S)
each.say "bye bye",0.001
#this dosn't work#Speaker.end() | 207297 | Speaker = require './speaker'
lesson01 = require './lesson01'
# 清除之前還沒有播放完的內容,從新開始
Speaker.restart()
# --------------------------- prepare for materials --------------------------
{
text:{title,paragraph}
RD1
IR
RD2
CQs
AQT
PDs1
PDs2
PDs3
PDs4
OC
} = lesson01
# ---------------------- set up roles and voices ---------------------------
{<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>} = Speaker
T = [
<NAME>
<NAME>
<NAME>
]
S = [
<NAME>
<NAME>
#<NAME>
#<NAME>
#<NAME>
]
T.map((each,idx) -> each.role = 'trainer')
S.map((each,idx) -> each.role = 'trainee')
# --------------------------- process the contents ----------------------------
S[0].say "自從這樣學新概念,媽媽再也不用擔心我的英語辣"
Speaker.quiet(4)
T[0].intro()
T[1].intro()
T[2].intro()
Speaker.quiet(1)
S[1].intro()
S[0].intro()
#S[2].intro()
#S[3].intro()
#S[4].intro()
# Read for the first time
T[1].say RD1.introduction
T[2].say title
T[2].say paragraph
# Intensive Reading
T[1].say IR.introduction
for question,idx in IR.teacher
T[2].say question
Speaker.quiet(0.1)
S[idx % 2].say IR.student[idx]
T[1].say RD2.introduction
T[2].say title
T[2].say paragraph
### vvvvvvvvvvvvvvvvvv
# (moved down)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
###
# ========= Ask Questions on Text ===========
T[1].say AQT.introduction
Speaker.quiet()
for t1Text,idx in AQT.example.teacher1
T[2].say t1Text
Speaker.quiet(0.5)
T[1].say AQT.example.teacher2[idx]
for t, idx in AQT.teacher
T[2].say t
S[0].say AQT.student[idx]
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[idx % 2].say OC.student[idx]
# (moved here since I think it might be too hard for the students)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
# Pattern Drills 1
T[1].say PDs1.introduction
for t,idx in PDs1.example.teacher1
T[0].say t
T[2].say PDs1.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs1.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs1.student1[idx]
T[2].say PDs1.teacher2[idx]
Speaker.quiet(2)
S[0].say PDs1.student2[idx]
# Pattern Drills 2
T[1].say PDs2.introduction
T[0].say PDs2.example.teacher0
T[1].say PDs2.example.teacher1
T[2].say PDs2.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs2.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs2.student1[idx]
Speaker.quiet(2)
S[1].say PDs2.student2[idx]
# Pattern Drills 3
T[1].say PDs3.introduction
T[0].say PDs3.example.teacher1
T[2].say PDs3.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs3.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs3.student[idx]
# Pattern Drills 4
T[1].say PDs4.introduction
for t,idx in PDs4.example.teacher1
T[0].say t
T[1].say PDs4.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs4.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs4.student1[idx]
T[1].say PDs4.teacher2[idx]
Speaker.quiet(2)
S[1].say PDs4.student2[idx]
###^^^^^^^^^^^^^^^^^^
# (moved forward)
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[1].say OC.student[idx]
###
T[2].say "That's all for today"
for each in T.concat(S)
each.say "bye bye",0.001
#this dosn't work#Speaker.end() | true | Speaker = require './speaker'
lesson01 = require './lesson01'
# 清除之前還沒有播放完的內容,從新開始
Speaker.restart()
# --------------------------- prepare for materials --------------------------
{
text:{title,paragraph}
RD1
IR
RD2
CQs
AQT
PDs1
PDs2
PDs3
PDs4
OC
} = lesson01
# ---------------------- set up roles and voices ---------------------------
{PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI} = Speaker
T = [
PI:NAME:<NAME>END_PI
PI:NAME:<NAME>END_PI
PI:NAME:<NAME>END_PI
]
S = [
PI:NAME:<NAME>END_PI
PI:NAME:<NAME>END_PI
#PI:NAME:<NAME>END_PI
#PI:NAME:<NAME>END_PI
#PI:NAME:<NAME>END_PI
]
T.map((each,idx) -> each.role = 'trainer')
S.map((each,idx) -> each.role = 'trainee')
# --------------------------- process the contents ----------------------------
S[0].say "自從這樣學新概念,媽媽再也不用擔心我的英語辣"
Speaker.quiet(4)
T[0].intro()
T[1].intro()
T[2].intro()
Speaker.quiet(1)
S[1].intro()
S[0].intro()
#S[2].intro()
#S[3].intro()
#S[4].intro()
# Read for the first time
T[1].say RD1.introduction
T[2].say title
T[2].say paragraph
# Intensive Reading
T[1].say IR.introduction
for question,idx in IR.teacher
T[2].say question
Speaker.quiet(0.1)
S[idx % 2].say IR.student[idx]
T[1].say RD2.introduction
T[2].say title
T[2].say paragraph
### vvvvvvvvvvvvvvvvvv
# (moved down)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
###
# ========= Ask Questions on Text ===========
T[1].say AQT.introduction
Speaker.quiet()
for t1Text,idx in AQT.example.teacher1
T[2].say t1Text
Speaker.quiet(0.5)
T[1].say AQT.example.teacher2[idx]
for t, idx in AQT.teacher
T[2].say t
S[0].say AQT.student[idx]
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[idx % 2].say OC.student[idx]
# (moved here since I think it might be too hard for the students)
# Comprehension Questions
T[1].say CQs.introduction
for question,idx in CQs.teacher
T[2].say question
Speaker.quiet(3)
S[0].say CQs.student[idx]
# Pattern Drills 1
T[1].say PDs1.introduction
for t,idx in PDs1.example.teacher1
T[0].say t
T[2].say PDs1.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs1.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs1.student1[idx]
T[2].say PDs1.teacher2[idx]
Speaker.quiet(2)
S[0].say PDs1.student2[idx]
# Pattern Drills 2
T[1].say PDs2.introduction
T[0].say PDs2.example.teacher0
T[1].say PDs2.example.teacher1
T[2].say PDs2.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs2.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs2.student1[idx]
Speaker.quiet(2)
S[1].say PDs2.student2[idx]
# Pattern Drills 3
T[1].say PDs3.introduction
T[0].say PDs3.example.teacher1
T[2].say PDs3.example.teacher2
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs3.teacher
T[2].say t
Speaker.quiet(2)
S[0].say PDs3.student[idx]
# Pattern Drills 4
T[1].say PDs4.introduction
for t,idx in PDs4.example.teacher1
T[0].say t
T[1].say PDs4.example.teacher2[idx]
Speaker.quiet(2)
T[2].say "Let's begin"
for t,idx in PDs4.teacher1
T[2].say t
Speaker.quiet(2)
S[0].say PDs4.student1[idx]
T[1].say PDs4.teacher2[idx]
Speaker.quiet(2)
S[1].say PDs4.student2[idx]
###^^^^^^^^^^^^^^^^^^
# (moved forward)
# Oral Composition
T[1].say OC.introduction
for t,idx in OC.teacher
T[2].say t
Speaker.quiet(2)
S[1].say OC.student[idx]
###
T[2].say "That's all for today"
for each in T.concat(S)
each.say "bye bye",0.001
#this dosn't work#Speaker.end() |
[
{
"context": "###\n# @author Will Steinmetz\n# jQuery notification plug-in inspired by the not",
"end": 28,
"score": 0.9998623132705688,
"start": 14,
"tag": "NAME",
"value": "Will Steinmetz"
},
{
"context": "ation style of Windows 8\n# Copyright (c)2013-2015, Will Steinmetz\n# Licens... | public/third_party/notific8/grunt/contrib-copy.coffee | pvndn/spa | 130 | ###
# @author Will Steinmetz
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, Will Steinmetz
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('copy',
font:
expand: true
src: ['src/fonts/*']
dest: 'dist/fonts'
filter: 'isFile'
flatten: true
css:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
js:
expand: true
src: [
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
code:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
)
grunt.loadNpmTasks 'grunt-contrib-copy'
| 198227 | ###
# @author <NAME>
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, <NAME>
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('copy',
font:
expand: true
src: ['src/fonts/*']
dest: 'dist/fonts'
filter: 'isFile'
flatten: true
css:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
js:
expand: true
src: [
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
code:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
)
grunt.loadNpmTasks 'grunt-contrib-copy'
| true | ###
# @author PI:NAME:<NAME>END_PI
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, PI:NAME:<NAME>END_PI
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('copy',
font:
expand: true
src: ['src/fonts/*']
dest: 'dist/fonts'
filter: 'isFile'
flatten: true
css:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
js:
expand: true
src: [
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
code:
expand: true
src: [
'build/css/*.css'
'build/css/*.css.map'
'build/js/*.js'
'build/js/*.js.map'
]
dest: 'dist'
filter: 'isFile'
flatten: true
)
grunt.loadNpmTasks 'grunt-contrib-copy'
|
[
{
"context": "tops responding with bender quotes\n#\n# Author:\n# Sam Roquitte <samroq@yahoo.com>\n\nmodule.exports = (robot) ->\n ",
"end": 272,
"score": 0.999884843826294,
"start": 260,
"tag": "NAME",
"value": "Sam Roquitte"
},
{
"context": " with bender quotes\n#\n# Author:\n# ... | src/bender.coffee | akitabox/hubot-bender | 0 | # Description
# hubot script to impersonate Bender from Futurama
#
# Configuration:
# none
#
# Commands:
# hubot bender on - starts responding to room messages with bender quotes
# hubot bender off - stops responding with bender quotes
#
# Author:
# Sam Roquitte <samroq@yahoo.com>
module.exports = (robot) ->
benderQuotes = [
'Hey. What kind of party is this? There\'s no booze and only one hooker.',
'That was stupid',
'Your an ass',
'Your mother',
'Up yours',
'I\'ll punchify your face',
'... the PTA has disbanded',
'It was a pornography store, I was buying pornography',
'I\'ll show you who is a booger blaster. I\'ll blast a booger so big...',
'That\'s what she said',
'Supercollider? I hardly knew her!',
'Hey baby... want to kill all humans?',
'Bite my shiny metal ass Todd!',
'Aw, I just made myself feel bad.',
'There. This\'ll teach those filthy bastards who\'s lovable.',
'Aw, it\'s nothing a lawsuit won\'t cure.',
'Stupid can opener! You killed my father, and now you\'ve come back for me!',
'You guys realize you live in a sewer, right? ',
'I\'m so lonely. I\'m gonna go eat a bucket of ice cream.',
'It ain\'t easy. It just proves how great I am. ',
'Others however will call me the World\'s Sexiest Killing Machine, that\'s fun at parties.',
'I accept this Nobel Peace Prize not just for myself, but for crime robots everywhere. Skoal! ',
'Oh, my God! Oh, my God! It\'s Elzar, the TV chef! Oh, kill me now, people!',
'Impending para un bending! ',
'But I don\'t belong here. I don\'t like things that are scary and painful.',
'In the name of all that is good and logical, we give thanks for the chemical energy we are about to absorb. To quote the prophet Jerematic, 10001010101...',
'Oh, no room for Bender, huh? Fine! I\'ll go build my own lunar lander, with blackjack and hookers. In fact, forget the lunar lander and the blackjack. Ahh, screw the whole thing!'
]
beAnAss = false
robot.hear /bender on/i, (msg) ->
beAnAss = true
msg.send 'I\'m back baby!'
robot.hear /bender off/i, (msg) ->
beAnAss = false
msg.send 'I am bender... please insert gerter'
robot.hear /(.*)/i, (msg) ->
if beAnAss
msg.send msg.random benderQuotes
| 214647 | # Description
# hubot script to impersonate Bender from Futurama
#
# Configuration:
# none
#
# Commands:
# hubot bender on - starts responding to room messages with bender quotes
# hubot bender off - stops responding with bender quotes
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
benderQuotes = [
'Hey. What kind of party is this? There\'s no booze and only one hooker.',
'That was stupid',
'Your an ass',
'Your mother',
'Up yours',
'I\'ll punchify your face',
'... the PTA has disbanded',
'It was a pornography store, I was buying pornography',
'I\'ll show you who is a booger blaster. I\'ll blast a booger so big...',
'That\'s what she said',
'Supercollider? I hardly knew her!',
'Hey baby... want to kill all humans?',
'Bite my shiny metal ass Todd!',
'Aw, I just made myself feel bad.',
'There. This\'ll teach those filthy bastards who\'s lovable.',
'Aw, it\'s nothing a lawsuit won\'t cure.',
'Stupid can opener! You killed my father, and now you\'ve come back for me!',
'You guys realize you live in a sewer, right? ',
'I\'m so lonely. I\'m gonna go eat a bucket of ice cream.',
'It ain\'t easy. It just proves how great I am. ',
'Others however will call me the World\'s Sexiest Killing Machine, that\'s fun at parties.',
'I accept this Nobel Peace Prize not just for myself, but for crime robots everywhere. Skoal! ',
'Oh, my God! Oh, my God! It\'s Elzar, the TV chef! Oh, kill me now, people!',
'Impending para un bending! ',
'But I don\'t belong here. I don\'t like things that are scary and painful.',
'In the name of all that is good and logical, we give thanks for the chemical energy we are about to absorb. To quote the prophet Jerematic, 10001010101...',
'Oh, no room for Bender, huh? Fine! I\'ll go build my own lunar lander, with blackjack and hookers. In fact, forget the lunar lander and the blackjack. Ahh, screw the whole thing!'
]
beAnAss = false
robot.hear /bender on/i, (msg) ->
beAnAss = true
msg.send 'I\'m back baby!'
robot.hear /bender off/i, (msg) ->
beAnAss = false
msg.send 'I am bender... please insert gerter'
robot.hear /(.*)/i, (msg) ->
if beAnAss
msg.send msg.random benderQuotes
| true | # Description
# hubot script to impersonate Bender from Futurama
#
# Configuration:
# none
#
# Commands:
# hubot bender on - starts responding to room messages with bender quotes
# hubot bender off - stops responding with bender quotes
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
benderQuotes = [
'Hey. What kind of party is this? There\'s no booze and only one hooker.',
'That was stupid',
'Your an ass',
'Your mother',
'Up yours',
'I\'ll punchify your face',
'... the PTA has disbanded',
'It was a pornography store, I was buying pornography',
'I\'ll show you who is a booger blaster. I\'ll blast a booger so big...',
'That\'s what she said',
'Supercollider? I hardly knew her!',
'Hey baby... want to kill all humans?',
'Bite my shiny metal ass Todd!',
'Aw, I just made myself feel bad.',
'There. This\'ll teach those filthy bastards who\'s lovable.',
'Aw, it\'s nothing a lawsuit won\'t cure.',
'Stupid can opener! You killed my father, and now you\'ve come back for me!',
'You guys realize you live in a sewer, right? ',
'I\'m so lonely. I\'m gonna go eat a bucket of ice cream.',
'It ain\'t easy. It just proves how great I am. ',
'Others however will call me the World\'s Sexiest Killing Machine, that\'s fun at parties.',
'I accept this Nobel Peace Prize not just for myself, but for crime robots everywhere. Skoal! ',
'Oh, my God! Oh, my God! It\'s Elzar, the TV chef! Oh, kill me now, people!',
'Impending para un bending! ',
'But I don\'t belong here. I don\'t like things that are scary and painful.',
'In the name of all that is good and logical, we give thanks for the chemical energy we are about to absorb. To quote the prophet Jerematic, 10001010101...',
'Oh, no room for Bender, huh? Fine! I\'ll go build my own lunar lander, with blackjack and hookers. In fact, forget the lunar lander and the blackjack. Ahh, screw the whole thing!'
]
beAnAss = false
robot.hear /bender on/i, (msg) ->
beAnAss = true
msg.send 'I\'m back baby!'
robot.hear /bender off/i, (msg) ->
beAnAss = false
msg.send 'I am bender... please insert gerter'
robot.hear /(.*)/i, (msg) ->
if beAnAss
msg.send msg.random benderQuotes
|
[
{
"context": "+ @name\n next()\n user = new User name: 'Jonathan'\n\n user.save ->\n test.equals User.schem",
"end": 1129,
"score": 0.9996048808097839,
"start": 1121,
"tag": "NAME",
"value": "Jonathan"
},
{
"context": "ame, user.name\n test.equals user.name... | node_modules/resources/persistence/vendor/jugglingdb/test/hookable_test.coffee | manecz/storytail | 1 | juggling = require('../index')
Schema = juggling.Schema
AbstractClass = juggling.AbstractClass
Hookable = juggling.Hookable
require('./spec_helper').init module.exports
schema = new Schema 'memory'
User = schema.define 'User',
email: String
name: String
password: String
state: String
age: Number
gender: String
domain: String
pendingPeriod: Number
createdByAdmin: Boolean
it "should trigger after initialize", (test) ->
User.afterInitialize = ->
User.afterInitialize = null
test.done()
user = new User
it "should trigger before create", (test) ->
User.beforeCreate = () ->
User.beforeCreate = null
test.done()
User.create -> test.ok "saved"
it "should trigger after create", (test) ->
User.afterCreate = (next) ->
User.afterCreate = null
next()
User.create ->
test.ok "saved"
test.done()
it 'should trigger before save', (test) ->
test.expect(3)
User.beforeSave = (next) ->
User.beforeSave = null
@name = 'mr. ' + @name
next()
user = new User name: 'Jonathan'
user.save ->
test.equals User.schema.adapter.cache.User[user.id].name, user.name
test.equals user.name, 'mr. Jonathan'
test.ok 'saved'
test.done()
it 'should trigger after save', (test) ->
User.afterSave = (next) ->
User.afterSave = null
next()
user = new User
user.save ->
test.ok "saved"
test.done()
it "should trigger before update", (test) ->
User.beforeUpdate = () ->
User.beforeUpdate = null
test.done()
User.create {}, (err, user) ->
user.updateAttributes email:"1@1.com", -> test.ok "updated"
it "should trigger after update", (test) ->
User.afterUpdate = () ->
User.afterUpdate = null
test.done()
User.create (err, user) ->
user.updateAttributes email: "1@1.com", -> test.ok "updated"
it "should trigger before destroy", (test)->
User.beforeDestroy = () ->
User.beforeDestroy = null
test.done()
User.create {}, (err, user) ->
user.destroy()
it "should trigger after destroy", (test) ->
User.afterDestroy = () ->
User.afterDestroy = null
test.done()
User.create (err, user) ->
user.destroy()
it 'allows me to modify attributes before saving', (test) ->
test.done()
| 176653 | juggling = require('../index')
Schema = juggling.Schema
AbstractClass = juggling.AbstractClass
Hookable = juggling.Hookable
require('./spec_helper').init module.exports
schema = new Schema 'memory'
User = schema.define 'User',
email: String
name: String
password: String
state: String
age: Number
gender: String
domain: String
pendingPeriod: Number
createdByAdmin: Boolean
it "should trigger after initialize", (test) ->
User.afterInitialize = ->
User.afterInitialize = null
test.done()
user = new User
it "should trigger before create", (test) ->
User.beforeCreate = () ->
User.beforeCreate = null
test.done()
User.create -> test.ok "saved"
it "should trigger after create", (test) ->
User.afterCreate = (next) ->
User.afterCreate = null
next()
User.create ->
test.ok "saved"
test.done()
it 'should trigger before save', (test) ->
test.expect(3)
User.beforeSave = (next) ->
User.beforeSave = null
@name = 'mr. ' + @name
next()
user = new User name: '<NAME>'
user.save ->
test.equals User.schema.adapter.cache.User[user.id].name, user.name
test.equals user.name, 'mr. <NAME>'
test.ok 'saved'
test.done()
it 'should trigger after save', (test) ->
User.afterSave = (next) ->
User.afterSave = null
next()
user = new User
user.save ->
test.ok "saved"
test.done()
it "should trigger before update", (test) ->
User.beforeUpdate = () ->
User.beforeUpdate = null
test.done()
User.create {}, (err, user) ->
user.updateAttributes email:"<EMAIL>", -> test.ok "updated"
it "should trigger after update", (test) ->
User.afterUpdate = () ->
User.afterUpdate = null
test.done()
User.create (err, user) ->
user.updateAttributes email: "<EMAIL>", -> test.ok "updated"
it "should trigger before destroy", (test)->
User.beforeDestroy = () ->
User.beforeDestroy = null
test.done()
User.create {}, (err, user) ->
user.destroy()
it "should trigger after destroy", (test) ->
User.afterDestroy = () ->
User.afterDestroy = null
test.done()
User.create (err, user) ->
user.destroy()
it 'allows me to modify attributes before saving', (test) ->
test.done()
| true | juggling = require('../index')
Schema = juggling.Schema
AbstractClass = juggling.AbstractClass
Hookable = juggling.Hookable
require('./spec_helper').init module.exports
schema = new Schema 'memory'
User = schema.define 'User',
email: String
name: String
password: String
state: String
age: Number
gender: String
domain: String
pendingPeriod: Number
createdByAdmin: Boolean
it "should trigger after initialize", (test) ->
User.afterInitialize = ->
User.afterInitialize = null
test.done()
user = new User
it "should trigger before create", (test) ->
User.beforeCreate = () ->
User.beforeCreate = null
test.done()
User.create -> test.ok "saved"
it "should trigger after create", (test) ->
User.afterCreate = (next) ->
User.afterCreate = null
next()
User.create ->
test.ok "saved"
test.done()
it 'should trigger before save', (test) ->
test.expect(3)
User.beforeSave = (next) ->
User.beforeSave = null
@name = 'mr. ' + @name
next()
user = new User name: 'PI:NAME:<NAME>END_PI'
user.save ->
test.equals User.schema.adapter.cache.User[user.id].name, user.name
test.equals user.name, 'mr. PI:NAME:<NAME>END_PI'
test.ok 'saved'
test.done()
it 'should trigger after save', (test) ->
User.afterSave = (next) ->
User.afterSave = null
next()
user = new User
user.save ->
test.ok "saved"
test.done()
it "should trigger before update", (test) ->
User.beforeUpdate = () ->
User.beforeUpdate = null
test.done()
User.create {}, (err, user) ->
user.updateAttributes email:"PI:EMAIL:<EMAIL>END_PI", -> test.ok "updated"
it "should trigger after update", (test) ->
User.afterUpdate = () ->
User.afterUpdate = null
test.done()
User.create (err, user) ->
user.updateAttributes email: "PI:EMAIL:<EMAIL>END_PI", -> test.ok "updated"
it "should trigger before destroy", (test)->
User.beforeDestroy = () ->
User.beforeDestroy = null
test.done()
User.create {}, (err, user) ->
user.destroy()
it "should trigger after destroy", (test) ->
User.afterDestroy = () ->
User.afterDestroy = null
test.done()
User.create (err, user) ->
user.destroy()
it 'allows me to modify attributes before saving', (test) ->
test.done()
|
[
{
"context": "orObject =\n value: null\n\n #https://github.com/petkaantonov/bluebird/wiki/Optimization-killers\n tryCatch = (",
"end": 5810,
"score": 0.999627411365509,
"start": 5798,
"tag": "USERNAME",
"value": "petkaantonov"
},
{
"context": "k)\n return false\n true\n\... | public/bower_components/angular-google-maps/src/coffee/directives/api/utils/_async.coffee | arslannaseem/notasoft | 0 | angular.module('uiGmapgoogle-maps.directives.api.utils')
.service('uiGmap_sync', [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service 'uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q','uiGmapDataStructures', 'uiGmapGmapUtil',
($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) ->
promiseTypes = uiGmapPromise.promiseTypes
isInProgress = uiGmapPromise.isInProgress
promiseStatus = uiGmapPromise.promiseStatus
ExposedPromise = uiGmapPromise.ExposedPromise
SniffedPromise = uiGmapPromise.SniffedPromise
kickPromise = (sniffedPromise, cancelCb) ->
#kick a promise off and log some info on it
promise = sniffedPromise.promise()
promise.promiseType = sniffedPromise.promiseType
$log.debug "promiseType: #{promise.promiseType}, state: #{promiseStatus promise.$$state.status}" if promise.$$state
promise.cancelCb = cancelCb
promise
doSkippPromise = (sniffedPromise,lastPromise) ->
# note this skipp could be specific to polys (but it works for that)
if sniffedPromise.promiseType == promiseTypes.create and
lastPromise.promiseType != promiseTypes.delete and lastPromise.promiseType != promiseTypes.init
$log.debug "lastPromise.promiseType #{lastPromise.promiseType}, newPromiseType: #{sniffedPromise.promiseType}, SKIPPED MUST COME AFTER DELETE ONLY"
return true
false
maybeCancelPromises = (queue, sniffedPromise,lastPromise) ->
# $log.warn "sniff: promiseType: #{sniffedPromise.promiseType}, lastPromiseType: #{lastPromise.promiseType}"
# $log.warn "lastPromise.cancelCb #{lastPromise.cancelCb}"
if sniffedPromise.promiseType == promiseTypes.delete and lastPromise.promiseType != promiseTypes.delete
if lastPromise.cancelCb? and _.isFunction(lastPromise.cancelCb) and isInProgress(lastPromise)
$log.debug "promiseType: #{sniffedPromise.promiseType}, CANCELING LAST PROMISE type: #{lastPromise.promiseType}"
lastPromise.cancelCb('cancel safe')
#see if we can cancel anything else
first = queue.peek()
if first? and isInProgress(first)# and first.promiseType != promiseTypes.delete
if first.hasOwnProperty("cancelCb") and _.isFunction first.cancelCb
$log.debug "promiseType: #{first.promiseType}, CANCELING FIRST PROMISE type: #{first.promiseType}"
first.cancelCb('cancel safe')
else
$log.warn 'first promise was not cancelable'
###
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
###
PromiseQueueManager = (existingPiecesObj, sniffedPromise, cancelCb) ->
unless existingPiecesObj.existingPieces
#TODO: rename existingPieces to some kind of queue
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue()
existingPiecesObj.existingPieces.enqueue kickPromise(sniffedPromise, cancelCb)
else
lastPromise = _.last existingPiecesObj.existingPieces._content
return if doSkippPromise(sniffedPromise, lastPromise)
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise)
newPromise = ExposedPromise lastPromise.finally ->
kickPromise(sniffedPromise, cancelCb)
newPromise.cancelCb = cancelCb
newPromise.promiseType = sniffedPromise.promiseType
existingPiecesObj.existingPieces.enqueue newPromise
# finally is important as we don't care how something is canceled
lastPromise.finally ->
# keep the queue tight
existingPiecesObj.existingPieces.dequeue()
managePromiseQueue = (objectToLock, promiseType, msg = '', cancelCb, fnPromise) ->
cancelLogger = (msg) ->
$log.debug "#{msg}: #{msg}"
cancelCb(msg)
PromiseQueueManager objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger
defaultChunkSize = 80
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
if result == 'cancel safe'
# THIS IS MAD IMPORTANT AS THIS IS OUR FALLTHOUGH TO ALLOW
# _async.each iterator to drop out at a safe point (IE the end of its iterator callback)
return false
true
###
Author: Nicholas McCready & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
keepGoing = true
while keepGoing and cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
keepGoing = logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if keepGoing and i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, chunkSizeOrDontChunk = defaultChunkSize, pauseCb, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, chunkSizeOrDontChunk, pauseCb, index, pauseMilli)
.then ->
results
each: each
map: map
managePromiseQueue: managePromiseQueue
promiseLock: managePromiseQueue
defaultChunkSize: defaultChunkSize
chunkSizeFrom:(fromSize) ->
ret = undefined
if _.isNumber fromSize
ret = fromSize
if uiGmapGmapUtil.isFalse(fromSize) or fromSize == false
ret = false
ret
]
| 5826 | angular.module('uiGmapgoogle-maps.directives.api.utils')
.service('uiGmap_sync', [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service 'uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q','uiGmapDataStructures', 'uiGmapGmapUtil',
($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) ->
promiseTypes = uiGmapPromise.promiseTypes
isInProgress = uiGmapPromise.isInProgress
promiseStatus = uiGmapPromise.promiseStatus
ExposedPromise = uiGmapPromise.ExposedPromise
SniffedPromise = uiGmapPromise.SniffedPromise
kickPromise = (sniffedPromise, cancelCb) ->
#kick a promise off and log some info on it
promise = sniffedPromise.promise()
promise.promiseType = sniffedPromise.promiseType
$log.debug "promiseType: #{promise.promiseType}, state: #{promiseStatus promise.$$state.status}" if promise.$$state
promise.cancelCb = cancelCb
promise
doSkippPromise = (sniffedPromise,lastPromise) ->
# note this skipp could be specific to polys (but it works for that)
if sniffedPromise.promiseType == promiseTypes.create and
lastPromise.promiseType != promiseTypes.delete and lastPromise.promiseType != promiseTypes.init
$log.debug "lastPromise.promiseType #{lastPromise.promiseType}, newPromiseType: #{sniffedPromise.promiseType}, SKIPPED MUST COME AFTER DELETE ONLY"
return true
false
maybeCancelPromises = (queue, sniffedPromise,lastPromise) ->
# $log.warn "sniff: promiseType: #{sniffedPromise.promiseType}, lastPromiseType: #{lastPromise.promiseType}"
# $log.warn "lastPromise.cancelCb #{lastPromise.cancelCb}"
if sniffedPromise.promiseType == promiseTypes.delete and lastPromise.promiseType != promiseTypes.delete
if lastPromise.cancelCb? and _.isFunction(lastPromise.cancelCb) and isInProgress(lastPromise)
$log.debug "promiseType: #{sniffedPromise.promiseType}, CANCELING LAST PROMISE type: #{lastPromise.promiseType}"
lastPromise.cancelCb('cancel safe')
#see if we can cancel anything else
first = queue.peek()
if first? and isInProgress(first)# and first.promiseType != promiseTypes.delete
if first.hasOwnProperty("cancelCb") and _.isFunction first.cancelCb
$log.debug "promiseType: #{first.promiseType}, CANCELING FIRST PROMISE type: #{first.promiseType}"
first.cancelCb('cancel safe')
else
$log.warn 'first promise was not cancelable'
###
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
###
PromiseQueueManager = (existingPiecesObj, sniffedPromise, cancelCb) ->
unless existingPiecesObj.existingPieces
#TODO: rename existingPieces to some kind of queue
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue()
existingPiecesObj.existingPieces.enqueue kickPromise(sniffedPromise, cancelCb)
else
lastPromise = _.last existingPiecesObj.existingPieces._content
return if doSkippPromise(sniffedPromise, lastPromise)
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise)
newPromise = ExposedPromise lastPromise.finally ->
kickPromise(sniffedPromise, cancelCb)
newPromise.cancelCb = cancelCb
newPromise.promiseType = sniffedPromise.promiseType
existingPiecesObj.existingPieces.enqueue newPromise
# finally is important as we don't care how something is canceled
lastPromise.finally ->
# keep the queue tight
existingPiecesObj.existingPieces.dequeue()
managePromiseQueue = (objectToLock, promiseType, msg = '', cancelCb, fnPromise) ->
cancelLogger = (msg) ->
$log.debug "#{msg}: #{msg}"
cancelCb(msg)
PromiseQueueManager objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger
defaultChunkSize = 80
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
if result == 'cancel safe'
# THIS IS MAD IMPORTANT AS THIS IS OUR FALLTHOUGH TO ALLOW
# _async.each iterator to drop out at a safe point (IE the end of its iterator callback)
return false
true
###
Author: <NAME> & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
keepGoing = true
while keepGoing and cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
keepGoing = logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if keepGoing and i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, chunkSizeOrDontChunk = defaultChunkSize, pauseCb, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, chunkSizeOrDontChunk, pauseCb, index, pauseMilli)
.then ->
results
each: each
map: map
managePromiseQueue: managePromiseQueue
promiseLock: managePromiseQueue
defaultChunkSize: defaultChunkSize
chunkSizeFrom:(fromSize) ->
ret = undefined
if _.isNumber fromSize
ret = fromSize
if uiGmapGmapUtil.isFalse(fromSize) or fromSize == false
ret = false
ret
]
| true | angular.module('uiGmapgoogle-maps.directives.api.utils')
.service('uiGmap_sync', [ ->
fakePromise: ->
_cb = undefined
then: (cb) ->
_cb = cb
resolve: () ->
_cb.apply(undefined, arguments)
])
.service 'uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q','uiGmapDataStructures', 'uiGmapGmapUtil',
($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) ->
promiseTypes = uiGmapPromise.promiseTypes
isInProgress = uiGmapPromise.isInProgress
promiseStatus = uiGmapPromise.promiseStatus
ExposedPromise = uiGmapPromise.ExposedPromise
SniffedPromise = uiGmapPromise.SniffedPromise
kickPromise = (sniffedPromise, cancelCb) ->
#kick a promise off and log some info on it
promise = sniffedPromise.promise()
promise.promiseType = sniffedPromise.promiseType
$log.debug "promiseType: #{promise.promiseType}, state: #{promiseStatus promise.$$state.status}" if promise.$$state
promise.cancelCb = cancelCb
promise
doSkippPromise = (sniffedPromise,lastPromise) ->
# note this skipp could be specific to polys (but it works for that)
if sniffedPromise.promiseType == promiseTypes.create and
lastPromise.promiseType != promiseTypes.delete and lastPromise.promiseType != promiseTypes.init
$log.debug "lastPromise.promiseType #{lastPromise.promiseType}, newPromiseType: #{sniffedPromise.promiseType}, SKIPPED MUST COME AFTER DELETE ONLY"
return true
false
maybeCancelPromises = (queue, sniffedPromise,lastPromise) ->
# $log.warn "sniff: promiseType: #{sniffedPromise.promiseType}, lastPromiseType: #{lastPromise.promiseType}"
# $log.warn "lastPromise.cancelCb #{lastPromise.cancelCb}"
if sniffedPromise.promiseType == promiseTypes.delete and lastPromise.promiseType != promiseTypes.delete
if lastPromise.cancelCb? and _.isFunction(lastPromise.cancelCb) and isInProgress(lastPromise)
$log.debug "promiseType: #{sniffedPromise.promiseType}, CANCELING LAST PROMISE type: #{lastPromise.promiseType}"
lastPromise.cancelCb('cancel safe')
#see if we can cancel anything else
first = queue.peek()
if first? and isInProgress(first)# and first.promiseType != promiseTypes.delete
if first.hasOwnProperty("cancelCb") and _.isFunction first.cancelCb
$log.debug "promiseType: #{first.promiseType}, CANCELING FIRST PROMISE type: #{first.promiseType}"
first.cancelCb('cancel safe')
else
$log.warn 'first promise was not cancelable'
###
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
###
PromiseQueueManager = (existingPiecesObj, sniffedPromise, cancelCb) ->
unless existingPiecesObj.existingPieces
#TODO: rename existingPieces to some kind of queue
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue()
existingPiecesObj.existingPieces.enqueue kickPromise(sniffedPromise, cancelCb)
else
lastPromise = _.last existingPiecesObj.existingPieces._content
return if doSkippPromise(sniffedPromise, lastPromise)
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise)
newPromise = ExposedPromise lastPromise.finally ->
kickPromise(sniffedPromise, cancelCb)
newPromise.cancelCb = cancelCb
newPromise.promiseType = sniffedPromise.promiseType
existingPiecesObj.existingPieces.enqueue newPromise
# finally is important as we don't care how something is canceled
lastPromise.finally ->
# keep the queue tight
existingPiecesObj.existingPieces.dequeue()
managePromiseQueue = (objectToLock, promiseType, msg = '', cancelCb, fnPromise) ->
cancelLogger = (msg) ->
$log.debug "#{msg}: #{msg}"
cancelCb(msg)
PromiseQueueManager objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger
defaultChunkSize = 80
errorObject =
value: null
#https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
tryCatch = (fn, ctx, args) ->
try
return fn.apply(ctx, args)
catch e
errorObject.value = e
return errorObject
logTryCatch = (fn, ctx, deferred, args) ->
result = tryCatch(fn, ctx, args)
if result == errorObject
msg = "error within chunking iterator: #{errorObject.value}"
$log.error msg
deferred.reject msg
if result == 'cancel safe'
# THIS IS MAD IMPORTANT AS THIS IS OUR FALLTHOUGH TO ALLOW
# _async.each iterator to drop out at a safe point (IE the end of its iterator callback)
return false
true
###
Author: PI:NAME:<NAME>END_PI & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
###
doChunk = (array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) ->
if chunkSizeOrDontChunk and chunkSizeOrDontChunk < array.length
cnt = chunkSizeOrDontChunk
else
cnt = array.length
i = index
keepGoing = true
while keepGoing and cnt-- and i < (if array then array.length else i + 1)
# process array[index] here
keepGoing = logTryCatch chunkCb, undefined, overallD, [array[i], i]
++i
if array
if keepGoing and i < array.length
index = i
if chunkSizeOrDontChunk
if pauseCb? and _.isFunction pauseCb
logTryCatch pauseCb, undefined, overallD, []
$timeout ->
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index
, pauseMilli, false
else
overallD.resolve()
each = (array, chunk, chunkSizeOrDontChunk = defaultChunkSize, pauseCb, index = 0, pauseMilli = 1) ->
ret = undefined
overallD = uiGmapPromise.defer()
ret = overallD.promise
unless pauseMilli
error = 'pause (delay) must be set from _async!'
$log.error error
overallD.reject error
return ret
if array == undefined or array?.length <= 0
overallD.resolve()
return ret
# set this to whatever number of items you can process at once
doChunk array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index
return ret
#copied from underscore but w/ async each above
map = (objs, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli) ->
results = []
return uiGmapPromise.resolve(results) unless objs? and objs?.length > 0
each(objs, (o) ->
results.push iterator o
, chunkSizeOrDontChunk, pauseCb, index, pauseMilli)
.then ->
results
each: each
map: map
managePromiseQueue: managePromiseQueue
promiseLock: managePromiseQueue
defaultChunkSize: defaultChunkSize
chunkSizeFrom:(fromSize) ->
ret = undefined
if _.isNumber fromSize
ret = fromSize
if uiGmapGmapUtil.isFalse(fromSize) or fromSize == false
ret = false
ret
]
|
[
{
"context": "login\n $scope.password = login_data.password\n $scope.sms_verification = true\n ",
"end": 1226,
"score": 0.84743732213974,
"start": 1218,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " login: $scope.login\n pass... | resources/assets/coffee/controllers/login.coffee | maxflex/tcms | 0 | angular
.module 'Egecms'
.controller 'LoginCtrl', ($scope, $http) ->
loadImage = ->
$scope.image_loaded = false
img = new Image
img.addEventListener "load", ->
$('body').css({'background-image': "url(#{$scope.wallpaper.image_url})"})
$scope.image_loaded = true
$scope.$apply()
setTimeout ->
$('#center').removeClass('animated').removeClass('fadeIn').removeAttr('style')
, 2000
img.src = $scope.wallpaper.image_url
angular.element(document).ready ->
loadImage()
$('input[autocomplete="off"]').each ->
input = this
id = $(input).attr('id')
$(input).removeAttr('id')
setTimeout ->
$(input).attr('id', id)
, 2000
$scope.l = Ladda.create(document.querySelector('#login-submit'))
login_data = $.cookie("login_data")
if login_data isnt undefined
login_data = JSON.parse(login_data)
$scope.login = login_data.login
$scope.password = login_data.password
$scope.sms_verification = true
$scope.$apply()
#обработка события по enter в форме логина
$scope.enter = ($event) ->
if $event.keyCode == 13
$scope.checkFields()
$scope.goLogin = ->
# $('center').removeClass('invalid')
$http.post 'login',
login: $scope.login
password: $scope.password
code: $scope.code
# captcha: grecaptcha.getResponse()
.then (response) ->
# grecaptcha.reset()
if response.data is true
$.removeCookie('login_data')
location.reload()
else if response.data is 'sms'
$scope.in_process = false
$scope.l.stop()
$scope.sms_verification = true
$.cookie("login_data", JSON.stringify({login: $scope.login, password: $scope.password}), { expires: 1 / (24 * 60) * 2, path: '/' })
else
$scope.in_process = false
$scope.l.stop()
$scope.error = "Неправильная пара логин-пароль"
# $('center').addClass('invalid')
$scope.$apply()
$scope.checkFields = ->
$scope.l.start()
$scope.in_process = true
$scope.goLogin()
# if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
| 187937 | angular
.module 'Egecms'
.controller 'LoginCtrl', ($scope, $http) ->
loadImage = ->
$scope.image_loaded = false
img = new Image
img.addEventListener "load", ->
$('body').css({'background-image': "url(#{$scope.wallpaper.image_url})"})
$scope.image_loaded = true
$scope.$apply()
setTimeout ->
$('#center').removeClass('animated').removeClass('fadeIn').removeAttr('style')
, 2000
img.src = $scope.wallpaper.image_url
angular.element(document).ready ->
loadImage()
$('input[autocomplete="off"]').each ->
input = this
id = $(input).attr('id')
$(input).removeAttr('id')
setTimeout ->
$(input).attr('id', id)
, 2000
$scope.l = Ladda.create(document.querySelector('#login-submit'))
login_data = $.cookie("login_data")
if login_data isnt undefined
login_data = JSON.parse(login_data)
$scope.login = login_data.login
$scope.password = login_data.<PASSWORD>
$scope.sms_verification = true
$scope.$apply()
#обработка события по enter в форме логина
$scope.enter = ($event) ->
if $event.keyCode == 13
$scope.checkFields()
$scope.goLogin = ->
# $('center').removeClass('invalid')
$http.post 'login',
login: $scope.login
password: $<PASSWORD>
code: $scope.code
# captcha: grecaptcha.getResponse()
.then (response) ->
# grecaptcha.reset()
if response.data is true
$.removeCookie('login_data')
location.reload()
else if response.data is 'sms'
$scope.in_process = false
$scope.l.stop()
$scope.sms_verification = true
$.cookie("login_data", JSON.stringify({login: $scope.login, password: $scope.password}), { expires: 1 / (24 * 60) * 2, path: '/' })
else
$scope.in_process = false
$scope.l.stop()
$scope.error = "Неправильная пара логин-пароль"
# $('center').addClass('invalid')
$scope.$apply()
$scope.checkFields = ->
$scope.l.start()
$scope.in_process = true
$scope.goLogin()
# if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
| true | angular
.module 'Egecms'
.controller 'LoginCtrl', ($scope, $http) ->
loadImage = ->
$scope.image_loaded = false
img = new Image
img.addEventListener "load", ->
$('body').css({'background-image': "url(#{$scope.wallpaper.image_url})"})
$scope.image_loaded = true
$scope.$apply()
setTimeout ->
$('#center').removeClass('animated').removeClass('fadeIn').removeAttr('style')
, 2000
img.src = $scope.wallpaper.image_url
angular.element(document).ready ->
loadImage()
$('input[autocomplete="off"]').each ->
input = this
id = $(input).attr('id')
$(input).removeAttr('id')
setTimeout ->
$(input).attr('id', id)
, 2000
$scope.l = Ladda.create(document.querySelector('#login-submit'))
login_data = $.cookie("login_data")
if login_data isnt undefined
login_data = JSON.parse(login_data)
$scope.login = login_data.login
$scope.password = login_data.PI:PASSWORD:<PASSWORD>END_PI
$scope.sms_verification = true
$scope.$apply()
#обработка события по enter в форме логина
$scope.enter = ($event) ->
if $event.keyCode == 13
$scope.checkFields()
$scope.goLogin = ->
# $('center').removeClass('invalid')
$http.post 'login',
login: $scope.login
password: $PI:PASSWORD:<PASSWORD>END_PI
code: $scope.code
# captcha: grecaptcha.getResponse()
.then (response) ->
# grecaptcha.reset()
if response.data is true
$.removeCookie('login_data')
location.reload()
else if response.data is 'sms'
$scope.in_process = false
$scope.l.stop()
$scope.sms_verification = true
$.cookie("login_data", JSON.stringify({login: $scope.login, password: $scope.password}), { expires: 1 / (24 * 60) * 2, path: '/' })
else
$scope.in_process = false
$scope.l.stop()
$scope.error = "Неправильная пара логин-пароль"
# $('center').addClass('invalid')
$scope.$apply()
$scope.checkFields = ->
$scope.l.start()
$scope.in_process = true
$scope.goLogin()
# if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
|
[
{
"context": "name:\n label: 'Username'\n description:",
"end": 88798,
"score": 0.7989317178726196,
"start": 88790,
"tag": "USERNAME",
"value": "Username"
},
{
"context": " {\n annot... | cyclotron-site/app/scripts/common/services/services.commonConfigService.coffee | baumandm/cyclotron | 1,657 | ###
# Copyright (c) 2013-2018 the original author or authors.
#
# Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
#
# 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.
###
# Common Config File - all default or shared configs
cyclotronServices.factory 'commonConfigService', ->
linkedWidgetOptions = (dashboard) ->
linkedWidgets = {}
_.each dashboard.pages, (page, pageIndex) ->
_.each page.widgets, (widget, widgetIndex) ->
return if widget.widget == 'linkedWidget'
widgetName = _.titleCase(widget.widget)
if widget.name?.length > 0 or widget.title?.length > 0
widgetName += ': ' + (widget.name || widget.title)
linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex }
linkedWidgets
datasourceOptions = (dashboard) ->
dataSources = {}
_.each dashboard.dataSources, (dataSource) ->
dataSources[dataSource.name] = { value: dataSource.name }
dataSources
exports = {
version: '2.0.2'
logging:
enableDebug: false
authentication:
enable: false
loginMessage: 'Please login using your LDAP username and password.'
analytics:
enable: false
newUser:
enableMessage: true
welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.'
iconClass: 'fa-info'
autoDecayDuration: 1
# Dashboard settings
dashboard:
properties:
name:
label: 'Name'
description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.'
placeholder: 'Dashboard Name'
type: 'string'
required: true
order: 0
displayName:
label: 'Display Name'
description: 'Display Name; this is displayed in the browser title bar or the Header Widget.'
placeholder: 'Display Name'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 1
description:
label: 'Description'
description: 'A short summary of the Dashboard\'s purpose or capabilities.'
placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.'
type: 'string'
required: false
order: 2
theme:
label: 'Theme'
description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.'
type: 'string'
default: 'dark'
required: false
options:
charcoal:
label: 'Charcoal'
value: 'charcoal'
dashboardBackgroundColor: '#1E2328'
aceTheme: 'solarized_dark'
dark:
label: 'Dark'
value: 'dark'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
darkmetro:
label: 'Dark Metro'
value: 'darkmetro'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
gto:
label: 'GTO'
value: 'gto'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
light:
label: 'Light'
value: 'light'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
lightborderless:
label: 'Light (borderless)'
value: 'lightborderless'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
dark2:
label: 'Very Dark'
value: 'dark2'
dashboardBackgroundColor: 'black'
aceTheme: 'monokai'
order: 5
themeVariant:
label: 'Theme Variant'
description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.'
type: 'string'
default: 'default'
required: false
defaultHidden: true
options:
default:
value: 'default'
transparent:
value: 'transparent'
'transparent-unpadded':
value: 'transparent-unpadded'
order: 6
style:
label: 'Style'
description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.'
type: 'string'
default: 'normal'
required: false
options:
normal:
value: 'normal'
fullscreen:
value: 'fullscreen'
defaultHidden: true
order: 7
autoRotate:
label: 'Auto-Rotate'
description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 10
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.'
type: 'integer'
placeholder: 'Seconds per page'
default: 60
required: false
defaultHidden: true
order: 11
preload:
label: 'Pre-Load Time (seconds)'
description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.'
placeholder: 'Seconds'
type: 'integer'
default: 0.050
required: false
defaultHidden: true
order: 12
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, all links will open in a new browser window; this is the default.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showDashboardControls:
label: 'Show Dashboard Controls'
description: 'If false, hides the default Dashboard controls (rotation, export, etc)'
type: 'boolean'
required: false
default: true
defaultHidden: true
sidebar:
label: 'Sidebar'
description: ''
type: 'propertyset'
default: {}
defaultHidden: true
properties:
showDashboardSidebar:
label: 'Show Dashboard Sidebar'
description: 'If false, hides the default Dashboard Sidebar.'
type: 'boolean'
required: false
default: false
order: 10
showDashboardTitle:
label: 'Include Dashboard Title'
description: 'Enables a section of the sidebar for the Dashboard title.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 11
showToolbar:
label: 'Include Toolbar'
description: 'Enables a toolbar in the sidebar.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 12
showHideWidgets:
label: 'Include Show/Hide Widgets'
description: 'Enables a section of the sidebar for overriding the visibility of Widgets.'
type: 'boolean'
required: false
default: false
defaultHidden: true
order: 13
sidebarContent:
label: 'Custom Sidebar Sections'
singleLabel: 'Section'
description: 'One or more sections of content to display in the Sidebar.'
type: 'propertyset[]'
default: []
order: 15
properties:
heading:
label: 'Heading'
description: 'Heading for the Sidebar section.'
type: 'string'
inlineJs: true
order: 1
html:
label: 'HTML Content'
description: 'HTML Content to display.'
placeholder: 'Value'
type: 'editor'
editorMode: 'html'
inlineJs: true
order: 2
pages:
label: 'Pages'
description: 'The list of Page definitions which compose the Dashboard.'
type: 'pages'
default: []
required: true
properties:
name:
label: 'Name'
description: 'Name of this page; used in the browser title and URL.'
placeholder: 'Page Name'
type: 'string'
required: false
order: 0
layout:
label: 'Layout'
description: 'Contains properties for configuring the Page layout and dimensions.'
type: 'propertyset'
default: {}
required: false
properties:
gridColumns:
label: 'Grid Columns'
description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.'
type: 'integer'
required: false
order: 0
gridRows:
label: 'Grid Rows'
description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.'
type: 'integer'
required: false
order: 1
gridWidthAdjustment:
label: 'Grid Page Width Adjustment'
description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).'
type: 'integer'
default: 0
required: false
defaultHidden: true
order: 2
gridHeightAdjustment:
label: 'Grid Page Height Adjustment'
description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.'
type: 'integer'
default: 0
required: false
order: 3
gutter:
label: 'Gutter'
description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 5
borderWidth:
label: 'Border Width'
description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.'
type: 'integer'
default: null
required: false
defaultHidden: true
order: 6
margin:
label: 'Margin'
description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 7
scrolling:
label: 'Scrolling Enabled'
description: 'Enables vertical scrolling of the page to display content longer than the current browser size.'
type: 'boolean'
default: true
required: false
defaultHidden: true
order: 8
order: 2
widgets:
label: 'Widgets'
description: 'An array of one or more Widgets to display on the page'
type: 'propertyset[]'
subState: 'edit.widget'
headingfn: 'getWidgetName'
default: []
required: true
properties:
widget:
label: 'Type'
description: 'The type of Widget to be rendered.'
type: 'string'
required: true
name:
label: 'Name'
description: 'Internal Widget name, displayed in the Dashboard Editor.'
placeholder: 'Name'
type: 'string'
required: false
defaultHidden: true
inlineJs: false
order: 1
title:
label: 'Title'
description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.'
placeholder: 'Widget Title'
type: 'string'
required: false
inlineJs: true
order: 2
gridHeight:
label: 'Grid Rows'
description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.'
placeholder: 'Number of Rows'
type: 'integer'
default: '1'
required: false
order: 100
gridWidth:
label: 'Grid Columns'
description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.'
placeholder: 'Number of Columns'
type: 'integer'
default: '1'
required: false
order: 101
height:
label: 'Height'
description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Height'
type: 'string'
required: false
defaultHidden: true
order: 102
width:
label: 'Width'
description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Width'
type: 'string'
required: false
defaultHidden: true
order: 103
autoHeight:
label: 'Auto-Height (Fit to Contents)'
description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.'
type: 'boolean'
required: false
defaultHidden: true
order: 104
helpText:
label: 'Help Text'
description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 109
theme:
label: 'Theme'
description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 110
themeVariant:
label: 'Theme Variant'
description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 111
noData:
label: 'No Data Message'
description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 120
noscroll:
label: 'No Scroll'
description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 121
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 122
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 123
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 124
hidden:
label: 'Hidden'
description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 125
order: 3
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.'
placeholder: 'Seconds per page'
inherit: true
type: 'integer'
required: false
defaultHidden: true
order: 4
frequency:
label: 'Frequency'
description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.'
default: 1
type: 'integer'
required: false
defaultHidden: true
order: 5
theme:
label: 'Theme'
description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 6
themeVariant:
label: 'Theme Variant'
description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 7
style:
label: 'Style'
description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 8
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 10
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 11
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 12;
dataSources:
label: 'Data Sources'
description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.'
type: 'datasources'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The Data Source Name is used to reference the Data Source from a widget'
placeholder: 'Data Source Name'
type: 'string'
required: true
order: 1
type:
label: 'Type'
description: 'Specifies the implementation type of the Data Source'
type: 'string'
required: true
order: 0
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 101
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
defaultHidden: true
order: 102
preload:
label: 'Preload'
description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
deferred:
label: 'Deferred'
description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
errorHandler:
label: 'Error Handler'
description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 104
options:
cloudwatch:
value: 'cloudwatch'
label: 'CloudWatch'
message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".'
placeholder: 'CloudWatch Endpoint'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
awsCredentials:
label: 'AWS Credentials'
description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: true
order: 12
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
parameters:
label: 'CloudWatch Parameters'
description: 'Set of parameters for the CloudWatch API.'
type: 'propertyset'
required: true
order: 13
properties:
Action:
label: 'Action'
description: 'Specifies one of the CloudWatch actions.'
type: 'string'
default: 'auto'
inlineJs: true
options:
ListMetrics:
value: 'ListMetrics'
GetMetricStatistics:
value: 'GetMetricStatistics'
required: true
order: 1
Namespace:
label: 'Namespace'
description: 'The namespace to filter against.'
type: 'string'
inlineJs: true
required: false
order: 2
MeasureName:
label: 'Metric Name'
description: 'The name of the metric to filter against.'
type: 'string'
inlineJs: true
required: false
order: 3
Dimensions:
label: 'Dimensions'
description: 'Optional; a list of Dimension key/values to filter against.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
order: 4
Statistics:
label: 'Statistics'
description: 'Specifies one or more Statistics to return.'
type: 'string[]'
inlineJs: true
options:
SampleCount:
value: 'SampleCount'
Average:
value: 'Average'
Sum:
value: 'Sum'
Minimum:
value: 'Minimum'
Maximum:
value: 'Maximum'
required: true
order: 5
Period:
label: 'Period'
description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.'
type: 'integer'
default: 60
required: false
placeholder: 'Number of Seconds'
order: 6
StartTime:
label: 'Start Time'
description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 8
EndTime:
label: 'End Time'
description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 9
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 15
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 16
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 17
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
cyclotronData:
value: 'cyclotronData'
label: 'CyclotronData'
icon: 'fa-cloud-download'
message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.'
properties:
key:
label: 'Bucket Key'
description: 'Specifies the unique key to a Cyclotron Data bucket.'
placeholder: 'Bucket Key'
type: 'string'
inlineJs: true
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
url:
label: 'Cyclotron Server'
description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
elasticsearch:
value: 'elasticsearch'
label: 'Elasticsearch'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Elasticsearch endpoint.'
placeholder: 'Elasticsearch URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
index:
label: 'Index'
description: 'Specifies the name of the Elasticsearch index to query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 12
method:
label: 'API Name'
description: 'Indicates which Elasticsearch API method to use; defaults to "_search".'
type: 'string'
inlineJs: true
inlineEncryption: true
defaultHidden: true
default: '_search'
required: false
order: 13
request:
label: 'Elasticsearch Request'
description: 'Specifies the Elasticsearch JSON request.'
placeholder: 'JSON'
type: 'editor'
editorMode: 'json'
inlineJs: true
inlineEncryption: true
required: true
order: 14
responseAdapter:
label: 'Response Adapter'
description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".'
type: 'string'
default: 'auto'
inlineJs: true
options:
'Auto':
value: 'auto'
'Hits':
value: 'hits'
'Aggregations':
value: 'aggregations'
'Raw':
value: 'raw'
required: false
order: 15
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 20
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 21
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 22
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 23
graphite:
value: 'graphite'
label: 'Graphite'
icon: 'fa-cloud-download'
message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.'
properties:
url:
label: 'URL'
description: 'The Graphite server'
placeholder: 'Graphite Server URL or IP'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
targets:
label: 'Targets'
description: 'One or more Graphite metrics, optionally with metrics.'
type: 'string[]'
inlineJs: true
inlineEncryption: true
required: true
order: 11
from:
label: 'From'
description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).'
placeholder: 'Start Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
until:
label: 'Until'
description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).'
placeholder: 'End Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
influxdb:
value: 'influxdb'
label: 'InfluxDB'
icon: 'fa-cloud-download'
message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open-source time series database built from the ground up to handle high write and query loads.'
properties:
url:
label: 'URL'
description: 'The InfluxDB server'
placeholder: 'InfluxDB Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
database:
label: 'Database'
description: 'Specifies the target InfluxDB database for the query.'
placeholder: 'Database'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
required: false
order: 11
query:
label: 'Query'
description: 'An InfluxQL query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
precision:
label: 'Precision'
description: 'Overrides the default timestamp precision.'
type: 'string'
default: 'ms'
inlineJs: true
options:
h:
value: 'h'
m:
value: 'm'
s:
value: 's'
ms:
value: 'ms'
u:
value: 'u'
ns:
value: 'ns'
order: 11
username:
label: 'Username'
description: 'Optional; username for authentication, if enabled.'
type: 'string'
inlineJs: true
inlineEncryption: true
order: 15
password:
label: 'Password'
description: 'Optional; password for authentication, if enabled.'
type: 'string'
inputType: 'password'
inlineJs: true
inlineEncryption: true
order: 16
insecureSsl:
label: 'Insecure SSL'
description: 'If true, disables SSL certificate validation; useful for self-signed certificates.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 18
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
javascript:
value: 'javascript'
label: 'JavaScript'
icon: 'fa-cloud-download'
message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.'
properties:
processor:
label: 'Processor'
description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 12
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 13
json:
value: 'json'
label: 'JSON'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the JSON Web Service URL.'
placeholder: 'Web Service URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
queryParameters:
label: 'Query Parameters'
description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.'
type: 'hash'
required: false
inlineJsKey: true
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 12
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 17
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
mock:
value: 'mock'
label: 'Mock'
icon: 'fa-cloud-download'
message: 'The Mock Data Source generates sample data for testing a dashboard.'
properties:
format:
label: 'Format'
description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".'
type: 'string'
required: false
default: 'object'
options:
object:
value: 'object'
pie:
value: 'pie'
large:
value: 'large'
ducati:
value: 'ducati'
order: 10
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
prometheus:
value: 'prometheus'
label: 'Prometheus'
icon: 'fa-cloud-download'
message: '<a href="https://prometheus.io/" target="_blank">Prometheus</a> is an open-source systems monitoring and alerting toolkit.'
properties:
url:
label: 'URL'
description: 'The Prometheus server'
placeholder: 'Prometheus Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
query:
label: 'Query'
description: 'A Prometheus expression query string.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
start:
label: 'Start'
description: 'Specifies the start time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults to 24 hours ago.'
placeholder: 'Start Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
end:
label: 'End'
description: 'Specifies the end time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults now.'
placeholder: 'End Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
step:
label: 'Step'
description: 'Query resolution step width (e.g. 10s, 1m, 4h, etc). If omitted, defaults to 1m.'
placeholder: 'Step width (10s, 1m, 4h, etc)'
type: 'string'
default: '1m'
inlineJs: true
order: 14
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
splunk:
value: 'splunk'
label: 'Splunk'
icon: 'fa-cloud-download'
properties:
query:
label: 'Query'
description: 'Splunk query'
placeholder: 'Splunk query'
type: 'textarea'
required: true
order: 10
earliest:
label: 'Earliest Time'
description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Earliest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 11
latest:
label: 'Latest Time'
description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Latest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
username:
label: 'Username'
description: 'Username to authenticate with Splunk'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
order: 13
password:
label: 'Password'
description: 'Password to authenticate with Splunk'
type: 'string'
inputType: 'password'
required: true
inlineJs: true
inlineEncryption: true
order: 14
host:
label: 'Host'
description: 'Splunk API host name'
placeholder: 'Splunk API host name'
type: 'string'
inputType: 'string'
required: false
defaultHidden: false
order: 15
url:
label: 'URL'
description: 'The Splunk API Search URL'
placeholder: 'Splunk API Search URL'
type: 'url'
inlineJs: true
inlineEncryption: true
default: 'https://#{host}:8089/services/search/jobs/export'
defaultHidden: true
required: false
order: 16
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 17
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 18
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 20
parameters:
label: 'Parameters'
description: 'A list of Parameters that can be used to configure the Dashboard.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The name used to set or reference this Parameter.'
type: 'string'
required: true
placeholder: 'Parameter Name'
order: 0
defaultValue:
label: 'Default Value'
description: 'The value used if the Parameter is not set when opening the Dashboard.'
type: 'string'
placeholder: 'Default Value'
required: false
inlineJs: true
order: 1
showInUrl:
label: 'Show in URL'
description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.'
type: 'boolean'
default: true
required: false
order: 2
editInHeader:
label: 'Editable in Header'
description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).'
type: 'boolean'
default: false
required: false
order: 3
persistent:
label: 'Persistent'
description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.'
type: 'boolean'
default: false
required: false
order: 4
changeEvent:
label: 'Change Event'
description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 10
editing:
label: 'Editing'
description: 'Configuration for how this Parameter can be edited in the Dashboard.'
type: 'propertyset'
required: false
default: {}
defaultHidden: true
order: 15
properties:
displayName:
label: 'Display Name'
description: 'The display name used for this Parameter.'
type: 'string'
required: false
placeholder: 'Display Name'
order: 1
editorType:
label: 'Editor Type'
description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).'
type: 'string'
required: false
default: 'textbox'
order: 2
options:
textbox:
value: 'textbox'
dropdown:
value: 'dropdown'
links:
value: 'links'
checkbox:
value: 'checkbox'
datetime:
value: 'datetime'
date:
value: 'date'
time:
value: 'time'
dataSource:
label: 'Data Source'
description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 4
datetimeFormat:
label: 'Date/Time Format'
description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.'
type: 'string'
required: false
placeholder: 'Format'
defaultHidden: true
order: 5
sample:
name: ''
defaultValue: ''
scripts:
label: 'Scripts'
description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the script'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a JavaScript file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'JavaScript file URL'
required: false
order: 1
text:
label: 'JavaScript Text'
description: 'Inline JavaScript to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'javascript'
placeholder: 'Inline JavaScript'
required: false
order: 2
singleLoad:
label: 'Single-Load'
description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.'
type: 'boolean'
required: false
default: false
order: 3
sample:
text: ''
styles:
label: 'Styles'
description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the style'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a CSS file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'CSS file URL'
required: false
order: 0
text:
label: 'CSS Text'
description: 'Inline CSS to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'css'
placeholder: 'Inline CSS'
required: false
order: 1
sample:
text: ''
controls:
# Controls how long to display the controls before hiding.
duration: 1000
# Controls how close the mouse must be before the controls appear
hitPaddingX: 60
hitPaddingY: 50
sample:
name: ''
sidebar:
showDashboardSidebar: true
pages: []
# Dashboard Sidebar
dashboardSidebar:
footer:
logos: [{
title: 'Cyclotron'
src: '/img/favicon32.png'
href: '/'
}]
# List of help pages
help: [
{
name: 'About'
path: '/partials/help/about.html'
tags: ['about', 'terminology', 'features']
children: [
{
name: 'Quick Start'
path: '/partials/help/quickstart.html'
tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets']
}
{
name: 'JSON'
path: '/partials/help/json.html'
tags: ['json']
}
{
name: 'Examples'
path: '/partials/help/examples.html'
tags: ['examples', 'cyclotron-examples']
}
{
name: 'Browser Compatibility'
path: '/partials/help/browserCompat.html'
tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck']
}
{
name: 'Permissions'
path: '/partials/help/permissions.html'
tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api']
}
{
name: 'Analytics'
path: '/partials/help/analytics.html'
tags: ['analytics', 'pageviews', 'visits', 'metrics']
}
{
name: 'Encrypted Strings'
path: '/partials/help/encryptedStrings.html'
tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt']
}
{
name: 'JavaScript API'
path: '/partials/help/javascriptApi.html'
tags: ['javascript', 'api', 'scripting']
}
{
name: 'CyclotronData'
path: '/partials/help/cyclotrondata.html'
tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api']
}
{
name: '3rd Party Libraries'
path: '/partials/help/3rdparty.html'
tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js']
}
{
name: 'Hotkeys'
path: '/partials/help/hotkeys.html'
tags: ['hotkeys', 'keys', 'shortcuts']
}
{
name: 'API'
path: '/partials/help/api.html'
tags: ['api', 'rest', 'service']
}
]
}
{
name: 'Dashboards'
path: '/partials/help/dashboards.html'
tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters']
children: [
{
name: 'Pages'
path: '/partials/help/pages.html'
tags: ['pages', 'widgets']
}
{
name: 'Layout'
path: '/partials/help/layout.html'
tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute']
}
{
name: 'Parameters'
path: '/partials/help/parameters.html'
tags: ['parameters']
}
{
name: 'Scripts'
path: '/partials/help/scripts.html'
tags: ['scripts', 'javascript']
}
{
name: 'Styles'
path: '/partials/help/styles.html'
tags: ['styles', 'css']
}
]
}
{
name: 'Data Sources'
path: '/partials/help/dataSources.html'
tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor']
}
{
name: 'Widgets'
path: '/partials/help/widgets.html'
tags: ['widgets']
}
]
# Formats supported for Dashboard Export
exportFormats: [{
label: 'PDF',
value: 'pdf'
}]
# Page settings
page:
sample:
frequency: 1
layout:
gridColumns: 2
gridRows: 2
widgets: []
# Widget settings
widgets:
annotationChart:
name: 'annotationChart'
label: 'Annotation Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
xAxis:
label: 'X-Axis'
description: 'Configuration of the X-axis.'
type: 'propertyset'
required: true
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source used for the x-axis.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
format:
label: 'Format'
description: 'Specifies which format the incoming datetime data is in.'
type: 'string'
options:
date:
value: 'date'
epoch:
value: 'epoch'
epochmillis:
value: 'epochmillis'
string:
value: 'string'
order: 2
formatString:
label: 'Format String'
description: 'Used with the String format to specify how the string should be parsed.'
type: 'string'
order: 3
order: 11
series:
label: 'Series'
singleLabel: 'series'
description: 'One or more series to display in the annotation chart.'
type: 'propertyset[]'
required: true
default: []
order: 12
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source to use as the y-axis value for this series.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
label:
label: 'Label'
description: 'Display label for the series; if omitted, the column name will be used.'
placeholder: 'Label'
inlineJs: true
type: 'string'
order: 2
annotationTitleColumn:
label: 'Annotation Title Column Name'
description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 3
annotationTextColumn:
label: 'Annotation Text Column Name'
description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 4
secondaryAxis:
label: 'Secondary Axis'
description: 'If true, places the series on a second axis on the left of the chart.'
inlineJs: true
type: 'boolean'
order: 5
options:
label: 'Options'
description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.'
type: 'propertyset'
required: false
inlineJs: true
properties:
allValuesSuffix:
label: 'All Values Suffix'
description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
defaultHidden: true
annotationsWidth:
label: 'Annotations Width'
description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.'
type: 'integer'
inlineJs: true
defaultHidden: true
displayAnnotations:
label: 'Display Annotations'
description: 'Controls whether annotations are displayed along with the chart.'
type: 'boolean'
inlineJs: true
default: true
defaultHidden: true
displayAnnotationsFilter:
label: 'Display Annotations Filter'
description: 'If set to true, the chart will display a filter control to filter annotations.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayDateBarSeparator:
label: 'Display Date Bar Separator'
description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayLegendDots:
label: 'Display Legend Dots'
description: 'If set to true, the chart will display dots next to the values in the legend text.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayLegendValues:
label: 'Display Legend Values'
description: 'If set to true, the chart will display the highlighted values in the legend.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayRangeSelector:
label: 'Display Range Selector'
description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayZoomButtons:
label: 'Display Zoom Buttons'
description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).'
type: 'boolean'
inlineJs: true
defaultHidden: true
fill:
label: 'Fill'
description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.'
type: 'integer'
inlineJs: true
defaultHidden: true
focusTarget:
label: 'Focus Target'
description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".'
type: 'string'
inlineJs: true
defaultHidden: true
default: 'category'
options:
datum:
value: 'datum'
category:
value: 'category'
legendPosition:
label: 'Legend Position'
description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
sameRow:
value: 'sameRow'
newRow:
value: 'newRow'
max:
label: 'Maximum'
description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
min:
label: 'Minimum'
description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
scaleFormat:
label: 'Scale Format'
description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.'
placeholder: 'Format'
type: 'string'
inlineJs: true
defaultHidden: true
scaleType:
label: 'Scale Type'
description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
maximized:
value: 'maximized'
fixed:
value: 'fixed'
allmaximized:
value: 'allmaximized'
allfixed:
value: 'allfixed'
thickness:
label: 'Thickness'
description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.'
placeholder: 'Thickness'
type: 'integer'
inlineJs: true
defaultHidden: true
zoomStartTime:
label: 'Zoom Start Time'
description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
zoomEndTime:
label: 'Zoom End Time'
description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
order: 13
annotationEditing:
label: 'Built-In Annotation Editing'
description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.'
type: 'boolean'
required: false
default: false
order: 13
annotationKey:
label: 'Built-In Annotation Key'
description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 14
events:
label: 'Events'
description: 'Optional event handlers for various events.'
type: 'propertyset'
required: false
defaultHidden: true
order: 15
properties:
rangechange:
label: 'Range Change Event'
description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 1
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 20
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 20
# Common options
options:
displayAnnotations: true
# Undocumented "chart" options
chart:
focusTarget: 'category'
sample: ->
# Generate new Annotation Chart Widget
{
annotationKey: uuid.v4()
}
# Theme-specific options
themes:
dark:
options:
dbackgroundColor: '#222222'
darkmetro:
options:
dbackgroundColor: '#202020'
chart:
name: 'chart'
label: 'Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
drilldownDataSource:
label: 'Drilldown Data Source'
description: 'The name of the Data Source providing drilldown data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: false
defaultHidden: true
options: datasourceOptions
order: 11
highchart:
label: 'Highchart Definition'
description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.'
type: 'json'
inlineJs: true
required: true
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 14
addShiftPoints:
label: 'Add/Shift Points'
description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.'
type: 'boolean'
default: false
required: false
order: 15
sample:
highchart:
series: [{
x: ''
y: ''
}
]
xAxis: [{
type: 'linear'
}
]
yAxis: [{
title:
text: 'Values'
}
]
themes:
light:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
drilldown:
activeAxisLabelStyle:
color: '#333'
textDecoration: 'none'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
gto:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
dark:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
dark2:
colors: [
'#2095F0' #Blue
'#FF9A13' #Orange
'#FFFF13' #Yellow
'#A61DF1' #Purple
'#28F712' #Green
'#FE131E' #Red
'#D1D1D0' #Offwhite
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
dataLabels:
style:
color: '#999'
textShadow: false
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
darkmetro:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
charcoal:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
clock:
name: 'clock'
label: 'Clock'
icon: 'fa-clock-o'
properties:
format:
label: 'Format'
description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats'
type: 'string'
default: 'dddd, MMMM Do YYYY, h:mm:ss a'
required: false
order: 10
timezone:
label: 'Time Zone'
description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone'
required: false
type: 'string'
order: 11
header:
name: 'header'
label: 'Header'
icon: 'fa-header'
properties:
headerTitle:
label: 'Header Title'
description: 'Contains properties for displaying a title in the header.'
type: 'propertyset'
order: 10
properties:
showTitle:
label: 'Show Title'
description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 1
showPageName:
label: 'Show Page Name'
description: 'Determines whether the current page name will be shown as part of the title.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 2
pageNameSeparator:
label: 'Page Name Separator'
description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.'
type: 'string'
required: false
default: ''
inlineJs: true
defaultHidden: true
order: 3
titleSize:
label: 'Title Size'
description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 5
logoUrl:
label: 'Logo URL'
description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.'
type: 'string'
required: false
inlineJs: true
order: 10
logoSize:
label: 'Logo Size'
description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 11
link:
label: 'Link'
description: 'If set, makes the Logo and Title a link to this URL.'
type: 'string'
required: false
inlineJs: true
order: 20
parameters:
label: 'Parameters'
description: 'Contains properties for displaying Dashboard Parameters in the header.'
type: 'propertyset'
order: 20
properties:
showParameters:
label: 'Show Parameters'
description: 'Determines whether Parameters will be shown.'
type: 'boolean'
default: false
required: false
inlineJs: true
order: 1
showUpdateButton:
label: 'Show Update Button'
description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.'
type: 'boolean'
default: false
required: false
order: 2
updateButtonLabel:
label: 'Update Button Label'
description: 'Customizes the label for the Update button, if shown.'
type: 'string'
default: 'Update'
defaultHidden: true
required: false
order: 2
updateEvent:
label: 'Update Button Click Event'
description: 'This event occurs when the Update button is clicked, if shown.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 10
parametersIncluded:
label: 'Included Parameters'
description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.'
type: 'string[]'
required: false
defaultHidden: true
order: 11
customHtml:
label: 'HTML Content'
description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.'
type: 'editor'
editorMode: 'html'
required: false
inlineJs: true
order: 30
html:
name: 'html'
label: 'HTML'
icon: 'fa-html5'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
html:
label: 'HTML'
description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 11
preHtml:
label: 'Pre-HTML'
description: 'Optional, contains HTML markup which is displayed before the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 12
postHtml:
label: 'Post-HTML'
description: 'Optional, contains HTML markup which is displayed after the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 15
iframe:
name: 'iframe'
label: 'iFrame'
icon: 'fa-desktop'
properties:
url:
label: 'Url'
description: 'Specifies the URL to be loaded within the Widget.'
type: 'string'
placeholder: 'Url'
required: true
default: 'http://www.expedia.com'
order: 10
refresh:
label: 'Refresh'
description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 11
image:
name: 'image'
label: 'Image'
icon: 'fa-image-o'
properties:
images:
label: 'Images'
singleLabel: 'Image'
description: 'One or more Images to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 10
properties:
url:
label: 'URL'
description: 'URL to the image to be displayed.'
placeholder: 'Url'
inlineJs: true
required: true
type: 'string'
order: 1
link:
label: 'Link'
description: 'Optional, specifies a URL that will be opened if the image is clicked on.'
placeholder: 'URL'
type: 'url'
inlineJs: true
required: false
order: 13
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the image.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 2
backgroundSize:
label: 'Background-Size'
description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
options:
auto:
value: 'auto'
contain:
value: 'contain'
cover:
value: 'cover'
'100%':
value: '100%'
order: 3
backgroundPosition:
label: 'Background Position'
description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'center'
defaultHidden: true
options:
center:
value: 'center'
top:
value: 'top'
bottom:
value: 'bottom'
left:
value: 'left'
right:
value: 'right'
order: 4
backgroundColor:
label: 'Background Color'
description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
backgroundRepeat:
label: 'Background Repeat'
description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'no-repeat'
defaultHidden: true
options:
'no-repeat':
value: 'no-repeat'
'repeat':
value: 'repeat'
'repeat-x':
value: 'repeat-x'
'repeat-y':
value: 'repeat-y'
'space':
value: 'space'
'round':
value: 'round'
order: 6
filters:
label: 'Filters'
description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 7
duration:
label: 'Auto-Rotate Duration'
description: 'Optional number of seconds; enables rotating among a set of images periodically.'
placeholder: 'Seconds'
type: 'integer'
default: 0
required: false
order: 11
javascript:
name: 'javascript'
label: 'JavaScript'
icon: 'fa-cogs'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
functionName:
label: 'Function Name'
description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot'
placeholder: 'Function Name'
type: 'string'
required: true
order: 11
refresh:
label: 'Refresh'
description: 'Optional; enables re-invoking the javascript object periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 14
json:
name: 'json',
label: 'JSON',
icon: 'fa-cog',
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
linkedWidget:
name: 'linkedWidget'
label: 'Linked Widget'
icon: 'fa-link'
properties:
linkedWidget:
label: 'Linked Widget'
description: 'Selects another Widget in this Dashboard to link.'
type: 'string'
required: true
options: linkedWidgetOptions
order: 10
number:
name: 'number'
label: 'Number'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
numbers:
label: 'Numbers'
singleLabel: 'number'
description: 'One or more Numbers to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 11
properties:
number:
label: 'Number'
description: 'Number value or expression.'
placeholder: 'Value'
inlineJs: true
required: false
type: 'string'
order: 1
prefix:
label: 'Prefix'
description: 'Optional; specifies a prefix to append to the number.'
placeholder: 'Prefix'
type: 'string'
inlineJs: true
order: 2
suffix:
label: 'Suffix'
description: 'Optional; specifies a suffix to append to the number.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
order: 3
color:
label: 'Color'
description: 'Sets the color of the number.'
placeholder: 'Color'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 4
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the number.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
icon:
label: 'Icon'
description: 'Optional Font Awesome icon class to be displayed with the number.'
placeholder: 'Icon Class'
inlineJs: true
type: 'string'
defaultHidden: true
order: 6
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
order: 7
iconTooltip:
label: 'IconTooltip'
description: 'Sets the tooltip of the icon.'
placeholder: 'Icon Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 8
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 9
orientation:
label: 'Orientation'
description: 'Controls the direction in which the numbers are arranged.'
type: 'string'
required: false
default: 'vertical'
options:
vertical:
value: 'vertical'
horizontal:
value: 'horizontal'
order: 12
autoSize:
label: 'Auto-Size Numbers'
description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.'
type: 'boolean'
required: false
default: true
order: 13
link:
label: 'Link'
description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.'
placeholder: 'URL'
type: 'url'
required: false
order: 14
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
qrcode:
name: 'qrcode'
label: 'QRcode'
icon: 'fa-cogs'
properties:
text:
label: 'Text'
description: 'Text content of the generated QR code.'
placeholder: 'QR Code Contents'
type: 'string'
required: false
order: 10
maxSize:
label: 'Max Size'
description: 'Maximum height/width of the QR code.'
type: 'integer'
required: false
order: 11
useUrl:
label: 'Use URL'
description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.'
type: 'boolean'
default: false
required: false
order: 12
dataSource:
label: 'Data Source'
description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
defaultHidden: true
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
defaultHidden: true
order: 15
colorDark:
label: 'Dark Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#000000'
required: false
defaultHidden: true
order: 16
colorLight:
label: 'Light Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#ffffff'
required: false
defaultHidden: true
order: 17
sample:
text: 'hello'
stoplight:
name: 'stoplight'
label: 'Stoplight'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
rules:
label: 'Rules'
description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled'
type: 'propertyset'
required: true
order: 11
properties:
green:
label: 'Green'
description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 3
yellow:
label: 'Yellow'
description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 2
red:
label: 'Red'
description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 1
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the stoplight.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 12
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
table:
name: 'table'
label: 'Table'
icon: 'fa-table'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
columns:
label: 'Columns'
singleLabel: 'column'
description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.'
type: 'propertyset[]'
inlineJs: true
properties:
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
order: 1
label:
label: 'Label'
description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
order: 2
text:
label: 'Text'
description: 'Overrides the text in the cell using this value as an expression.'
type: 'string'
inlineJs: true
defaultHidden: true
order: 3
tooltip:
label: 'Tooltip'
description: 'Optionally specifies a tooltip to display for each cell in the column.'
type: 'string'
inlineJs: true
defaultHidden: true
headerTooltip:
label: 'Header Tooltip'
description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
defaultHidden: true
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
link:
label: 'Link'
description: 'If provided, the cell text will be made into a link rather than plain text.'
type: 'url'
inlineJs: true
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, links will open in a new browser window; this is the default.'
type: 'boolean'
default: true
defaultHidden: true
numeralformat:
label: 'Numeral Format'
description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.'
type: 'string'
inlineJs: true
defaultHidden: true
image:
label: 'Image'
description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.'
type: 'url'
inlineJs: true
defaultHidden: true
imageHeight:
label: 'Image Height'
description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.'
type: 'string'
inlineJs: true
defaultHidden: true
icon:
label: 'Icon'
description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.'
type: 'string'
inlineJs: true
defaultHidden: true
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
border:
label: 'Border'
description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.'
type: 'string'
inlineJs: true
defaultHidden: true
group:
label: 'Column Group'
description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.'
type: 'string'
inlineJs: true
defaultHidden: true
groupRows:
label: 'Group Rows'
description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.'
type: 'boolean'
default: false
defaultHidden: true
columnSortFunction:
label: 'Column Sort Function'
description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".'
type: 'string'
inlineJs: true
defaultHidden: true
columnsIgnored:
label: 'Columns Ignored'
description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.'
type: 'string[]'
required: false
inlineJs: false
defaultHidden: true
order: 10
sample:
name: ''
rules:
label: 'Rules'
singleLabel: 'rule'
description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.'
type: 'propertyset[]'
inlineJs: true
properties:
rule:
label: 'Rule'
description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.'
type: 'string'
required: true
inlineJs: true
order: 1
columns:
label: 'Columns Affected'
description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.'
type: 'string[]'
required: false
order: 2
columnsIgnored:
label: 'Columns Ignored'
description: 'Optionally specifies an array of column names that the rule does NOT apply to.'
type: 'string[]'
required: false
order: 3
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
defaultHidden: true
'font-weight':
label: 'Font-Weight (CSS)'
description: 'CSS setting for `font-weight`'
type: 'string'
inlineJs: true
defaultHidden: true
color:
label: 'Color (CSS)'
description: 'CSS setting for `color`'
type: 'string'
inlineJs: true
defaultHidden: true
'background-color':
label: 'Background Color (CSS)'
description: 'CSS setting for `background-color`'
type: 'string'
inlineJs: true
defaultHidden: true
order: 11
sample:
rule: 'true'
freezeHeaders:
label: 'Freeze Headers'
description: 'Enables frozen headers at the top of the widget when scrolling'
type: 'boolean'
default: false
required: false
order: 12
omitHeaders:
label: 'Omit Headers'
description: 'Disables the table header row'
type: 'boolean'
default: false
required: false
order: 13
enableSort:
label: 'Enable Sort'
description: 'Enable or disable user sort controls'
type: 'boolean'
default: true
required: false
order: 14
rowHeight:
label: 'Minimum Row Height'
description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.'
type: 'integer'
required: false
order: 15
pagination:
label: 'Pagination'
description: 'Controls pagination of the Table.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
enabled:
label: 'Enable Pagination'
description: 'Enables or disables pagination for this Table Widget.'
type: 'boolean'
default: false
required: false
order: 1
autoItemsPerPage:
label: 'Auto Items Per Page'
description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.'
type: 'boolean'
default: true
required: false
order: 2
itemsPerPage:
label: 'Items Per Page'
description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.'
type: 'integer'
required: false
order: 3
belowPagerMessage:
label: 'Below Pager Message'
description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.'
type: 'string'
required: false
order: 4
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 17
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 18
sortFunction:
label: 'Sort Function'
description: 'Optional, specifies an alternative function to the default sort implementation.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
onSort:
label: 'Sort Event'
description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 20
tableau:
name: 'tableau'
label: 'Tableau'
icon: 'fa-cog'
properties:
params:
label: 'Parameters'
description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.'
type: 'hash'
required: true
editorMode: 'json'
order: 10
treemap:
name: 'treemap'
label: 'Treemap'
icon: 'fa-tree'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
labelProperty:
label: 'Label Property'
description: 'The name of the property to use as the label of each item.'
type: 'string'
inlineJs: true
required: false
default: 'name'
defaultHidden: true
order: 11
valueProperty:
label: 'Value Property'
description: 'The name of the property to use to calculate the size of each item.'
type: 'string'
inlineJs: true
required: false
default: 'value'
defaultHidden: true
order: 12
valueDescription:
label: 'Value Description'
description: 'A short description of the property used to calculate the size of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 13
valueFormat:
label: 'Value Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
order: 14
colorProperty:
label: 'Color Property'
description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.'
type: 'string'
inlineJs: true
required: false
default: 'color'
order: 15
colorDescription:
label: 'Color Description'
description: 'A short description of the property used to calculate the color of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 16
colorFormat:
label: 'Color Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
large:
value: '0a'
order: 17
colorStops:
label: 'Color Stops'
singleLabel: 'color'
description: 'Specifies a list of color stops used to build a gradient.'
type: 'propertyset[]'
inlineJs: true
properties:
value:
label: 'Value'
description: 'The numerical value assigned to this color stop.'
type: 'number'
required: true
inlineJs: true
order: 1
color:
label: 'Color'
description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.'
type: 'string'
required: false
inlineJs: true
order: 2
order: 18
showLegend:
label: 'Show Legend'
description: 'Enables or disables the color legend.'
type: 'boolean'
default: true
required: false
order: 19
legendHeight:
label: 'Legend Height'
description: 'Specifies the height of the legend in pixels.'
type: 'number'
default: 30
required: false
defaultHidden: true
order: 20
youtube:
name: 'youtube'
label: 'YouTube'
icon: 'fa-youtube'
properties:
videoId:
label: 'Video / Playlist ID'
description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.'
type: 'string'
inlineJs: true
placeholder: 'ID'
required: true
order: 10
autoplay:
label: 'Auto-Play'
description: 'If true, automatically plays the video when the Widget is loaded.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 13
loop:
label: 'Loop'
description: 'If true, automatically loops the video when it completes.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 14
enableKeyboard:
label: 'Enable Keyboard'
description: 'If true, enables keyboard controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 15
enableControls:
label: 'Enable Controls'
description: 'If true, enables on-screen video controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 16
showAnnotations:
label: 'Show Annotations'
description: 'If true, displays available annotations over the video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 17
showRelated:
label: 'Show Related'
description: 'If true, displays related videos at the end of this video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 18
}
# Copy Theme options to inherited locations
exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
# Copy Style options to inherited locations
exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options
# Table Widget: Column properties duplicated in Rules:
tableProperties = exports.widgets.table.properties
_.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label')
# Copy some chart themes
exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light
# Populate Help tags with properties
helpDashboards = _.find(exports.help, { name: 'Dashboards' })
helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name
helpDataSources = _.find(exports.help, { name: 'Data Sources' })
helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name
helpWidgets = _.find(exports.help, { name: 'Widgets' })
helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name
propertyMapHelper = (value, name) ->
v = _.cloneDeep value
v.name = name
return v
# Add Widget and Data Source help pages
helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) ->
{
name: dataSource.label || dataSource.value
path: '/partials/help/datasources/' + dataSource.value + '.html'
tags: _.map dataSource.properties, propertyMapHelper
}
helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) ->
{
name: widget.label || widget.name
path: '/widgets/' + widget.name + '/help.html'
tags: _.map widget.properties, propertyMapHelper
}
return exports
| 10245 | ###
# Copyright (c) 2013-2018 the original author or authors.
#
# Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
#
# 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.
###
# Common Config File - all default or shared configs
cyclotronServices.factory 'commonConfigService', ->
linkedWidgetOptions = (dashboard) ->
linkedWidgets = {}
_.each dashboard.pages, (page, pageIndex) ->
_.each page.widgets, (widget, widgetIndex) ->
return if widget.widget == 'linkedWidget'
widgetName = _.titleCase(widget.widget)
if widget.name?.length > 0 or widget.title?.length > 0
widgetName += ': ' + (widget.name || widget.title)
linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex }
linkedWidgets
datasourceOptions = (dashboard) ->
dataSources = {}
_.each dashboard.dataSources, (dataSource) ->
dataSources[dataSource.name] = { value: dataSource.name }
dataSources
exports = {
version: '2.0.2'
logging:
enableDebug: false
authentication:
enable: false
loginMessage: 'Please login using your LDAP username and password.'
analytics:
enable: false
newUser:
enableMessage: true
welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.'
iconClass: 'fa-info'
autoDecayDuration: 1
# Dashboard settings
dashboard:
properties:
name:
label: 'Name'
description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.'
placeholder: 'Dashboard Name'
type: 'string'
required: true
order: 0
displayName:
label: 'Display Name'
description: 'Display Name; this is displayed in the browser title bar or the Header Widget.'
placeholder: 'Display Name'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 1
description:
label: 'Description'
description: 'A short summary of the Dashboard\'s purpose or capabilities.'
placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.'
type: 'string'
required: false
order: 2
theme:
label: 'Theme'
description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.'
type: 'string'
default: 'dark'
required: false
options:
charcoal:
label: 'Charcoal'
value: 'charcoal'
dashboardBackgroundColor: '#1E2328'
aceTheme: 'solarized_dark'
dark:
label: 'Dark'
value: 'dark'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
darkmetro:
label: 'Dark Metro'
value: 'darkmetro'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
gto:
label: 'GTO'
value: 'gto'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
light:
label: 'Light'
value: 'light'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
lightborderless:
label: 'Light (borderless)'
value: 'lightborderless'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
dark2:
label: 'Very Dark'
value: 'dark2'
dashboardBackgroundColor: 'black'
aceTheme: 'monokai'
order: 5
themeVariant:
label: 'Theme Variant'
description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.'
type: 'string'
default: 'default'
required: false
defaultHidden: true
options:
default:
value: 'default'
transparent:
value: 'transparent'
'transparent-unpadded':
value: 'transparent-unpadded'
order: 6
style:
label: 'Style'
description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.'
type: 'string'
default: 'normal'
required: false
options:
normal:
value: 'normal'
fullscreen:
value: 'fullscreen'
defaultHidden: true
order: 7
autoRotate:
label: 'Auto-Rotate'
description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 10
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.'
type: 'integer'
placeholder: 'Seconds per page'
default: 60
required: false
defaultHidden: true
order: 11
preload:
label: 'Pre-Load Time (seconds)'
description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.'
placeholder: 'Seconds'
type: 'integer'
default: 0.050
required: false
defaultHidden: true
order: 12
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, all links will open in a new browser window; this is the default.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showDashboardControls:
label: 'Show Dashboard Controls'
description: 'If false, hides the default Dashboard controls (rotation, export, etc)'
type: 'boolean'
required: false
default: true
defaultHidden: true
sidebar:
label: 'Sidebar'
description: ''
type: 'propertyset'
default: {}
defaultHidden: true
properties:
showDashboardSidebar:
label: 'Show Dashboard Sidebar'
description: 'If false, hides the default Dashboard Sidebar.'
type: 'boolean'
required: false
default: false
order: 10
showDashboardTitle:
label: 'Include Dashboard Title'
description: 'Enables a section of the sidebar for the Dashboard title.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 11
showToolbar:
label: 'Include Toolbar'
description: 'Enables a toolbar in the sidebar.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 12
showHideWidgets:
label: 'Include Show/Hide Widgets'
description: 'Enables a section of the sidebar for overriding the visibility of Widgets.'
type: 'boolean'
required: false
default: false
defaultHidden: true
order: 13
sidebarContent:
label: 'Custom Sidebar Sections'
singleLabel: 'Section'
description: 'One or more sections of content to display in the Sidebar.'
type: 'propertyset[]'
default: []
order: 15
properties:
heading:
label: 'Heading'
description: 'Heading for the Sidebar section.'
type: 'string'
inlineJs: true
order: 1
html:
label: 'HTML Content'
description: 'HTML Content to display.'
placeholder: 'Value'
type: 'editor'
editorMode: 'html'
inlineJs: true
order: 2
pages:
label: 'Pages'
description: 'The list of Page definitions which compose the Dashboard.'
type: 'pages'
default: []
required: true
properties:
name:
label: 'Name'
description: 'Name of this page; used in the browser title and URL.'
placeholder: 'Page Name'
type: 'string'
required: false
order: 0
layout:
label: 'Layout'
description: 'Contains properties for configuring the Page layout and dimensions.'
type: 'propertyset'
default: {}
required: false
properties:
gridColumns:
label: 'Grid Columns'
description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.'
type: 'integer'
required: false
order: 0
gridRows:
label: 'Grid Rows'
description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.'
type: 'integer'
required: false
order: 1
gridWidthAdjustment:
label: 'Grid Page Width Adjustment'
description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).'
type: 'integer'
default: 0
required: false
defaultHidden: true
order: 2
gridHeightAdjustment:
label: 'Grid Page Height Adjustment'
description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.'
type: 'integer'
default: 0
required: false
order: 3
gutter:
label: 'Gutter'
description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 5
borderWidth:
label: 'Border Width'
description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.'
type: 'integer'
default: null
required: false
defaultHidden: true
order: 6
margin:
label: 'Margin'
description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 7
scrolling:
label: 'Scrolling Enabled'
description: 'Enables vertical scrolling of the page to display content longer than the current browser size.'
type: 'boolean'
default: true
required: false
defaultHidden: true
order: 8
order: 2
widgets:
label: 'Widgets'
description: 'An array of one or more Widgets to display on the page'
type: 'propertyset[]'
subState: 'edit.widget'
headingfn: 'getWidgetName'
default: []
required: true
properties:
widget:
label: 'Type'
description: 'The type of Widget to be rendered.'
type: 'string'
required: true
name:
label: 'Name'
description: 'Internal Widget name, displayed in the Dashboard Editor.'
placeholder: 'Name'
type: 'string'
required: false
defaultHidden: true
inlineJs: false
order: 1
title:
label: 'Title'
description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.'
placeholder: 'Widget Title'
type: 'string'
required: false
inlineJs: true
order: 2
gridHeight:
label: 'Grid Rows'
description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.'
placeholder: 'Number of Rows'
type: 'integer'
default: '1'
required: false
order: 100
gridWidth:
label: 'Grid Columns'
description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.'
placeholder: 'Number of Columns'
type: 'integer'
default: '1'
required: false
order: 101
height:
label: 'Height'
description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Height'
type: 'string'
required: false
defaultHidden: true
order: 102
width:
label: 'Width'
description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Width'
type: 'string'
required: false
defaultHidden: true
order: 103
autoHeight:
label: 'Auto-Height (Fit to Contents)'
description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.'
type: 'boolean'
required: false
defaultHidden: true
order: 104
helpText:
label: 'Help Text'
description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 109
theme:
label: 'Theme'
description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 110
themeVariant:
label: 'Theme Variant'
description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 111
noData:
label: 'No Data Message'
description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 120
noscroll:
label: 'No Scroll'
description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 121
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 122
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 123
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 124
hidden:
label: 'Hidden'
description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 125
order: 3
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.'
placeholder: 'Seconds per page'
inherit: true
type: 'integer'
required: false
defaultHidden: true
order: 4
frequency:
label: 'Frequency'
description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.'
default: 1
type: 'integer'
required: false
defaultHidden: true
order: 5
theme:
label: 'Theme'
description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 6
themeVariant:
label: 'Theme Variant'
description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 7
style:
label: 'Style'
description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 8
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 10
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 11
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 12;
dataSources:
label: 'Data Sources'
description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.'
type: 'datasources'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The Data Source Name is used to reference the Data Source from a widget'
placeholder: 'Data Source Name'
type: 'string'
required: true
order: 1
type:
label: 'Type'
description: 'Specifies the implementation type of the Data Source'
type: 'string'
required: true
order: 0
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 101
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
defaultHidden: true
order: 102
preload:
label: 'Preload'
description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
deferred:
label: 'Deferred'
description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
errorHandler:
label: 'Error Handler'
description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 104
options:
cloudwatch:
value: 'cloudwatch'
label: 'CloudWatch'
message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".'
placeholder: 'CloudWatch Endpoint'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
awsCredentials:
label: 'AWS Credentials'
description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: true
order: 12
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
parameters:
label: 'CloudWatch Parameters'
description: 'Set of parameters for the CloudWatch API.'
type: 'propertyset'
required: true
order: 13
properties:
Action:
label: 'Action'
description: 'Specifies one of the CloudWatch actions.'
type: 'string'
default: 'auto'
inlineJs: true
options:
ListMetrics:
value: 'ListMetrics'
GetMetricStatistics:
value: 'GetMetricStatistics'
required: true
order: 1
Namespace:
label: 'Namespace'
description: 'The namespace to filter against.'
type: 'string'
inlineJs: true
required: false
order: 2
MeasureName:
label: 'Metric Name'
description: 'The name of the metric to filter against.'
type: 'string'
inlineJs: true
required: false
order: 3
Dimensions:
label: 'Dimensions'
description: 'Optional; a list of Dimension key/values to filter against.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
order: 4
Statistics:
label: 'Statistics'
description: 'Specifies one or more Statistics to return.'
type: 'string[]'
inlineJs: true
options:
SampleCount:
value: 'SampleCount'
Average:
value: 'Average'
Sum:
value: 'Sum'
Minimum:
value: 'Minimum'
Maximum:
value: 'Maximum'
required: true
order: 5
Period:
label: 'Period'
description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.'
type: 'integer'
default: 60
required: false
placeholder: 'Number of Seconds'
order: 6
StartTime:
label: 'Start Time'
description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 8
EndTime:
label: 'End Time'
description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 9
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 15
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 16
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 17
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
cyclotronData:
value: 'cyclotronData'
label: 'CyclotronData'
icon: 'fa-cloud-download'
message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.'
properties:
key:
label: 'Bucket Key'
description: 'Specifies the unique key to a Cyclotron Data bucket.'
placeholder: 'Bucket Key'
type: 'string'
inlineJs: true
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
url:
label: 'Cyclotron Server'
description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
elasticsearch:
value: 'elasticsearch'
label: 'Elasticsearch'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Elasticsearch endpoint.'
placeholder: 'Elasticsearch URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
index:
label: 'Index'
description: 'Specifies the name of the Elasticsearch index to query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 12
method:
label: 'API Name'
description: 'Indicates which Elasticsearch API method to use; defaults to "_search".'
type: 'string'
inlineJs: true
inlineEncryption: true
defaultHidden: true
default: '_search'
required: false
order: 13
request:
label: 'Elasticsearch Request'
description: 'Specifies the Elasticsearch JSON request.'
placeholder: 'JSON'
type: 'editor'
editorMode: 'json'
inlineJs: true
inlineEncryption: true
required: true
order: 14
responseAdapter:
label: 'Response Adapter'
description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".'
type: 'string'
default: 'auto'
inlineJs: true
options:
'Auto':
value: 'auto'
'Hits':
value: 'hits'
'Aggregations':
value: 'aggregations'
'Raw':
value: 'raw'
required: false
order: 15
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 20
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 21
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 22
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 23
graphite:
value: 'graphite'
label: 'Graphite'
icon: 'fa-cloud-download'
message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.'
properties:
url:
label: 'URL'
description: 'The Graphite server'
placeholder: 'Graphite Server URL or IP'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
targets:
label: 'Targets'
description: 'One or more Graphite metrics, optionally with metrics.'
type: 'string[]'
inlineJs: true
inlineEncryption: true
required: true
order: 11
from:
label: 'From'
description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).'
placeholder: 'Start Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
until:
label: 'Until'
description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).'
placeholder: 'End Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
influxdb:
value: 'influxdb'
label: 'InfluxDB'
icon: 'fa-cloud-download'
message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open-source time series database built from the ground up to handle high write and query loads.'
properties:
url:
label: 'URL'
description: 'The InfluxDB server'
placeholder: 'InfluxDB Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
database:
label: 'Database'
description: 'Specifies the target InfluxDB database for the query.'
placeholder: 'Database'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
required: false
order: 11
query:
label: 'Query'
description: 'An InfluxQL query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
precision:
label: 'Precision'
description: 'Overrides the default timestamp precision.'
type: 'string'
default: 'ms'
inlineJs: true
options:
h:
value: 'h'
m:
value: 'm'
s:
value: 's'
ms:
value: 'ms'
u:
value: 'u'
ns:
value: 'ns'
order: 11
username:
label: 'Username'
description: 'Optional; username for authentication, if enabled.'
type: 'string'
inlineJs: true
inlineEncryption: true
order: 15
password:
label: 'Password'
description: 'Optional; password for authentication, if enabled.'
type: 'string'
inputType: 'password'
inlineJs: true
inlineEncryption: true
order: 16
insecureSsl:
label: 'Insecure SSL'
description: 'If true, disables SSL certificate validation; useful for self-signed certificates.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 18
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
javascript:
value: 'javascript'
label: 'JavaScript'
icon: 'fa-cloud-download'
message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.'
properties:
processor:
label: 'Processor'
description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 12
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 13
json:
value: 'json'
label: 'JSON'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the JSON Web Service URL.'
placeholder: 'Web Service URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
queryParameters:
label: 'Query Parameters'
description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.'
type: 'hash'
required: false
inlineJsKey: true
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 12
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 17
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
mock:
value: 'mock'
label: 'Mock'
icon: 'fa-cloud-download'
message: 'The Mock Data Source generates sample data for testing a dashboard.'
properties:
format:
label: 'Format'
description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".'
type: 'string'
required: false
default: 'object'
options:
object:
value: 'object'
pie:
value: 'pie'
large:
value: 'large'
ducati:
value: 'ducati'
order: 10
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
prometheus:
value: 'prometheus'
label: 'Prometheus'
icon: 'fa-cloud-download'
message: '<a href="https://prometheus.io/" target="_blank">Prometheus</a> is an open-source systems monitoring and alerting toolkit.'
properties:
url:
label: 'URL'
description: 'The Prometheus server'
placeholder: 'Prometheus Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
query:
label: 'Query'
description: 'A Prometheus expression query string.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
start:
label: 'Start'
description: 'Specifies the start time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults to 24 hours ago.'
placeholder: 'Start Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
end:
label: 'End'
description: 'Specifies the end time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults now.'
placeholder: 'End Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
step:
label: 'Step'
description: 'Query resolution step width (e.g. 10s, 1m, 4h, etc). If omitted, defaults to 1m.'
placeholder: 'Step width (10s, 1m, 4h, etc)'
type: 'string'
default: '1m'
inlineJs: true
order: 14
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
splunk:
value: 'splunk'
label: 'Splunk'
icon: 'fa-cloud-download'
properties:
query:
label: 'Query'
description: 'Splunk query'
placeholder: 'Splunk query'
type: 'textarea'
required: true
order: 10
earliest:
label: 'Earliest Time'
description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Earliest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 11
latest:
label: 'Latest Time'
description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Latest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
username:
label: 'Username'
description: 'Username to authenticate with Splunk'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
order: 13
password:
label: 'Password'
description: 'Password to authenticate with Splunk'
type: 'string'
inputType: 'password'
required: true
inlineJs: true
inlineEncryption: true
order: 14
host:
label: 'Host'
description: 'Splunk API host name'
placeholder: 'Splunk API host name'
type: 'string'
inputType: 'string'
required: false
defaultHidden: false
order: 15
url:
label: 'URL'
description: 'The Splunk API Search URL'
placeholder: 'Splunk API Search URL'
type: 'url'
inlineJs: true
inlineEncryption: true
default: 'https://#{host}:8089/services/search/jobs/export'
defaultHidden: true
required: false
order: 16
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 17
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 18
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 20
parameters:
label: 'Parameters'
description: 'A list of Parameters that can be used to configure the Dashboard.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The name used to set or reference this Parameter.'
type: 'string'
required: true
placeholder: 'Parameter Name'
order: 0
defaultValue:
label: 'Default Value'
description: 'The value used if the Parameter is not set when opening the Dashboard.'
type: 'string'
placeholder: 'Default Value'
required: false
inlineJs: true
order: 1
showInUrl:
label: 'Show in URL'
description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.'
type: 'boolean'
default: true
required: false
order: 2
editInHeader:
label: 'Editable in Header'
description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).'
type: 'boolean'
default: false
required: false
order: 3
persistent:
label: 'Persistent'
description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.'
type: 'boolean'
default: false
required: false
order: 4
changeEvent:
label: 'Change Event'
description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 10
editing:
label: 'Editing'
description: 'Configuration for how this Parameter can be edited in the Dashboard.'
type: 'propertyset'
required: false
default: {}
defaultHidden: true
order: 15
properties:
displayName:
label: 'Display Name'
description: 'The display name used for this Parameter.'
type: 'string'
required: false
placeholder: 'Display Name'
order: 1
editorType:
label: 'Editor Type'
description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).'
type: 'string'
required: false
default: 'textbox'
order: 2
options:
textbox:
value: 'textbox'
dropdown:
value: 'dropdown'
links:
value: 'links'
checkbox:
value: 'checkbox'
datetime:
value: 'datetime'
date:
value: 'date'
time:
value: 'time'
dataSource:
label: 'Data Source'
description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 4
datetimeFormat:
label: 'Date/Time Format'
description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.'
type: 'string'
required: false
placeholder: 'Format'
defaultHidden: true
order: 5
sample:
name: ''
defaultValue: ''
scripts:
label: 'Scripts'
description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the script'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a JavaScript file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'JavaScript file URL'
required: false
order: 1
text:
label: 'JavaScript Text'
description: 'Inline JavaScript to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'javascript'
placeholder: 'Inline JavaScript'
required: false
order: 2
singleLoad:
label: 'Single-Load'
description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.'
type: 'boolean'
required: false
default: false
order: 3
sample:
text: ''
styles:
label: 'Styles'
description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the style'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a CSS file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'CSS file URL'
required: false
order: 0
text:
label: 'CSS Text'
description: 'Inline CSS to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'css'
placeholder: 'Inline CSS'
required: false
order: 1
sample:
text: ''
controls:
# Controls how long to display the controls before hiding.
duration: 1000
# Controls how close the mouse must be before the controls appear
hitPaddingX: 60
hitPaddingY: 50
sample:
name: ''
sidebar:
showDashboardSidebar: true
pages: []
# Dashboard Sidebar
dashboardSidebar:
footer:
logos: [{
title: 'Cyclotron'
src: '/img/favicon32.png'
href: '/'
}]
# List of help pages
help: [
{
name: 'About'
path: '/partials/help/about.html'
tags: ['about', 'terminology', 'features']
children: [
{
name: 'Quick Start'
path: '/partials/help/quickstart.html'
tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets']
}
{
name: 'JSON'
path: '/partials/help/json.html'
tags: ['json']
}
{
name: 'Examples'
path: '/partials/help/examples.html'
tags: ['examples', 'cyclotron-examples']
}
{
name: 'Browser Compatibility'
path: '/partials/help/browserCompat.html'
tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck']
}
{
name: 'Permissions'
path: '/partials/help/permissions.html'
tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api']
}
{
name: 'Analytics'
path: '/partials/help/analytics.html'
tags: ['analytics', 'pageviews', 'visits', 'metrics']
}
{
name: 'Encrypted Strings'
path: '/partials/help/encryptedStrings.html'
tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt']
}
{
name: 'JavaScript API'
path: '/partials/help/javascriptApi.html'
tags: ['javascript', 'api', 'scripting']
}
{
name: 'CyclotronData'
path: '/partials/help/cyclotrondata.html'
tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api']
}
{
name: '3rd Party Libraries'
path: '/partials/help/3rdparty.html'
tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js']
}
{
name: 'Hotkeys'
path: '/partials/help/hotkeys.html'
tags: ['hotkeys', 'keys', 'shortcuts']
}
{
name: 'API'
path: '/partials/help/api.html'
tags: ['api', 'rest', 'service']
}
]
}
{
name: 'Dashboards'
path: '/partials/help/dashboards.html'
tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters']
children: [
{
name: 'Pages'
path: '/partials/help/pages.html'
tags: ['pages', 'widgets']
}
{
name: 'Layout'
path: '/partials/help/layout.html'
tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute']
}
{
name: 'Parameters'
path: '/partials/help/parameters.html'
tags: ['parameters']
}
{
name: 'Scripts'
path: '/partials/help/scripts.html'
tags: ['scripts', 'javascript']
}
{
name: 'Styles'
path: '/partials/help/styles.html'
tags: ['styles', 'css']
}
]
}
{
name: 'Data Sources'
path: '/partials/help/dataSources.html'
tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor']
}
{
name: 'Widgets'
path: '/partials/help/widgets.html'
tags: ['widgets']
}
]
# Formats supported for Dashboard Export
exportFormats: [{
label: 'PDF',
value: 'pdf'
}]
# Page settings
page:
sample:
frequency: 1
layout:
gridColumns: 2
gridRows: 2
widgets: []
# Widget settings
widgets:
annotationChart:
name: 'annotationChart'
label: 'Annotation Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
xAxis:
label: 'X-Axis'
description: 'Configuration of the X-axis.'
type: 'propertyset'
required: true
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source used for the x-axis.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
format:
label: 'Format'
description: 'Specifies which format the incoming datetime data is in.'
type: 'string'
options:
date:
value: 'date'
epoch:
value: 'epoch'
epochmillis:
value: 'epochmillis'
string:
value: 'string'
order: 2
formatString:
label: 'Format String'
description: 'Used with the String format to specify how the string should be parsed.'
type: 'string'
order: 3
order: 11
series:
label: 'Series'
singleLabel: 'series'
description: 'One or more series to display in the annotation chart.'
type: 'propertyset[]'
required: true
default: []
order: 12
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source to use as the y-axis value for this series.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
label:
label: 'Label'
description: 'Display label for the series; if omitted, the column name will be used.'
placeholder: 'Label'
inlineJs: true
type: 'string'
order: 2
annotationTitleColumn:
label: 'Annotation Title Column Name'
description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 3
annotationTextColumn:
label: 'Annotation Text Column Name'
description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 4
secondaryAxis:
label: 'Secondary Axis'
description: 'If true, places the series on a second axis on the left of the chart.'
inlineJs: true
type: 'boolean'
order: 5
options:
label: 'Options'
description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.'
type: 'propertyset'
required: false
inlineJs: true
properties:
allValuesSuffix:
label: 'All Values Suffix'
description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
defaultHidden: true
annotationsWidth:
label: 'Annotations Width'
description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.'
type: 'integer'
inlineJs: true
defaultHidden: true
displayAnnotations:
label: 'Display Annotations'
description: 'Controls whether annotations are displayed along with the chart.'
type: 'boolean'
inlineJs: true
default: true
defaultHidden: true
displayAnnotationsFilter:
label: 'Display Annotations Filter'
description: 'If set to true, the chart will display a filter control to filter annotations.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayDateBarSeparator:
label: 'Display Date Bar Separator'
description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayLegendDots:
label: 'Display Legend Dots'
description: 'If set to true, the chart will display dots next to the values in the legend text.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayLegendValues:
label: 'Display Legend Values'
description: 'If set to true, the chart will display the highlighted values in the legend.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayRangeSelector:
label: 'Display Range Selector'
description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayZoomButtons:
label: 'Display Zoom Buttons'
description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).'
type: 'boolean'
inlineJs: true
defaultHidden: true
fill:
label: 'Fill'
description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.'
type: 'integer'
inlineJs: true
defaultHidden: true
focusTarget:
label: 'Focus Target'
description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".'
type: 'string'
inlineJs: true
defaultHidden: true
default: 'category'
options:
datum:
value: 'datum'
category:
value: 'category'
legendPosition:
label: 'Legend Position'
description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
sameRow:
value: 'sameRow'
newRow:
value: 'newRow'
max:
label: 'Maximum'
description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
min:
label: 'Minimum'
description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
scaleFormat:
label: 'Scale Format'
description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.'
placeholder: 'Format'
type: 'string'
inlineJs: true
defaultHidden: true
scaleType:
label: 'Scale Type'
description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
maximized:
value: 'maximized'
fixed:
value: 'fixed'
allmaximized:
value: 'allmaximized'
allfixed:
value: 'allfixed'
thickness:
label: 'Thickness'
description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.'
placeholder: 'Thickness'
type: 'integer'
inlineJs: true
defaultHidden: true
zoomStartTime:
label: 'Zoom Start Time'
description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
zoomEndTime:
label: 'Zoom End Time'
description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
order: 13
annotationEditing:
label: 'Built-In Annotation Editing'
description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.'
type: 'boolean'
required: false
default: false
order: 13
annotationKey:
label: 'Built-In Annotation Key'
description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 14
events:
label: 'Events'
description: 'Optional event handlers for various events.'
type: 'propertyset'
required: false
defaultHidden: true
order: 15
properties:
rangechange:
label: 'Range Change Event'
description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 1
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 20
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 20
# Common options
options:
displayAnnotations: true
# Undocumented "chart" options
chart:
focusTarget: 'category'
sample: ->
# Generate new Annotation Chart Widget
{
annotationKey: <KEY>
}
# Theme-specific options
themes:
dark:
options:
dbackgroundColor: '#222222'
darkmetro:
options:
dbackgroundColor: '#202020'
chart:
name: 'chart'
label: 'Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
drilldownDataSource:
label: 'Drilldown Data Source'
description: 'The name of the Data Source providing drilldown data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: false
defaultHidden: true
options: datasourceOptions
order: 11
highchart:
label: 'Highchart Definition'
description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.'
type: 'json'
inlineJs: true
required: true
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 14
addShiftPoints:
label: 'Add/Shift Points'
description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.'
type: 'boolean'
default: false
required: false
order: 15
sample:
highchart:
series: [{
x: ''
y: ''
}
]
xAxis: [{
type: 'linear'
}
]
yAxis: [{
title:
text: 'Values'
}
]
themes:
light:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
drilldown:
activeAxisLabelStyle:
color: '#333'
textDecoration: 'none'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
gto:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
dark:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
dark2:
colors: [
'#2095F0' #Blue
'#FF9A13' #Orange
'#FFFF13' #Yellow
'#A61DF1' #Purple
'#28F712' #Green
'#FE131E' #Red
'#D1D1D0' #Offwhite
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
dataLabels:
style:
color: '#999'
textShadow: false
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
darkmetro:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
charcoal:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
clock:
name: 'clock'
label: 'Clock'
icon: 'fa-clock-o'
properties:
format:
label: 'Format'
description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats'
type: 'string'
default: 'dddd, MMMM Do YYYY, h:mm:ss a'
required: false
order: 10
timezone:
label: 'Time Zone'
description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone'
required: false
type: 'string'
order: 11
header:
name: 'header'
label: 'Header'
icon: 'fa-header'
properties:
headerTitle:
label: 'Header Title'
description: 'Contains properties for displaying a title in the header.'
type: 'propertyset'
order: 10
properties:
showTitle:
label: 'Show Title'
description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 1
showPageName:
label: 'Show Page Name'
description: 'Determines whether the current page name will be shown as part of the title.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 2
pageNameSeparator:
label: 'Page Name Separator'
description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.'
type: 'string'
required: false
default: ''
inlineJs: true
defaultHidden: true
order: 3
titleSize:
label: 'Title Size'
description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 5
logoUrl:
label: 'Logo URL'
description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.'
type: 'string'
required: false
inlineJs: true
order: 10
logoSize:
label: 'Logo Size'
description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 11
link:
label: 'Link'
description: 'If set, makes the Logo and Title a link to this URL.'
type: 'string'
required: false
inlineJs: true
order: 20
parameters:
label: 'Parameters'
description: 'Contains properties for displaying Dashboard Parameters in the header.'
type: 'propertyset'
order: 20
properties:
showParameters:
label: 'Show Parameters'
description: 'Determines whether Parameters will be shown.'
type: 'boolean'
default: false
required: false
inlineJs: true
order: 1
showUpdateButton:
label: 'Show Update Button'
description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.'
type: 'boolean'
default: false
required: false
order: 2
updateButtonLabel:
label: 'Update Button Label'
description: 'Customizes the label for the Update button, if shown.'
type: 'string'
default: 'Update'
defaultHidden: true
required: false
order: 2
updateEvent:
label: 'Update Button Click Event'
description: 'This event occurs when the Update button is clicked, if shown.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 10
parametersIncluded:
label: 'Included Parameters'
description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.'
type: 'string[]'
required: false
defaultHidden: true
order: 11
customHtml:
label: 'HTML Content'
description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.'
type: 'editor'
editorMode: 'html'
required: false
inlineJs: true
order: 30
html:
name: 'html'
label: 'HTML'
icon: 'fa-html5'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
html:
label: 'HTML'
description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 11
preHtml:
label: 'Pre-HTML'
description: 'Optional, contains HTML markup which is displayed before the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 12
postHtml:
label: 'Post-HTML'
description: 'Optional, contains HTML markup which is displayed after the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 15
iframe:
name: 'iframe'
label: 'iFrame'
icon: 'fa-desktop'
properties:
url:
label: 'Url'
description: 'Specifies the URL to be loaded within the Widget.'
type: 'string'
placeholder: 'Url'
required: true
default: 'http://www.expedia.com'
order: 10
refresh:
label: 'Refresh'
description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 11
image:
name: 'image'
label: 'Image'
icon: 'fa-image-o'
properties:
images:
label: 'Images'
singleLabel: 'Image'
description: 'One or more Images to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 10
properties:
url:
label: 'URL'
description: 'URL to the image to be displayed.'
placeholder: 'Url'
inlineJs: true
required: true
type: 'string'
order: 1
link:
label: 'Link'
description: 'Optional, specifies a URL that will be opened if the image is clicked on.'
placeholder: 'URL'
type: 'url'
inlineJs: true
required: false
order: 13
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the image.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 2
backgroundSize:
label: 'Background-Size'
description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
options:
auto:
value: 'auto'
contain:
value: 'contain'
cover:
value: 'cover'
'100%':
value: '100%'
order: 3
backgroundPosition:
label: 'Background Position'
description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'center'
defaultHidden: true
options:
center:
value: 'center'
top:
value: 'top'
bottom:
value: 'bottom'
left:
value: 'left'
right:
value: 'right'
order: 4
backgroundColor:
label: 'Background Color'
description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
backgroundRepeat:
label: 'Background Repeat'
description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'no-repeat'
defaultHidden: true
options:
'no-repeat':
value: 'no-repeat'
'repeat':
value: 'repeat'
'repeat-x':
value: 'repeat-x'
'repeat-y':
value: 'repeat-y'
'space':
value: 'space'
'round':
value: 'round'
order: 6
filters:
label: 'Filters'
description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 7
duration:
label: 'Auto-Rotate Duration'
description: 'Optional number of seconds; enables rotating among a set of images periodically.'
placeholder: 'Seconds'
type: 'integer'
default: 0
required: false
order: 11
javascript:
name: 'javascript'
label: 'JavaScript'
icon: 'fa-cogs'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
functionName:
label: 'Function Name'
description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot'
placeholder: 'Function Name'
type: 'string'
required: true
order: 11
refresh:
label: 'Refresh'
description: 'Optional; enables re-invoking the javascript object periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 14
json:
name: 'json',
label: 'JSON',
icon: 'fa-cog',
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
linkedWidget:
name: 'linkedWidget'
label: 'Linked Widget'
icon: 'fa-link'
properties:
linkedWidget:
label: 'Linked Widget'
description: 'Selects another Widget in this Dashboard to link.'
type: 'string'
required: true
options: linkedWidgetOptions
order: 10
number:
name: 'number'
label: 'Number'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
numbers:
label: 'Numbers'
singleLabel: 'number'
description: 'One or more Numbers to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 11
properties:
number:
label: 'Number'
description: 'Number value or expression.'
placeholder: 'Value'
inlineJs: true
required: false
type: 'string'
order: 1
prefix:
label: 'Prefix'
description: 'Optional; specifies a prefix to append to the number.'
placeholder: 'Prefix'
type: 'string'
inlineJs: true
order: 2
suffix:
label: 'Suffix'
description: 'Optional; specifies a suffix to append to the number.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
order: 3
color:
label: 'Color'
description: 'Sets the color of the number.'
placeholder: 'Color'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 4
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the number.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
icon:
label: 'Icon'
description: 'Optional Font Awesome icon class to be displayed with the number.'
placeholder: 'Icon Class'
inlineJs: true
type: 'string'
defaultHidden: true
order: 6
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
order: 7
iconTooltip:
label: 'IconTooltip'
description: 'Sets the tooltip of the icon.'
placeholder: 'Icon Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 8
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 9
orientation:
label: 'Orientation'
description: 'Controls the direction in which the numbers are arranged.'
type: 'string'
required: false
default: 'vertical'
options:
vertical:
value: 'vertical'
horizontal:
value: 'horizontal'
order: 12
autoSize:
label: 'Auto-Size Numbers'
description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.'
type: 'boolean'
required: false
default: true
order: 13
link:
label: 'Link'
description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.'
placeholder: 'URL'
type: 'url'
required: false
order: 14
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
qrcode:
name: 'qrcode'
label: 'QRcode'
icon: 'fa-cogs'
properties:
text:
label: 'Text'
description: 'Text content of the generated QR code.'
placeholder: 'QR Code Contents'
type: 'string'
required: false
order: 10
maxSize:
label: 'Max Size'
description: 'Maximum height/width of the QR code.'
type: 'integer'
required: false
order: 11
useUrl:
label: 'Use URL'
description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.'
type: 'boolean'
default: false
required: false
order: 12
dataSource:
label: 'Data Source'
description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
defaultHidden: true
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
defaultHidden: true
order: 15
colorDark:
label: 'Dark Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#000000'
required: false
defaultHidden: true
order: 16
colorLight:
label: 'Light Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#ffffff'
required: false
defaultHidden: true
order: 17
sample:
text: 'hello'
stoplight:
name: 'stoplight'
label: 'Stoplight'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
rules:
label: 'Rules'
description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled'
type: 'propertyset'
required: true
order: 11
properties:
green:
label: 'Green'
description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 3
yellow:
label: 'Yellow'
description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 2
red:
label: 'Red'
description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 1
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the stoplight.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 12
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
table:
name: 'table'
label: 'Table'
icon: 'fa-table'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
columns:
label: 'Columns'
singleLabel: 'column'
description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.'
type: 'propertyset[]'
inlineJs: true
properties:
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
order: 1
label:
label: 'Label'
description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
order: 2
text:
label: 'Text'
description: 'Overrides the text in the cell using this value as an expression.'
type: 'string'
inlineJs: true
defaultHidden: true
order: 3
tooltip:
label: 'Tooltip'
description: 'Optionally specifies a tooltip to display for each cell in the column.'
type: 'string'
inlineJs: true
defaultHidden: true
headerTooltip:
label: 'Header Tooltip'
description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
defaultHidden: true
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
link:
label: 'Link'
description: 'If provided, the cell text will be made into a link rather than plain text.'
type: 'url'
inlineJs: true
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, links will open in a new browser window; this is the default.'
type: 'boolean'
default: true
defaultHidden: true
numeralformat:
label: 'Numeral Format'
description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.'
type: 'string'
inlineJs: true
defaultHidden: true
image:
label: 'Image'
description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.'
type: 'url'
inlineJs: true
defaultHidden: true
imageHeight:
label: 'Image Height'
description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.'
type: 'string'
inlineJs: true
defaultHidden: true
icon:
label: 'Icon'
description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.'
type: 'string'
inlineJs: true
defaultHidden: true
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
border:
label: 'Border'
description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.'
type: 'string'
inlineJs: true
defaultHidden: true
group:
label: 'Column Group'
description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.'
type: 'string'
inlineJs: true
defaultHidden: true
groupRows:
label: 'Group Rows'
description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.'
type: 'boolean'
default: false
defaultHidden: true
columnSortFunction:
label: 'Column Sort Function'
description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".'
type: 'string'
inlineJs: true
defaultHidden: true
columnsIgnored:
label: 'Columns Ignored'
description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.'
type: 'string[]'
required: false
inlineJs: false
defaultHidden: true
order: 10
sample:
name: ''
rules:
label: 'Rules'
singleLabel: 'rule'
description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.'
type: 'propertyset[]'
inlineJs: true
properties:
rule:
label: 'Rule'
description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.'
type: 'string'
required: true
inlineJs: true
order: 1
columns:
label: 'Columns Affected'
description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.'
type: 'string[]'
required: false
order: 2
columnsIgnored:
label: 'Columns Ignored'
description: 'Optionally specifies an array of column names that the rule does NOT apply to.'
type: 'string[]'
required: false
order: 3
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
defaultHidden: true
'font-weight':
label: 'Font-Weight (CSS)'
description: 'CSS setting for `font-weight`'
type: 'string'
inlineJs: true
defaultHidden: true
color:
label: 'Color (CSS)'
description: 'CSS setting for `color`'
type: 'string'
inlineJs: true
defaultHidden: true
'background-color':
label: 'Background Color (CSS)'
description: 'CSS setting for `background-color`'
type: 'string'
inlineJs: true
defaultHidden: true
order: 11
sample:
rule: 'true'
freezeHeaders:
label: 'Freeze Headers'
description: 'Enables frozen headers at the top of the widget when scrolling'
type: 'boolean'
default: false
required: false
order: 12
omitHeaders:
label: 'Omit Headers'
description: 'Disables the table header row'
type: 'boolean'
default: false
required: false
order: 13
enableSort:
label: 'Enable Sort'
description: 'Enable or disable user sort controls'
type: 'boolean'
default: true
required: false
order: 14
rowHeight:
label: 'Minimum Row Height'
description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.'
type: 'integer'
required: false
order: 15
pagination:
label: 'Pagination'
description: 'Controls pagination of the Table.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
enabled:
label: 'Enable Pagination'
description: 'Enables or disables pagination for this Table Widget.'
type: 'boolean'
default: false
required: false
order: 1
autoItemsPerPage:
label: 'Auto Items Per Page'
description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.'
type: 'boolean'
default: true
required: false
order: 2
itemsPerPage:
label: 'Items Per Page'
description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.'
type: 'integer'
required: false
order: 3
belowPagerMessage:
label: 'Below Pager Message'
description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.'
type: 'string'
required: false
order: 4
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 17
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 18
sortFunction:
label: 'Sort Function'
description: 'Optional, specifies an alternative function to the default sort implementation.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
onSort:
label: 'Sort Event'
description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 20
tableau:
name: 'tableau'
label: 'Tableau'
icon: 'fa-cog'
properties:
params:
label: 'Parameters'
description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.'
type: 'hash'
required: true
editorMode: 'json'
order: 10
treemap:
name: 'treemap'
label: 'Treemap'
icon: 'fa-tree'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
labelProperty:
label: 'Label Property'
description: 'The name of the property to use as the label of each item.'
type: 'string'
inlineJs: true
required: false
default: 'name'
defaultHidden: true
order: 11
valueProperty:
label: 'Value Property'
description: 'The name of the property to use to calculate the size of each item.'
type: 'string'
inlineJs: true
required: false
default: 'value'
defaultHidden: true
order: 12
valueDescription:
label: 'Value Description'
description: 'A short description of the property used to calculate the size of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 13
valueFormat:
label: 'Value Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
order: 14
colorProperty:
label: 'Color Property'
description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.'
type: 'string'
inlineJs: true
required: false
default: 'color'
order: 15
colorDescription:
label: 'Color Description'
description: 'A short description of the property used to calculate the color of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 16
colorFormat:
label: 'Color Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
large:
value: '0a'
order: 17
colorStops:
label: 'Color Stops'
singleLabel: 'color'
description: 'Specifies a list of color stops used to build a gradient.'
type: 'propertyset[]'
inlineJs: true
properties:
value:
label: 'Value'
description: 'The numerical value assigned to this color stop.'
type: 'number'
required: true
inlineJs: true
order: 1
color:
label: 'Color'
description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.'
type: 'string'
required: false
inlineJs: true
order: 2
order: 18
showLegend:
label: 'Show Legend'
description: 'Enables or disables the color legend.'
type: 'boolean'
default: true
required: false
order: 19
legendHeight:
label: 'Legend Height'
description: 'Specifies the height of the legend in pixels.'
type: 'number'
default: 30
required: false
defaultHidden: true
order: 20
youtube:
name: 'youtube'
label: 'YouTube'
icon: 'fa-youtube'
properties:
videoId:
label: 'Video / Playlist ID'
description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.'
type: 'string'
inlineJs: true
placeholder: 'ID'
required: true
order: 10
autoplay:
label: 'Auto-Play'
description: 'If true, automatically plays the video when the Widget is loaded.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 13
loop:
label: 'Loop'
description: 'If true, automatically loops the video when it completes.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 14
enableKeyboard:
label: 'Enable Keyboard'
description: 'If true, enables keyboard controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 15
enableControls:
label: 'Enable Controls'
description: 'If true, enables on-screen video controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 16
showAnnotations:
label: 'Show Annotations'
description: 'If true, displays available annotations over the video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 17
showRelated:
label: 'Show Related'
description: 'If true, displays related videos at the end of this video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 18
}
# Copy Theme options to inherited locations
exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
# Copy Style options to inherited locations
exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options
# Table Widget: Column properties duplicated in Rules:
tableProperties = exports.widgets.table.properties
_.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label')
# Copy some chart themes
exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light
# Populate Help tags with properties
helpDashboards = _.find(exports.help, { name: 'Dashboards' })
helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name
helpDataSources = _.find(exports.help, { name: 'Data Sources' })
helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name
helpWidgets = _.find(exports.help, { name: 'Widgets' })
helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name
propertyMapHelper = (value, name) ->
v = _.cloneDeep value
v.name = name
return v
# Add Widget and Data Source help pages
helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) ->
{
name: dataSource.label || dataSource.value
path: '/partials/help/datasources/' + dataSource.value + '.html'
tags: _.map dataSource.properties, propertyMapHelper
}
helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) ->
{
name: widget.label || widget.name
path: '/widgets/' + widget.name + '/help.html'
tags: _.map widget.properties, propertyMapHelper
}
return exports
| true | ###
# Copyright (c) 2013-2018 the original author or authors.
#
# Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
#
# 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.
###
# Common Config File - all default or shared configs
cyclotronServices.factory 'commonConfigService', ->
linkedWidgetOptions = (dashboard) ->
linkedWidgets = {}
_.each dashboard.pages, (page, pageIndex) ->
_.each page.widgets, (widget, widgetIndex) ->
return if widget.widget == 'linkedWidget'
widgetName = _.titleCase(widget.widget)
if widget.name?.length > 0 or widget.title?.length > 0
widgetName += ': ' + (widget.name || widget.title)
linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex }
linkedWidgets
datasourceOptions = (dashboard) ->
dataSources = {}
_.each dashboard.dataSources, (dataSource) ->
dataSources[dataSource.name] = { value: dataSource.name }
dataSources
exports = {
version: '2.0.2'
logging:
enableDebug: false
authentication:
enable: false
loginMessage: 'Please login using your LDAP username and password.'
analytics:
enable: false
newUser:
enableMessage: true
welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.'
iconClass: 'fa-info'
autoDecayDuration: 1
# Dashboard settings
dashboard:
properties:
name:
label: 'Name'
description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.'
placeholder: 'Dashboard Name'
type: 'string'
required: true
order: 0
displayName:
label: 'Display Name'
description: 'Display Name; this is displayed in the browser title bar or the Header Widget.'
placeholder: 'Display Name'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 1
description:
label: 'Description'
description: 'A short summary of the Dashboard\'s purpose or capabilities.'
placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.'
type: 'string'
required: false
order: 2
theme:
label: 'Theme'
description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.'
type: 'string'
default: 'dark'
required: false
options:
charcoal:
label: 'Charcoal'
value: 'charcoal'
dashboardBackgroundColor: '#1E2328'
aceTheme: 'solarized_dark'
dark:
label: 'Dark'
value: 'dark'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
darkmetro:
label: 'Dark Metro'
value: 'darkmetro'
dashboardBackgroundColor: '#2f2f2f'
aceTheme: 'tomorrow_night'
gto:
label: 'GTO'
value: 'gto'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
light:
label: 'Light'
value: 'light'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
lightborderless:
label: 'Light (borderless)'
value: 'lightborderless'
dashboardBackgroundColor: 'white'
aceTheme: 'chrome'
dark2:
label: 'Very Dark'
value: 'dark2'
dashboardBackgroundColor: 'black'
aceTheme: 'monokai'
order: 5
themeVariant:
label: 'Theme Variant'
description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.'
type: 'string'
default: 'default'
required: false
defaultHidden: true
options:
default:
value: 'default'
transparent:
value: 'transparent'
'transparent-unpadded':
value: 'transparent-unpadded'
order: 6
style:
label: 'Style'
description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.'
type: 'string'
default: 'normal'
required: false
options:
normal:
value: 'normal'
fullscreen:
value: 'fullscreen'
defaultHidden: true
order: 7
autoRotate:
label: 'Auto-Rotate'
description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 10
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.'
type: 'integer'
placeholder: 'Seconds per page'
default: 60
required: false
defaultHidden: true
order: 11
preload:
label: 'Pre-Load Time (seconds)'
description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.'
placeholder: 'Seconds'
type: 'integer'
default: 0.050
required: false
defaultHidden: true
order: 12
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.'
type: 'boolean'
default: true
required: false
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, all links will open in a new browser window; this is the default.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.'
type: 'boolean'
required: false
default: true
defaultHidden: true
showDashboardControls:
label: 'Show Dashboard Controls'
description: 'If false, hides the default Dashboard controls (rotation, export, etc)'
type: 'boolean'
required: false
default: true
defaultHidden: true
sidebar:
label: 'Sidebar'
description: ''
type: 'propertyset'
default: {}
defaultHidden: true
properties:
showDashboardSidebar:
label: 'Show Dashboard Sidebar'
description: 'If false, hides the default Dashboard Sidebar.'
type: 'boolean'
required: false
default: false
order: 10
showDashboardTitle:
label: 'Include Dashboard Title'
description: 'Enables a section of the sidebar for the Dashboard title.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 11
showToolbar:
label: 'Include Toolbar'
description: 'Enables a toolbar in the sidebar.'
type: 'boolean'
required: false
default: true
defaultHidden: true
order: 12
showHideWidgets:
label: 'Include Show/Hide Widgets'
description: 'Enables a section of the sidebar for overriding the visibility of Widgets.'
type: 'boolean'
required: false
default: false
defaultHidden: true
order: 13
sidebarContent:
label: 'Custom Sidebar Sections'
singleLabel: 'Section'
description: 'One or more sections of content to display in the Sidebar.'
type: 'propertyset[]'
default: []
order: 15
properties:
heading:
label: 'Heading'
description: 'Heading for the Sidebar section.'
type: 'string'
inlineJs: true
order: 1
html:
label: 'HTML Content'
description: 'HTML Content to display.'
placeholder: 'Value'
type: 'editor'
editorMode: 'html'
inlineJs: true
order: 2
pages:
label: 'Pages'
description: 'The list of Page definitions which compose the Dashboard.'
type: 'pages'
default: []
required: true
properties:
name:
label: 'Name'
description: 'Name of this page; used in the browser title and URL.'
placeholder: 'Page Name'
type: 'string'
required: false
order: 0
layout:
label: 'Layout'
description: 'Contains properties for configuring the Page layout and dimensions.'
type: 'propertyset'
default: {}
required: false
properties:
gridColumns:
label: 'Grid Columns'
description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.'
type: 'integer'
required: false
order: 0
gridRows:
label: 'Grid Rows'
description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.'
type: 'integer'
required: false
order: 1
gridWidthAdjustment:
label: 'Grid Page Width Adjustment'
description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).'
type: 'integer'
default: 0
required: false
defaultHidden: true
order: 2
gridHeightAdjustment:
label: 'Grid Page Height Adjustment'
description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.'
type: 'integer'
default: 0
required: false
order: 3
gutter:
label: 'Gutter'
description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 5
borderWidth:
label: 'Border Width'
description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.'
type: 'integer'
default: null
required: false
defaultHidden: true
order: 6
margin:
label: 'Margin'
description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.'
type: 'integer'
default: 10
required: false
defaultHidden: true
order: 7
scrolling:
label: 'Scrolling Enabled'
description: 'Enables vertical scrolling of the page to display content longer than the current browser size.'
type: 'boolean'
default: true
required: false
defaultHidden: true
order: 8
order: 2
widgets:
label: 'Widgets'
description: 'An array of one or more Widgets to display on the page'
type: 'propertyset[]'
subState: 'edit.widget'
headingfn: 'getWidgetName'
default: []
required: true
properties:
widget:
label: 'Type'
description: 'The type of Widget to be rendered.'
type: 'string'
required: true
name:
label: 'Name'
description: 'Internal Widget name, displayed in the Dashboard Editor.'
placeholder: 'Name'
type: 'string'
required: false
defaultHidden: true
inlineJs: false
order: 1
title:
label: 'Title'
description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.'
placeholder: 'Widget Title'
type: 'string'
required: false
inlineJs: true
order: 2
gridHeight:
label: 'Grid Rows'
description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.'
placeholder: 'Number of Rows'
type: 'integer'
default: '1'
required: false
order: 100
gridWidth:
label: 'Grid Columns'
description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.'
placeholder: 'Number of Columns'
type: 'integer'
default: '1'
required: false
order: 101
height:
label: 'Height'
description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Height'
type: 'string'
required: false
defaultHidden: true
order: 102
width:
label: 'Width'
description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).'
placeholder: 'Width'
type: 'string'
required: false
defaultHidden: true
order: 103
autoHeight:
label: 'Auto-Height (Fit to Contents)'
description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.'
type: 'boolean'
required: false
defaultHidden: true
order: 104
helpText:
label: 'Help Text'
description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.'
type: 'string'
required: false
inlineJs: true
defaultHidden: true
order: 109
theme:
label: 'Theme'
description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 110
themeVariant:
label: 'Theme Variant'
description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 111
noData:
label: 'No Data Message'
description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 120
noscroll:
label: 'No Scroll'
description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 121
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 122
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 123
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 124
hidden:
label: 'Hidden'
description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 125
order: 3
duration:
label: 'Auto-Rotate Duration (seconds)'
description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.'
placeholder: 'Seconds per page'
inherit: true
type: 'integer'
required: false
defaultHidden: true
order: 4
frequency:
label: 'Frequency'
description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.'
default: 1
type: 'integer'
required: false
defaultHidden: true
order: 5
theme:
label: 'Theme'
description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 6
themeVariant:
label: 'Theme Variant'
description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 7
style:
label: 'Style'
description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.'
type: 'string'
inherit: true
required: false
defaultHidden: true
order: 8
allowFullscreen:
label: 'Allow Fullscreen'
description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 10
allowExport:
label: 'Allow Export'
description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.'
type: 'boolean'
inherit: true
required: false
defaultHidden: true
order: 11
showWidgetErrors:
label: 'Show Error Messages on Widgets'
description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.'
type: 'boolean'
required: false
inherit: true
defaultHidden: true
order: 12;
dataSources:
label: 'Data Sources'
description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.'
type: 'datasources'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The Data Source Name is used to reference the Data Source from a widget'
placeholder: 'Data Source Name'
type: 'string'
required: true
order: 1
type:
label: 'Type'
description: 'Specifies the implementation type of the Data Source'
type: 'string'
required: true
order: 0
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 101
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
defaultHidden: true
order: 102
preload:
label: 'Preload'
description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
deferred:
label: 'Deferred'
description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.'
type: 'boolean'
inlineJs: false
required: false
default: false
defaultHidden: true
order: 103
errorHandler:
label: 'Error Handler'
description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 104
options:
cloudwatch:
value: 'cloudwatch'
label: 'CloudWatch'
message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".'
placeholder: 'CloudWatch Endpoint'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
awsCredentials:
label: 'AWS Credentials'
description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: true
order: 12
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
parameters:
label: 'CloudWatch Parameters'
description: 'Set of parameters for the CloudWatch API.'
type: 'propertyset'
required: true
order: 13
properties:
Action:
label: 'Action'
description: 'Specifies one of the CloudWatch actions.'
type: 'string'
default: 'auto'
inlineJs: true
options:
ListMetrics:
value: 'ListMetrics'
GetMetricStatistics:
value: 'GetMetricStatistics'
required: true
order: 1
Namespace:
label: 'Namespace'
description: 'The namespace to filter against.'
type: 'string'
inlineJs: true
required: false
order: 2
MeasureName:
label: 'Metric Name'
description: 'The name of the metric to filter against.'
type: 'string'
inlineJs: true
required: false
order: 3
Dimensions:
label: 'Dimensions'
description: 'Optional; a list of Dimension key/values to filter against.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
order: 4
Statistics:
label: 'Statistics'
description: 'Specifies one or more Statistics to return.'
type: 'string[]'
inlineJs: true
options:
SampleCount:
value: 'SampleCount'
Average:
value: 'Average'
Sum:
value: 'Sum'
Minimum:
value: 'Minimum'
Maximum:
value: 'Maximum'
required: true
order: 5
Period:
label: 'Period'
description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.'
type: 'integer'
default: 60
required: false
placeholder: 'Number of Seconds'
order: 6
StartTime:
label: 'Start Time'
description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 8
EndTime:
label: 'End Time'
description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).'
type: 'string'
inlineJs: true
required: false
order: 9
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 15
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 16
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 17
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
cyclotronData:
value: 'cyclotronData'
label: 'CyclotronData'
icon: 'fa-cloud-download'
message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.'
properties:
key:
label: 'Bucket Key'
description: 'Specifies the unique key to a Cyclotron Data bucket.'
placeholder: 'Bucket Key'
type: 'string'
inlineJs: true
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
url:
label: 'Cyclotron Server'
description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
elasticsearch:
value: 'elasticsearch'
label: 'Elasticsearch'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the Elasticsearch endpoint.'
placeholder: 'Elasticsearch URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
index:
label: 'Index'
description: 'Specifies the name of the Elasticsearch index to query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 12
method:
label: 'API Name'
description: 'Indicates which Elasticsearch API method to use; defaults to "_search".'
type: 'string'
inlineJs: true
inlineEncryption: true
defaultHidden: true
default: '_search'
required: false
order: 13
request:
label: 'Elasticsearch Request'
description: 'Specifies the Elasticsearch JSON request.'
placeholder: 'JSON'
type: 'editor'
editorMode: 'json'
inlineJs: true
inlineEncryption: true
required: true
order: 14
responseAdapter:
label: 'Response Adapter'
description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".'
type: 'string'
default: 'auto'
inlineJs: true
options:
'Auto':
value: 'auto'
'Hits':
value: 'hits'
'Aggregations':
value: 'aggregations'
'Raw':
value: 'raw'
required: false
order: 15
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 20
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 21
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 22
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 23
graphite:
value: 'graphite'
label: 'Graphite'
icon: 'fa-cloud-download'
message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.'
properties:
url:
label: 'URL'
description: 'The Graphite server'
placeholder: 'Graphite Server URL or IP'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
targets:
label: 'Targets'
description: 'One or more Graphite metrics, optionally with metrics.'
type: 'string[]'
inlineJs: true
inlineEncryption: true
required: true
order: 11
from:
label: 'From'
description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).'
placeholder: 'Start Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
until:
label: 'Until'
description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).'
placeholder: 'End Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
influxdb:
value: 'influxdb'
label: 'InfluxDB'
icon: 'fa-cloud-download'
message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open-source time series database built from the ground up to handle high write and query loads.'
properties:
url:
label: 'URL'
description: 'The InfluxDB server'
placeholder: 'InfluxDB Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
database:
label: 'Database'
description: 'Specifies the target InfluxDB database for the query.'
placeholder: 'Database'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
required: false
order: 11
query:
label: 'Query'
description: 'An InfluxQL query.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
precision:
label: 'Precision'
description: 'Overrides the default timestamp precision.'
type: 'string'
default: 'ms'
inlineJs: true
options:
h:
value: 'h'
m:
value: 'm'
s:
value: 's'
ms:
value: 'ms'
u:
value: 'u'
ns:
value: 'ns'
order: 11
username:
label: 'Username'
description: 'Optional; username for authentication, if enabled.'
type: 'string'
inlineJs: true
inlineEncryption: true
order: 15
password:
label: 'Password'
description: 'Optional; password for authentication, if enabled.'
type: 'string'
inputType: 'password'
inlineJs: true
inlineEncryption: true
order: 16
insecureSsl:
label: 'Insecure SSL'
description: 'If true, disables SSL certificate validation; useful for self-signed certificates.'
type: 'boolean'
default: false
required: false
defaultHidden: true
order: 18
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the HTTP request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 19
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
javascript:
value: 'javascript'
label: 'JavaScript'
icon: 'fa-cloud-download'
message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.'
properties:
processor:
label: 'Processor'
description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: true
order: 10
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 12
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 13
json:
value: 'json'
label: 'JSON'
icon: 'fa-cloud-download'
properties:
url:
label: 'URL'
description: 'Specifies the JSON Web Service URL.'
placeholder: 'Web Service URL'
type: 'url'
inlineJs: true
inlineEncryption: true
required: true
order: 10
queryParameters:
label: 'Query Parameters'
description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.'
type: 'hash'
required: false
inlineJsKey: true
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 12
options:
label: 'Options'
description: 'Optional request parameters that are passed to the library making the request.'
type: 'hash'
required: false
inlineJsValue: true
inlineEncryption: true
defaultHidden: true
order: 13
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 14
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 15
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 16
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
awsCredentials:
label: 'AWS Credentials'
description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.'
type: 'propertyset'
required: false
defaultHidden: true
order: 17
properties:
accessKeyId:
label: 'Access Key Id'
description: 'AWS access key id'
type: 'string'
placeholder: 'Access Key Id'
inlineJs: true
inlineEncryption: true
order: 1
secretAccessKey:
label: 'Secret Access Key'
description: 'AWS sercet access key'
type: 'string'
placeholder: 'Secret Access Key'
inlineJs: true
inlineEncryption: true
order: 2
mock:
value: 'mock'
label: 'Mock'
icon: 'fa-cloud-download'
message: 'The Mock Data Source generates sample data for testing a dashboard.'
properties:
format:
label: 'Format'
description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".'
type: 'string'
required: false
default: 'object'
options:
object:
value: 'object'
pie:
value: 'pie'
large:
value: 'large'
ducati:
value: 'ducati'
order: 10
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 11
prometheus:
value: 'prometheus'
label: 'Prometheus'
icon: 'fa-cloud-download'
message: '<a href="https://prometheus.io/" target="_blank">Prometheus</a> is an open-source systems monitoring and alerting toolkit.'
properties:
url:
label: 'URL'
description: 'The Prometheus server'
placeholder: 'Prometheus Server URL or IP'
type: 'url'
inlineJs: true
required: true
order: 10
query:
label: 'Query'
description: 'A Prometheus expression query string.'
type: 'string'
inlineJs: true
inlineEncryption: true
required: true
order: 11
start:
label: 'Start'
description: 'Specifies the start time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults to 24 hours ago.'
placeholder: 'Start Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
end:
label: 'End'
description: 'Specifies the end time for the retrieved time range, in RFC 3339 (ISO 8601) format. If omitted, it defaults now.'
placeholder: 'End Time (ISO 8601 format)'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 13
step:
label: 'Step'
description: 'Query resolution step width (e.g. 10s, 1m, 4h, etc). If omitted, defaults to 1m.'
placeholder: 'Step width (10s, 1m, 4h, etc)'
type: 'string'
default: '1m'
inlineJs: true
order: 14
refresh:
label: 'Auto-Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 21
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 22
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
order: 23
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 11
splunk:
value: 'splunk'
label: 'Splunk'
icon: 'fa-cloud-download'
properties:
query:
label: 'Query'
description: 'Splunk query'
placeholder: 'Splunk query'
type: 'textarea'
required: true
order: 10
earliest:
label: 'Earliest Time'
description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Earliest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 11
latest:
label: 'Latest Time'
description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.'
placeholder: 'Latest Time'
type: 'string'
inlineJs: true
inlineEncryption: true
required: false
order: 12
username:
label: 'Username'
description: 'Username to authenticate with Splunk'
type: 'string'
required: true
inlineJs: true
inlineEncryption: true
order: 13
password:
label: 'Password'
description: 'Password to authenticate with Splunk'
type: 'string'
inputType: 'password'
required: true
inlineJs: true
inlineEncryption: true
order: 14
host:
label: 'Host'
description: 'Splunk API host name'
placeholder: 'Splunk API host name'
type: 'string'
inputType: 'string'
required: false
defaultHidden: false
order: 15
url:
label: 'URL'
description: 'The Splunk API Search URL'
placeholder: 'Splunk API Search URL'
type: 'url'
inlineJs: true
inlineEncryption: true
default: 'https://#{host}:8089/services/search/jobs/export'
defaultHidden: true
required: false
order: 16
refresh:
label: 'Refresh'
description: 'Optional; specifies the number of seconds after which the Data Source reloads'
type: 'integer'
required: false
placeholder: 'Number of Seconds'
order: 17
preProcessor:
label: 'Pre-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 18
postProcessor:
label: 'Post-Processor'
description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
proxy:
label: 'Proxy Server'
description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.'
type: 'url'
inlineJs: true
required: false
defaultHidden: true
order: 20
parameters:
label: 'Parameters'
description: 'A list of Parameters that can be used to configure the Dashboard.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'The name used to set or reference this Parameter.'
type: 'string'
required: true
placeholder: 'Parameter Name'
order: 0
defaultValue:
label: 'Default Value'
description: 'The value used if the Parameter is not set when opening the Dashboard.'
type: 'string'
placeholder: 'Default Value'
required: false
inlineJs: true
order: 1
showInUrl:
label: 'Show in URL'
description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.'
type: 'boolean'
default: true
required: false
order: 2
editInHeader:
label: 'Editable in Header'
description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).'
type: 'boolean'
default: false
required: false
order: 3
persistent:
label: 'Persistent'
description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.'
type: 'boolean'
default: false
required: false
order: 4
changeEvent:
label: 'Change Event'
description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 10
editing:
label: 'Editing'
description: 'Configuration for how this Parameter can be edited in the Dashboard.'
type: 'propertyset'
required: false
default: {}
defaultHidden: true
order: 15
properties:
displayName:
label: 'Display Name'
description: 'The display name used for this Parameter.'
type: 'string'
required: false
placeholder: 'Display Name'
order: 1
editorType:
label: 'Editor Type'
description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).'
type: 'string'
required: false
default: 'textbox'
order: 2
options:
textbox:
value: 'textbox'
dropdown:
value: 'dropdown'
links:
value: 'links'
checkbox:
value: 'checkbox'
datetime:
value: 'datetime'
date:
value: 'date'
time:
value: 'time'
dataSource:
label: 'Data Source'
description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 4
datetimeFormat:
label: 'Date/Time Format'
description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.'
type: 'string'
required: false
placeholder: 'Format'
defaultHidden: true
order: 5
sample:
name: ''
defaultValue: ''
scripts:
label: 'Scripts'
description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the script'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a JavaScript file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'JavaScript file URL'
required: false
order: 1
text:
label: 'JavaScript Text'
description: 'Inline JavaScript to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'javascript'
placeholder: 'Inline JavaScript'
required: false
order: 2
singleLoad:
label: 'Single-Load'
description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.'
type: 'boolean'
required: false
default: false
order: 3
sample:
text: ''
styles:
label: 'Styles'
description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.'
type: 'propertyset[]'
default: []
required: false
properties:
name:
label: 'Name'
description: 'Display name of the style'
type: 'string'
placeholder: 'Name'
required: false
order: 0
path:
label: 'Path'
description: 'URL to a CSS file, to be loaded along with the Dashboard'
type: 'url'
placeholder: 'CSS file URL'
required: false
order: 0
text:
label: 'CSS Text'
description: 'Inline CSS to be run when the Dashboard is loaded'
type: 'editor'
editorMode: 'css'
placeholder: 'Inline CSS'
required: false
order: 1
sample:
text: ''
controls:
# Controls how long to display the controls before hiding.
duration: 1000
# Controls how close the mouse must be before the controls appear
hitPaddingX: 60
hitPaddingY: 50
sample:
name: ''
sidebar:
showDashboardSidebar: true
pages: []
# Dashboard Sidebar
dashboardSidebar:
footer:
logos: [{
title: 'Cyclotron'
src: '/img/favicon32.png'
href: '/'
}]
# List of help pages
help: [
{
name: 'About'
path: '/partials/help/about.html'
tags: ['about', 'terminology', 'features']
children: [
{
name: 'Quick Start'
path: '/partials/help/quickstart.html'
tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets']
}
{
name: 'JSON'
path: '/partials/help/json.html'
tags: ['json']
}
{
name: 'Examples'
path: '/partials/help/examples.html'
tags: ['examples', 'cyclotron-examples']
}
{
name: 'Browser Compatibility'
path: '/partials/help/browserCompat.html'
tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck']
}
{
name: 'Permissions'
path: '/partials/help/permissions.html'
tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api']
}
{
name: 'Analytics'
path: '/partials/help/analytics.html'
tags: ['analytics', 'pageviews', 'visits', 'metrics']
}
{
name: 'Encrypted Strings'
path: '/partials/help/encryptedStrings.html'
tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt']
}
{
name: 'JavaScript API'
path: '/partials/help/javascriptApi.html'
tags: ['javascript', 'api', 'scripting']
}
{
name: 'CyclotronData'
path: '/partials/help/cyclotrondata.html'
tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api']
}
{
name: '3rd Party Libraries'
path: '/partials/help/3rdparty.html'
tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js']
}
{
name: 'Hotkeys'
path: '/partials/help/hotkeys.html'
tags: ['hotkeys', 'keys', 'shortcuts']
}
{
name: 'API'
path: '/partials/help/api.html'
tags: ['api', 'rest', 'service']
}
]
}
{
name: 'Dashboards'
path: '/partials/help/dashboards.html'
tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters']
children: [
{
name: 'Pages'
path: '/partials/help/pages.html'
tags: ['pages', 'widgets']
}
{
name: 'Layout'
path: '/partials/help/layout.html'
tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute']
}
{
name: 'Parameters'
path: '/partials/help/parameters.html'
tags: ['parameters']
}
{
name: 'Scripts'
path: '/partials/help/scripts.html'
tags: ['scripts', 'javascript']
}
{
name: 'Styles'
path: '/partials/help/styles.html'
tags: ['styles', 'css']
}
]
}
{
name: 'Data Sources'
path: '/partials/help/dataSources.html'
tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor']
}
{
name: 'Widgets'
path: '/partials/help/widgets.html'
tags: ['widgets']
}
]
# Formats supported for Dashboard Export
exportFormats: [{
label: 'PDF',
value: 'pdf'
}]
# Page settings
page:
sample:
frequency: 1
layout:
gridColumns: 2
gridRows: 2
widgets: []
# Widget settings
widgets:
annotationChart:
name: 'annotationChart'
label: 'Annotation Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
xAxis:
label: 'X-Axis'
description: 'Configuration of the X-axis.'
type: 'propertyset'
required: true
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source used for the x-axis.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
format:
label: 'Format'
description: 'Specifies which format the incoming datetime data is in.'
type: 'string'
options:
date:
value: 'date'
epoch:
value: 'epoch'
epochmillis:
value: 'epochmillis'
string:
value: 'string'
order: 2
formatString:
label: 'Format String'
description: 'Used with the String format to specify how the string should be parsed.'
type: 'string'
order: 3
order: 11
series:
label: 'Series'
singleLabel: 'series'
description: 'One or more series to display in the annotation chart.'
type: 'propertyset[]'
required: true
default: []
order: 12
properties:
column:
label: 'Column Name'
description: 'Name of the column in the Data Source to use as the y-axis value for this series.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 1
label:
label: 'Label'
description: 'Display label for the series; if omitted, the column name will be used.'
placeholder: 'Label'
inlineJs: true
type: 'string'
order: 2
annotationTitleColumn:
label: 'Annotation Title Column Name'
description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 3
annotationTextColumn:
label: 'Annotation Text Column Name'
description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.'
placeholder: 'Column Name'
inlineJs: true
type: 'string'
order: 4
secondaryAxis:
label: 'Secondary Axis'
description: 'If true, places the series on a second axis on the left of the chart.'
inlineJs: true
type: 'boolean'
order: 5
options:
label: 'Options'
description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.'
type: 'propertyset'
required: false
inlineJs: true
properties:
allValuesSuffix:
label: 'All Values Suffix'
description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
defaultHidden: true
annotationsWidth:
label: 'Annotations Width'
description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.'
type: 'integer'
inlineJs: true
defaultHidden: true
displayAnnotations:
label: 'Display Annotations'
description: 'Controls whether annotations are displayed along with the chart.'
type: 'boolean'
inlineJs: true
default: true
defaultHidden: true
displayAnnotationsFilter:
label: 'Display Annotations Filter'
description: 'If set to true, the chart will display a filter control to filter annotations.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayDateBarSeparator:
label: 'Display Date Bar Separator'
description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.'
type: 'boolean'
inlineJs: true
default: false
defaultHidden: true
displayLegendDots:
label: 'Display Legend Dots'
description: 'If set to true, the chart will display dots next to the values in the legend text.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayLegendValues:
label: 'Display Legend Values'
description: 'If set to true, the chart will display the highlighted values in the legend.'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayRangeSelector:
label: 'Display Range Selector'
description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).'
type: 'boolean'
inlineJs: true
defaultHidden: true
displayZoomButtons:
label: 'Display Zoom Buttons'
description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).'
type: 'boolean'
inlineJs: true
defaultHidden: true
fill:
label: 'Fill'
description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.'
type: 'integer'
inlineJs: true
defaultHidden: true
focusTarget:
label: 'Focus Target'
description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".'
type: 'string'
inlineJs: true
defaultHidden: true
default: 'category'
options:
datum:
value: 'datum'
category:
value: 'category'
legendPosition:
label: 'Legend Position'
description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
sameRow:
value: 'sameRow'
newRow:
value: 'newRow'
max:
label: 'Maximum'
description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
min:
label: 'Minimum'
description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.'
type: 'number'
inlineJs: true
defaultHidden: true
scaleFormat:
label: 'Scale Format'
description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.'
placeholder: 'Format'
type: 'string'
inlineJs: true
defaultHidden: true
scaleType:
label: 'Scale Type'
description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.'
type: 'string'
inlineJs: true
defaultHidden: true
options:
maximized:
value: 'maximized'
fixed:
value: 'fixed'
allmaximized:
value: 'allmaximized'
allfixed:
value: 'allfixed'
thickness:
label: 'Thickness'
description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.'
placeholder: 'Thickness'
type: 'integer'
inlineJs: true
defaultHidden: true
zoomStartTime:
label: 'Zoom Start Time'
description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
zoomEndTime:
label: 'Zoom End Time'
description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.'
placeholder: 'Date Time'
type: 'datetime'
inlineJs: true
defaultHidden: true
order: 13
annotationEditing:
label: 'Built-In Annotation Editing'
description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.'
type: 'boolean'
required: false
default: false
order: 13
annotationKey:
label: 'Built-In Annotation Key'
description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 14
events:
label: 'Events'
description: 'Optional event handlers for various events.'
type: 'propertyset'
required: false
defaultHidden: true
order: 15
properties:
rangechange:
label: 'Range Change Event'
description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 1
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 20
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 20
# Common options
options:
displayAnnotations: true
# Undocumented "chart" options
chart:
focusTarget: 'category'
sample: ->
# Generate new Annotation Chart Widget
{
annotationKey: PI:KEY:<KEY>END_PI
}
# Theme-specific options
themes:
dark:
options:
dbackgroundColor: '#222222'
darkmetro:
options:
dbackgroundColor: '#202020'
chart:
name: 'chart'
label: 'Chart'
icon: 'fa-bar-chart-o'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
drilldownDataSource:
label: 'Drilldown Data Source'
description: 'The name of the Data Source providing drilldown data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: false
defaultHidden: true
options: datasourceOptions
order: 11
highchart:
label: 'Highchart Definition'
description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.'
type: 'json'
inlineJs: true
required: true
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 14
addShiftPoints:
label: 'Add/Shift Points'
description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.'
type: 'boolean'
default: false
required: false
order: 15
sample:
highchart:
series: [{
x: ''
y: ''
}
]
xAxis: [{
type: 'linear'
}
]
yAxis: [{
title:
text: 'Values'
}
]
themes:
light:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
drilldown:
activeAxisLabelStyle:
color: '#333'
textDecoration: 'none'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
gto:
chart:
style:
fontFamily: '"Open Sans", sans-serif'
plotOptions:
series:
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
pie:
borderWidth: 0
title:
style:
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
lineWidth: 0
tickWidth: 0
labels:
style:
fontSize: '11px'
title:
style:
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
symbolWidth: 40
dark:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
dark2:
colors: [
'#2095F0' #Blue
'#FF9A13' #Orange
'#FFFF13' #Yellow
'#A61DF1' #Purple
'#28F712' #Green
'#FE131E' #Red
'#D1D1D0' #Offwhite
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
dataLabels:
style:
color: '#999'
textShadow: false
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
darkmetro:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: true
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
charcoal:
colors: [
'#007D9D' #Blue
'#82B93A' #Green
'#E3AAD5' #Pink
'#EBDC46' #Yellow
'#AC5B41' #Red
'#D1D1D0' #Offwhite
'#B07288' #Purple
]
chart:
backgroundColor: null #'#333333'
borderWidth: 0
borderRadius: 0
plotBackgroundColor: null
plotShadow: false
plotBorderWidth: 0
style:
fontFamily: '"Open Sans", sans-serif'
color: '#FFF'
drilldown:
activeAxisLabelStyle:
color: '#999'
textDecoration: 'none'
activeDataLabelStyle:
color: '#999'
textDecoration: 'none'
title:
style:
color: '#FFF'
font: '16px "Lato", sans-serif'
fontWeight: 'bold'
subtitle:
style:
color: '#FFF'
font: '12px "Lato", sans-serif'
xAxis:
gridLineWidth: 0
lineColor: '#999'
tickColor: '#999'
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
yAxis:
alternateGridColor: null
minorTickInterval: null
gridLineColor: 'rgba(255, 255, 255, .1)'
minorGridLineColor: 'rgba(255,255,255,0.07)'
lineWidth: 0
tickWidth: 0
labels:
style:
color: '#999'
fontSize: '11px'
title:
style:
color: '#EEE'
fontSize: '14px'
fontWeight: '300'
legend:
borderRadius: 0
borderWidth: 0
itemStyle:
color: '#CCC'
itemHoverStyle:
color: '#FFF'
itemHiddenStyle:
color: '#333'
symbolWidth: 40
labels:
style:
color: '#CCC'
tooltip:
backgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, 'rgba(96, 96, 96, .8)']
[1, 'rgba(16, 16, 16, .8)']
]
borderWidth: 0
style:
color: '#FFF'
plotOptions:
series:
dataLabels:
style:
color: '#999'
textShadow: false
shadow: false
marker:
enabled: false
states:
hover:
enabled: true
bar:
borderWidth: 0
column:
borderWidth: 0
line:
dataLabels:
color: '#CCC'
marker:
lineColor: '#333'
pie:
borderWidth: 0
dataLabels:
color: '#999'
fontSize: '14px'
spline:
marker:
lineColor: '#333'
scatter:
marker:
lineColor: '#333'
candlestick:
lineColor: 'white'
toolbar:
itemStyle:
color: '#CCC'
navigation:
buttonOptions:
symbolStroke: '#DDDDDD'
hoverSymbolStroke: '#FFFFFF'
theme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#606060']
[0.6, '#333333']
]
stroke: '#000000'
# scroll charts
rangeSelector:
buttonTheme:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
stroke: '#000000'
style:
color: '#CCC'
fontWeight: 'bold'
states:
hover:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#BBB']
[0.6, '#888']
]
stroke: '#000000'
style:
color: 'white'
select:
fill:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.1, '#000']
[0.3, '#333']
]
stroke: '#000000'
style:
color: 'yellow'
inputStyle:
backgroundColor: '#333'
color: 'silver'
labelStyle:
color: 'silver'
navigator:
handles:
backgroundColor: '#666'
borderColor: '#AAA'
outlineColor: '#CCC'
maskFill: 'rgba(16, 16, 16, 0.5)'
series:
color: '#7798BF'
lineColor: '#A6C7ED'
scrollbar:
barBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
barBorderColor: '#CCC'
buttonArrowColor: '#CCC'
buttonBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0.4, '#888']
[0.6, '#555']
]
buttonBorderColor: '#CCC'
rifleColor: '#FFF'
trackBackgroundColor:
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }
stops: [
[0, '#000']
[1, '#333']
]
trackBorderColor: '#666'
clock:
name: 'clock'
label: 'Clock'
icon: 'fa-clock-o'
properties:
format:
label: 'Format'
description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats'
type: 'string'
default: 'dddd, MMMM Do YYYY, h:mm:ss a'
required: false
order: 10
timezone:
label: 'Time Zone'
description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone'
required: false
type: 'string'
order: 11
header:
name: 'header'
label: 'Header'
icon: 'fa-header'
properties:
headerTitle:
label: 'Header Title'
description: 'Contains properties for displaying a title in the header.'
type: 'propertyset'
order: 10
properties:
showTitle:
label: 'Show Title'
description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 1
showPageName:
label: 'Show Page Name'
description: 'Determines whether the current page name will be shown as part of the title.'
type: 'boolean'
default: true
required: false
inlineJs: true
order: 2
pageNameSeparator:
label: 'Page Name Separator'
description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.'
type: 'string'
required: false
default: ''
inlineJs: true
defaultHidden: true
order: 3
titleSize:
label: 'Title Size'
description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 5
logoUrl:
label: 'Logo URL'
description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.'
type: 'string'
required: false
inlineJs: true
order: 10
logoSize:
label: 'Logo Size'
description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.'
type: 'string'
required: false
inlineJs: true
order: 11
link:
label: 'Link'
description: 'If set, makes the Logo and Title a link to this URL.'
type: 'string'
required: false
inlineJs: true
order: 20
parameters:
label: 'Parameters'
description: 'Contains properties for displaying Dashboard Parameters in the header.'
type: 'propertyset'
order: 20
properties:
showParameters:
label: 'Show Parameters'
description: 'Determines whether Parameters will be shown.'
type: 'boolean'
default: false
required: false
inlineJs: true
order: 1
showUpdateButton:
label: 'Show Update Button'
description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.'
type: 'boolean'
default: false
required: false
order: 2
updateButtonLabel:
label: 'Update Button Label'
description: 'Customizes the label for the Update button, if shown.'
type: 'string'
default: 'Update'
defaultHidden: true
required: false
order: 2
updateEvent:
label: 'Update Button Click Event'
description: 'This event occurs when the Update button is clicked, if shown.'
type: 'editor'
editorMode: 'javascript'
required: false
order: 10
parametersIncluded:
label: 'Included Parameters'
description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.'
type: 'string[]'
required: false
defaultHidden: true
order: 11
customHtml:
label: 'HTML Content'
description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.'
type: 'editor'
editorMode: 'html'
required: false
inlineJs: true
order: 30
html:
name: 'html'
label: 'HTML'
icon: 'fa-html5'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
html:
label: 'HTML'
description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 11
preHtml:
label: 'Pre-HTML'
description: 'Optional, contains HTML markup which is displayed before the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 12
postHtml:
label: 'Post-HTML'
description: 'Optional, contains HTML markup which is displayed after the main body of HTML.'
type: 'editor'
editorMode: 'html'
required: false
default: ''
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 15
iframe:
name: 'iframe'
label: 'iFrame'
icon: 'fa-desktop'
properties:
url:
label: 'Url'
description: 'Specifies the URL to be loaded within the Widget.'
type: 'string'
placeholder: 'Url'
required: true
default: 'http://www.expedia.com'
order: 10
refresh:
label: 'Refresh'
description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 11
image:
name: 'image'
label: 'Image'
icon: 'fa-image-o'
properties:
images:
label: 'Images'
singleLabel: 'Image'
description: 'One or more Images to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 10
properties:
url:
label: 'URL'
description: 'URL to the image to be displayed.'
placeholder: 'Url'
inlineJs: true
required: true
type: 'string'
order: 1
link:
label: 'Link'
description: 'Optional, specifies a URL that will be opened if the image is clicked on.'
placeholder: 'URL'
type: 'url'
inlineJs: true
required: false
order: 13
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the image.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 2
backgroundSize:
label: 'Background-Size'
description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
options:
auto:
value: 'auto'
contain:
value: 'contain'
cover:
value: 'cover'
'100%':
value: '100%'
order: 3
backgroundPosition:
label: 'Background Position'
description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'center'
defaultHidden: true
options:
center:
value: 'center'
top:
value: 'top'
bottom:
value: 'bottom'
left:
value: 'left'
right:
value: 'right'
order: 4
backgroundColor:
label: 'Background Color'
description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
backgroundRepeat:
label: 'Background Repeat'
description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.'
type: 'string'
inlineJs: true
required: false
default: 'no-repeat'
defaultHidden: true
options:
'no-repeat':
value: 'no-repeat'
'repeat':
value: 'repeat'
'repeat-x':
value: 'repeat-x'
'repeat-y':
value: 'repeat-y'
'space':
value: 'space'
'round':
value: 'round'
order: 6
filters:
label: 'Filters'
description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 7
duration:
label: 'Auto-Rotate Duration'
description: 'Optional number of seconds; enables rotating among a set of images periodically.'
placeholder: 'Seconds'
type: 'integer'
default: 0
required: false
order: 11
javascript:
name: 'javascript'
label: 'JavaScript'
icon: 'fa-cogs'
properties:
dataSource:
label: 'Data Source'
description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
order: 10
functionName:
label: 'Function Name'
description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot'
placeholder: 'Function Name'
type: 'string'
required: true
order: 11
refresh:
label: 'Refresh'
description: 'Optional; enables re-invoking the javascript object periodically every N seconds.'
placeholder: 'Seconds'
type: 'integer'
required: false
order: 12
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 13
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
order: 14
json:
name: 'json',
label: 'JSON',
icon: 'fa-cog',
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
linkedWidget:
name: 'linkedWidget'
label: 'Linked Widget'
icon: 'fa-link'
properties:
linkedWidget:
label: 'Linked Widget'
description: 'Selects another Widget in this Dashboard to link.'
type: 'string'
required: true
options: linkedWidgetOptions
order: 10
number:
name: 'number'
label: 'Number'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
numbers:
label: 'Numbers'
singleLabel: 'number'
description: 'One or more Numbers to display in this widget.'
type: 'propertyset[]'
required: true
default: []
order: 11
properties:
number:
label: 'Number'
description: 'Number value or expression.'
placeholder: 'Value'
inlineJs: true
required: false
type: 'string'
order: 1
prefix:
label: 'Prefix'
description: 'Optional; specifies a prefix to append to the number.'
placeholder: 'Prefix'
type: 'string'
inlineJs: true
order: 2
suffix:
label: 'Suffix'
description: 'Optional; specifies a suffix to append to the number.'
placeholder: 'Suffix'
type: 'string'
inlineJs: true
order: 3
color:
label: 'Color'
description: 'Sets the color of the number.'
placeholder: 'Color'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 4
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the number.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 5
icon:
label: 'Icon'
description: 'Optional Font Awesome icon class to be displayed with the number.'
placeholder: 'Icon Class'
inlineJs: true
type: 'string'
defaultHidden: true
order: 6
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
order: 7
iconTooltip:
label: 'IconTooltip'
description: 'Sets the tooltip of the icon.'
placeholder: 'Icon Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 8
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 9
orientation:
label: 'Orientation'
description: 'Controls the direction in which the numbers are arranged.'
type: 'string'
required: false
default: 'vertical'
options:
vertical:
value: 'vertical'
horizontal:
value: 'horizontal'
order: 12
autoSize:
label: 'Auto-Size Numbers'
description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.'
type: 'boolean'
required: false
default: true
order: 13
link:
label: 'Link'
description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.'
placeholder: 'URL'
type: 'url'
required: false
order: 14
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
qrcode:
name: 'qrcode'
label: 'QRcode'
icon: 'fa-cogs'
properties:
text:
label: 'Text'
description: 'Text content of the generated QR code.'
placeholder: 'QR Code Contents'
type: 'string'
required: false
order: 10
maxSize:
label: 'Max Size'
description: 'Maximum height/width of the QR code.'
type: 'integer'
required: false
order: 11
useUrl:
label: 'Use URL'
description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.'
type: 'boolean'
default: false
required: false
order: 12
dataSource:
label: 'Data Source'
description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.'
placeholder: 'Data Source name'
type: 'string'
required: false
options: datasourceOptions
defaultHidden: true
order: 13
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
defaultHidden: true
order: 14
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
placeholder: 'Column name'
type: 'string[]'
inlineJs: true
required: false
defaultHidden: true
order: 15
colorDark:
label: 'Dark Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#000000'
required: false
defaultHidden: true
order: 16
colorLight:
label: 'Light Color'
description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.'
placeholder: 'CSS color or hex color code'
type: 'string'
default: '#ffffff'
required: false
defaultHidden: true
order: 17
sample:
text: 'hello'
stoplight:
name: 'stoplight'
label: 'Stoplight'
icon: 'fa-cog'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source Name'
type: 'string'
required: false
options: datasourceOptions
order: 10
rules:
label: 'Rules'
description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled'
type: 'propertyset'
required: true
order: 11
properties:
green:
label: 'Green'
description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 3
yellow:
label: 'Yellow'
description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 2
red:
label: 'Red'
description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.'
type: 'string'
placeholder: 'Rule Expression'
inlineJs: true
order: 1
tooltip:
label: 'Tooltip'
description: 'Sets the tooltip of the stoplight.'
placeholder: 'Tooltip'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 12
filters:
label: 'Filters'
description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row"
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 15
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 16
table:
name: 'table'
label: 'Table'
icon: 'fa-table'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
columns:
label: 'Columns'
singleLabel: 'column'
description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.'
type: 'propertyset[]'
inlineJs: true
properties:
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
order: 1
label:
label: 'Label'
description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
order: 2
text:
label: 'Text'
description: 'Overrides the text in the cell using this value as an expression.'
type: 'string'
inlineJs: true
defaultHidden: true
order: 3
tooltip:
label: 'Tooltip'
description: 'Optionally specifies a tooltip to display for each cell in the column.'
type: 'string'
inlineJs: true
defaultHidden: true
headerTooltip:
label: 'Header Tooltip'
description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.'
type: 'string'
inlineJs: true
defaultHidden: true
onClick:
label: 'Click Event'
description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
link:
label: 'Link'
description: 'If provided, the cell text will be made into a link rather than plain text.'
type: 'url'
inlineJs: true
defaultHidden: true
openLinksInNewWindow:
label: 'Open Links in New Window'
description: 'If true, links will open in a new browser window; this is the default.'
type: 'boolean'
default: true
defaultHidden: true
numeralformat:
label: 'Numeral Format'
description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.'
type: 'string'
inlineJs: true
defaultHidden: true
image:
label: 'Image'
description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.'
type: 'url'
inlineJs: true
defaultHidden: true
imageHeight:
label: 'Image Height'
description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.'
type: 'string'
inlineJs: true
defaultHidden: true
icon:
label: 'Icon'
description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.'
type: 'string'
inlineJs: true
defaultHidden: true
iconColor:
label: 'Icon Color'
description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").'
type: 'string'
inlineJs: true
defaultHidden: true
border:
label: 'Border'
description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.'
type: 'string'
inlineJs: true
defaultHidden: true
group:
label: 'Column Group'
description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.'
type: 'string'
inlineJs: true
defaultHidden: true
groupRows:
label: 'Group Rows'
description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.'
type: 'boolean'
default: false
defaultHidden: true
columnSortFunction:
label: 'Column Sort Function'
description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".'
type: 'string'
inlineJs: true
defaultHidden: true
columnsIgnored:
label: 'Columns Ignored'
description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.'
type: 'string[]'
required: false
inlineJs: false
defaultHidden: true
order: 10
sample:
name: ''
rules:
label: 'Rules'
singleLabel: 'rule'
description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.'
type: 'propertyset[]'
inlineJs: true
properties:
rule:
label: 'Rule'
description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.'
type: 'string'
required: true
inlineJs: true
order: 1
columns:
label: 'Columns Affected'
description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.'
type: 'string[]'
required: false
order: 2
columnsIgnored:
label: 'Columns Ignored'
description: 'Optionally specifies an array of column names that the rule does NOT apply to.'
type: 'string[]'
required: false
order: 3
name:
label: 'Name'
description: 'Indicates the name of the data source field to use for this column.'
type: 'string'
inlineJs: true
defaultHidden: true
'font-weight':
label: 'Font-Weight (CSS)'
description: 'CSS setting for `font-weight`'
type: 'string'
inlineJs: true
defaultHidden: true
color:
label: 'Color (CSS)'
description: 'CSS setting for `color`'
type: 'string'
inlineJs: true
defaultHidden: true
'background-color':
label: 'Background Color (CSS)'
description: 'CSS setting for `background-color`'
type: 'string'
inlineJs: true
defaultHidden: true
order: 11
sample:
rule: 'true'
freezeHeaders:
label: 'Freeze Headers'
description: 'Enables frozen headers at the top of the widget when scrolling'
type: 'boolean'
default: false
required: false
order: 12
omitHeaders:
label: 'Omit Headers'
description: 'Disables the table header row'
type: 'boolean'
default: false
required: false
order: 13
enableSort:
label: 'Enable Sort'
description: 'Enable or disable user sort controls'
type: 'boolean'
default: true
required: false
order: 14
rowHeight:
label: 'Minimum Row Height'
description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.'
type: 'integer'
required: false
order: 15
pagination:
label: 'Pagination'
description: 'Controls pagination of the Table.'
type: 'propertyset'
required: false
defaultHidden: true
order: 16
properties:
enabled:
label: 'Enable Pagination'
description: 'Enables or disables pagination for this Table Widget.'
type: 'boolean'
default: false
required: false
order: 1
autoItemsPerPage:
label: 'Auto Items Per Page'
description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.'
type: 'boolean'
default: true
required: false
order: 2
itemsPerPage:
label: 'Items Per Page'
description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.'
type: 'integer'
required: false
order: 3
belowPagerMessage:
label: 'Below Pager Message'
description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.'
type: 'string'
required: false
order: 4
filters:
label: 'Filters'
description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.'
type: 'hash'
inlineJsKey: true
inlineJsValue: true
required: false
order: 17
sortBy:
label: 'Sort By'
description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.'
type: 'string[]'
inlineJs: true
required: false
placeholder: 'Column name'
order: 18
sortFunction:
label: 'Sort Function'
description: 'Optional, specifies an alternative function to the default sort implementation.'
placeholder: 'JavaScript Function'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 19
onSort:
label: 'Sort Event'
description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.'
type: 'editor'
editorMode: 'javascript'
required: false
defaultHidden: true
order: 20
tableau:
name: 'tableau'
label: 'Tableau'
icon: 'fa-cog'
properties:
params:
label: 'Parameters'
description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.'
type: 'hash'
required: true
editorMode: 'json'
order: 10
treemap:
name: 'treemap'
label: 'Treemap'
icon: 'fa-tree'
properties:
dataSource:
label: 'Data Source'
description: 'The name of the Data Source providing data for this Widget.'
placeholder: 'Data Source name'
type: 'string'
required: true
options: datasourceOptions
order: 10
labelProperty:
label: 'Label Property'
description: 'The name of the property to use as the label of each item.'
type: 'string'
inlineJs: true
required: false
default: 'name'
defaultHidden: true
order: 11
valueProperty:
label: 'Value Property'
description: 'The name of the property to use to calculate the size of each item.'
type: 'string'
inlineJs: true
required: false
default: 'value'
defaultHidden: true
order: 12
valueDescription:
label: 'Value Description'
description: 'A short description of the property used to calculate the size of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 13
valueFormat:
label: 'Value Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
order: 14
colorProperty:
label: 'Color Property'
description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.'
type: 'string'
inlineJs: true
required: false
default: 'color'
order: 15
colorDescription:
label: 'Color Description'
description: 'A short description of the property used to calculate the color of each item. Used in tooltips.'
type: 'string'
inlineJs: true
required: false
defaultHidden: true
order: 16
colorFormat:
label: 'Color Format'
description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.'
type: 'string'
default: ',.2f'
required: false
defaultHidden: true
inlineJs: true
options:
default:
value: '0,0.[0]'
percent:
value: '0,0%'
integer:
value: '0,0'
currency:
value: '$0,0'
large:
value: '0a'
order: 17
colorStops:
label: 'Color Stops'
singleLabel: 'color'
description: 'Specifies a list of color stops used to build a gradient.'
type: 'propertyset[]'
inlineJs: true
properties:
value:
label: 'Value'
description: 'The numerical value assigned to this color stop.'
type: 'number'
required: true
inlineJs: true
order: 1
color:
label: 'Color'
description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.'
type: 'string'
required: false
inlineJs: true
order: 2
order: 18
showLegend:
label: 'Show Legend'
description: 'Enables or disables the color legend.'
type: 'boolean'
default: true
required: false
order: 19
legendHeight:
label: 'Legend Height'
description: 'Specifies the height of the legend in pixels.'
type: 'number'
default: 30
required: false
defaultHidden: true
order: 20
youtube:
name: 'youtube'
label: 'YouTube'
icon: 'fa-youtube'
properties:
videoId:
label: 'Video / Playlist ID'
description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.'
type: 'string'
inlineJs: true
placeholder: 'ID'
required: true
order: 10
autoplay:
label: 'Auto-Play'
description: 'If true, automatically plays the video when the Widget is loaded.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 13
loop:
label: 'Loop'
description: 'If true, automatically loops the video when it completes.'
type: 'boolean'
inlineJs: true
default: true
required: false
order: 14
enableKeyboard:
label: 'Enable Keyboard'
description: 'If true, enables keyboard controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 15
enableControls:
label: 'Enable Controls'
description: 'If true, enables on-screen video controls which are disabled by default.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 16
showAnnotations:
label: 'Show Annotations'
description: 'If true, displays available annotations over the video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 17
showRelated:
label: 'Show Related'
description: 'If true, displays related videos at the end of this video.'
type: 'boolean'
inlineJs: true
default: false
required: false
defaultHidden: true
order: 18
}
# Copy Theme options to inherited locations
exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options
exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options
# Copy Style options to inherited locations
exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options
# Table Widget: Column properties duplicated in Rules:
tableProperties = exports.widgets.table.properties
_.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label')
# Copy some chart themes
exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light
# Populate Help tags with properties
helpDashboards = _.find(exports.help, { name: 'Dashboards' })
helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name
helpDataSources = _.find(exports.help, { name: 'Data Sources' })
helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name
helpWidgets = _.find(exports.help, { name: 'Widgets' })
helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name
propertyMapHelper = (value, name) ->
v = _.cloneDeep value
v.name = name
return v
# Add Widget and Data Source help pages
helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) ->
{
name: dataSource.label || dataSource.value
path: '/partials/help/datasources/' + dataSource.value + '.html'
tags: _.map dataSource.properties, propertyMapHelper
}
helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) ->
{
name: widget.label || widget.name
path: '/widgets/' + widget.name + '/help.html'
tags: _.map widget.properties, propertyMapHelper
}
return exports
|
[
{
"context": "\n inputOptions :\n name : 'username'\n forceCase : 'lowercase'\n plac",
"end": 346,
"score": 0.9930529594421387,
"start": 338,
"tag": "USERNAME",
"value": "username"
},
{
"context": "pe : 'password'\n placeholde... | client/landing/site.landing/coffee/login/loginform.coffee | lionheart1022/koding | 0 | kd = require 'kd'
JView = require './../core/jview'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : 'Password'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green koding'
icon : 'koding'
loader : yes
type : 'submit'
attributes :
testpath : 'login-button'
@gitlabButton = new kd.ButtonView
title : 'SIGN IN WITH GITLAB'
style : 'solid medium green gitlab'
icon : 'gitlab'
loader :
color : '#48BA7D'
callback : ->
kd.singletons.oauthController.redirectToOauth { provider: 'gitlab' }
@gitlabLogin = new JView
cssClass : 'gitlab hidden'
pistachioParams : { @gitlabButton }
pistachio : '''
<div class='or'><span>or</span></div>
{{> gitlabButton}}
</div>
'''
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
{{> @gitlabLogin}}
'''
| 84684 | kd = require 'kd'
JView = require './../core/jview'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : '<PASSWORD>'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green koding'
icon : 'koding'
loader : yes
type : 'submit'
attributes :
testpath : 'login-button'
@gitlabButton = new kd.ButtonView
title : 'SIGN IN WITH GITLAB'
style : 'solid medium green gitlab'
icon : 'gitlab'
loader :
color : '#48BA7D'
callback : ->
kd.singletons.oauthController.redirectToOauth { provider: 'gitlab' }
@gitlabLogin = new JView
cssClass : 'gitlab hidden'
pistachioParams : { @gitlabButton }
pistachio : '''
<div class='or'><span>or</span></div>
{{> gitlabButton}}
</div>
'''
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
{{> @gitlabLogin}}
'''
| true | kd = require 'kd'
JView = require './../core/jview'
LoginViewInlineForm = require './loginviewinlineform'
LoginInputView = require './logininputview'
module.exports = class LoginInlineForm extends LoginViewInlineForm
constructor: ->
super
@username = new LoginInputView
inputOptions :
name : 'username'
forceCase : 'lowercase'
placeholder : 'Username or Email'
testPath : 'login-form-username'
attributes :
testpath : 'login-form-username'
validate :
rules :
required : yes
messages :
required : 'Please enter a username.'
@password = new LoginInputView
inputOptions :
name : 'password'
type : 'password'
placeholder : 'PI:PASSWORD:<PASSWORD>END_PI'
testPath : 'login-form-password'
attributes :
testpath : 'login-form-password'
validate :
rules :
required : yes
messages :
required : 'Please enter your password.'
@tfcode = new LoginInputView
inputOptions :
name : 'tfcode'
placeholder : 'Two-Factor Authentication Code'
testPath : 'login-form-tfcode'
attributes :
testpath : 'login-form-tfcode'
@tfcode.hide()
@button = new kd.ButtonView
title : 'SIGN IN'
style : 'solid medium green koding'
icon : 'koding'
loader : yes
type : 'submit'
attributes :
testpath : 'login-button'
@gitlabButton = new kd.ButtonView
title : 'SIGN IN WITH GITLAB'
style : 'solid medium green gitlab'
icon : 'gitlab'
loader :
color : '#48BA7D'
callback : ->
kd.singletons.oauthController.redirectToOauth { provider: 'gitlab' }
@gitlabLogin = new JView
cssClass : 'gitlab hidden'
pistachioParams : { @gitlabButton }
pistachio : '''
<div class='or'><span>or</span></div>
{{> gitlabButton}}
</div>
'''
activate: ->
@username.setFocus()
resetDecoration: ->
@username.resetDecoration()
@password.resetDecoration()
@tfcode.hide()
pistachio: ->
'''
<div>{{> @username}}</div>
<div>{{> @password}}</div>
<div>{{> @tfcode}}</div>
<div>{{> @button}}</div>
{{> @gitlabLogin}}
'''
|
[
{
"context": "\n\t\tpagingType: \"numbers\"\n\n\t}\n\n\tif flowId\n\t\tkey = \"instanceFlow\" + flowId\n\n\t\toptions.name = key\n\n\t\tTabularTables.",
"end": 9515,
"score": 0.9662022590637207,
"start": 9503,
"tag": "KEY",
"value": "instanceFlow"
},
{
"context": "sTabularOptions = (... | creator/packages/steedos-workflow/tabular.coffee | yicone/steedos-platform | 42 | Steedos.subs["InstanceTabular"] = new SubsManager()
_handleListFields = (fields) ->
ins_fields = new Array();
fields?.forEach (f)->
if f.type == 'table'
console.log 'ignore opinion field in table'
else if f.type == 'section'
f?.fields?.forEach (f1)->
ins_fields.push f1
else
ins_fields.push f
return ins_fields
updateTabularTitle = ()->
# 如果columns有加减,请修改Template.instance_list._tableColumns 函数
instancesListTableTabular = (flowId, fields)->
options = {
name: "instances",
collection: db.instances,
pub: "instance_tabular",
onUnload: ()->
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
drawCallback: (settings)->
emptyTd = $(".dataTables_empty")
if emptyTd.length
emptyTd[0].colSpan = "6"
if !Steedos.isMobile() && !Steedos.isPad()
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
$(".instance-list").scrollTop(0).ready ->
$(".instance-list").perfectScrollbar("update")
else
$(".instance-list").scrollTop(0)
title = t "pager_input_hint"
ellipsisLink = settings.oInstance.parent().find('.paging_numbers .pagination .disabled a')
ellipsisLink.attr("title", title).css("cursor", "pointer").click ->
if !$(this).find('input').length
input = $('<input class="paginate_input form-control input-sm" type="text" style="border: none; padding:0 2px;"/>')
if Steedos.isMobile()
input.css({
width:"52px"
height: "20px"
})
else
input.css({
width:"52px"
height: "16px"
})
input.attr("title", title).attr("placeholder", title)
$(this).empty().append input
goPage = (index)->
if index > 0
pages = Math.ceil(settings.fnRecordsDisplay() / settings._iDisplayLength)
if index > pages
# 页码超出索引时跳转到最后一页
index = pages
index--
settings.oInstance.DataTable().page(index).draw('page')
input.blur (e)->
currentPage = $(this).val()
goPage currentPage
$(this).parent().html '...'
input.keydown (e)->
if(e.keyCode.toString() == "13")
currentPage = $(this).val()
goPage currentPage
createdRow: (row, data, dataIndex) ->
if Meteor.isClient
if data._id == FlowRouter.current().params.instanceId
row.setAttribute("class", "selected")
columns: [
{
data: "_id",
orderable: false
render: (val, type, doc) ->
modifiedString = moment(doc.modified).format('YYYY-MM-DD');
modified = doc.modified
if Session.get("box") == 'inbox' && doc.state != 'draft'
modified = doc.start_date || doc.modified
if Session.get("box") == 'outbox' || Session.get("box") == 'monitor'
modified = doc.submit_date || doc.submit_date
modifiedFromNow = Steedos.momentReactiveFromNow(modified);
flow_name = doc.flow_name
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
if Session.get("box") != 'draft' && doc.current_step_name
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
step_current_name_view = "<div class='flow-name'>#{flow_name}</div>"
agent_view = "";
if doc.agent_user_name && Session.get("box") == 'inbox'
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
isFavoriteSelected = Favorites.isRecordSelected("instances", doc._id)
if Favorites.isRecordSelected("instances", doc._id)
unread = '<i class="ion ion-ios-star-outline instance-favorite-selected"></i>'
else if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIcon = ""
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}
<span>#{doc.applicant_name}</span>
</div>
<div class='instance-detail'>#{step_current_name_view}
<span class='instance-modified' title='#{modifiedString}'>#{modifiedFromNow}</span>
</div>
"""
},
{
data: "applicant_organization_name",
title: t("instances_applicant_organization_name"),
visible: false,
},
{
data: "name",
title: t("instances_name"),
render: (val, type, doc) ->
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
agent_view = "";
if doc.agent_user_name
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}</div>
"""
visible: false,
orderable: false
},
{
data: "applicant_name",
title: t("instances_applicant_name"),
visible: false,
orderable: false
},
{
data: "submit_date",
title: t("instances_submit_date"),
render: (val, type, doc) ->
if doc.submit_date
return moment(doc.submit_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "flow_name",
title: t("instances_flow"),
visible: false,
orderable: false
},
{
data: "current_step_name",
title: t("instances_step_current_name"),
render: (val, type, doc) ->
if doc.state == "completed"
judge = doc.final_decision || "approved"
step_current_name = doc.current_step_name || ''
cc_tag = ''
if doc.cc_count > 0
cc_tag = TAPi18n.__('cc_tag')
return """
<div class="step-current-state #{judge}">#{step_current_name}#{cc_tag}</div>
"""
visible: false,
orderable: false
},
{
data: "modified",
title: t("instances_modified"),
render: (val, type, doc) ->
return moment(doc.modified).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "start_date",
title: t("instances_start_date"),
render: (val, type, doc) ->
if doc.start_date
return moment(doc.start_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "my_finish_date",
render: (val, type, doc) ->
if doc.my_finish_date
return moment(doc.my_finish_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "modified",
visible: false
},
{
data: "keywords",
visible: false
},
{
data: "is_archived",
render: (val, type, doc) ->
if doc?.values?.record_need && doc.values.record_need == "true"
if doc?.is_archived
return t("YES")
return t("NO")
visible: false
orderable: false
}
],
dom: do ->
# 手机上不显示一页显示多少条记录选项
if Steedos.isMobile()
'tp'
else
'tpl'
order: [[4, "desc"]],
extraFields: ["form", "flow", "inbox_users", "state", "space", "applicant", "form_version",
"flow_version", "is_cc", "cc_count", "is_read", "current_step_name", "values", "keywords", "final_decision", "flow_name", "is_hidden", "agent_user_name"],
lengthChange: true,
lengthMenu: [10,15,20,25,50,100],
pageLength: 10,
info: false,
searching: true,
responsive:
details: false
autoWidth: false,
changeSelector: (selector, userId) ->
unless userId
return {_id: -1}
space = selector.space
unless space
if selector?.$and?.length > 0
space = selector.$and.getProperty('space')[0]
unless space
return {_id: -1}
space_user = db.space_users.findOne({user: userId, space: space}, {fields: {_id: 1}})
unless space_user
return {_id: -1}
return selector
pagingType: "numbers"
}
if flowId
key = "instanceFlow" + flowId
options.name = key
TabularTables.instances.fields = fields
ins_fields = _handleListFields TabularTables.instances.fields
ins_fields.forEach (f)->
if f.type != 'table' && f.is_list_display
options.columns.push
data: (f.name || f.code),
title: t(f.name || f.code),
visible: false,
orderable: false
render: (val, type, doc) ->
values = doc.values || {}
value = values[f.code]
switch f.type
when 'user'
value = value?.name
when 'group'
value = value?.fullname
when 'date'
if value
value = moment(value).format('YYYY-MM-DD')
when 'dateTime'
if value
value = moment(value).format('YYYY-MM-DD HH:mm')
when 'checkbox'
if value == true || value == 'true'
value = TAPi18n.__("form_field_checkbox_yes");
else
value = TAPi18n.__("form_field_checkbox_no");
when 'odata'
if value
if _.isArray(value)
value = _.pluck(value, '@label').toString()
else
value = value['@label']
return value
return options;
Meteor.startup ()->
TabularTables.instances = new Tabular.Table instancesListTableTabular()
GetBoxInstancesTabularOptions = (box, flowId, fields)->
key = "instanceFlow" + box + flowId
if box == "inbox"
options = _get_inbox_instances_tabular_options(flowId, fields)
else if box == "outbox"
options = _get_outbox_instances_tabular_options(flowId, fields)
else
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
if flowId
options.name = key
return options
_get_inbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
options.order = [[8, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': false
'_approve.handler': userId,
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'start_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_start_date": {$first: "$_approve.start_date"}}
ag_sort = 'approve_start_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.inbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("inbox")
_get_outbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "outbox_instances"
options.order = [[9, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': true
$or: [{'_approve.handler': userId},{'_approve.user': userId}]
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'my_finish_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_finish_date": {$last: "$_approve.finish_date"}}
ag_sort = 'approve_finish_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.outbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("outbox")
if Meteor.isClient
TabularTables.flowInstances = new ReactiveVar()
Meteor.startup ()->
Tracker.autorun (c) ->
if Meteor.isClient && !Steedos.isMobile()
if Session.get("flowId") && Session.get("box") != 'draft'
Meteor.call "newInstancesListTabular", Session.get("box"), Session.get("flowId"), (error, result) ->
newInstancesListTabular Session.get("box"), Session.get("flowId"), result
Template.instance_list._changeOrder()
newInstancesListTabular = (box, flowId, fields)->
if !fields
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
fields = _handleListFields fields
if fields?.filterProperty("is_list_display", true)?.length > 0
key = "instanceFlow" + box + flowId
if Meteor.isClient
TabularTables.flowInstances.set(new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields))
else
new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields)
console.log "new TabularTables ", key
if Meteor.isServer
Meteor.methods
newInstancesListTabular: (box, flowId)->
newInstancesListTabular(box, flowId)
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
return fields
| 123241 | Steedos.subs["InstanceTabular"] = new SubsManager()
_handleListFields = (fields) ->
ins_fields = new Array();
fields?.forEach (f)->
if f.type == 'table'
console.log 'ignore opinion field in table'
else if f.type == 'section'
f?.fields?.forEach (f1)->
ins_fields.push f1
else
ins_fields.push f
return ins_fields
updateTabularTitle = ()->
# 如果columns有加减,请修改Template.instance_list._tableColumns 函数
instancesListTableTabular = (flowId, fields)->
options = {
name: "instances",
collection: db.instances,
pub: "instance_tabular",
onUnload: ()->
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
drawCallback: (settings)->
emptyTd = $(".dataTables_empty")
if emptyTd.length
emptyTd[0].colSpan = "6"
if !Steedos.isMobile() && !Steedos.isPad()
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
$(".instance-list").scrollTop(0).ready ->
$(".instance-list").perfectScrollbar("update")
else
$(".instance-list").scrollTop(0)
title = t "pager_input_hint"
ellipsisLink = settings.oInstance.parent().find('.paging_numbers .pagination .disabled a')
ellipsisLink.attr("title", title).css("cursor", "pointer").click ->
if !$(this).find('input').length
input = $('<input class="paginate_input form-control input-sm" type="text" style="border: none; padding:0 2px;"/>')
if Steedos.isMobile()
input.css({
width:"52px"
height: "20px"
})
else
input.css({
width:"52px"
height: "16px"
})
input.attr("title", title).attr("placeholder", title)
$(this).empty().append input
goPage = (index)->
if index > 0
pages = Math.ceil(settings.fnRecordsDisplay() / settings._iDisplayLength)
if index > pages
# 页码超出索引时跳转到最后一页
index = pages
index--
settings.oInstance.DataTable().page(index).draw('page')
input.blur (e)->
currentPage = $(this).val()
goPage currentPage
$(this).parent().html '...'
input.keydown (e)->
if(e.keyCode.toString() == "13")
currentPage = $(this).val()
goPage currentPage
createdRow: (row, data, dataIndex) ->
if Meteor.isClient
if data._id == FlowRouter.current().params.instanceId
row.setAttribute("class", "selected")
columns: [
{
data: "_id",
orderable: false
render: (val, type, doc) ->
modifiedString = moment(doc.modified).format('YYYY-MM-DD');
modified = doc.modified
if Session.get("box") == 'inbox' && doc.state != 'draft'
modified = doc.start_date || doc.modified
if Session.get("box") == 'outbox' || Session.get("box") == 'monitor'
modified = doc.submit_date || doc.submit_date
modifiedFromNow = Steedos.momentReactiveFromNow(modified);
flow_name = doc.flow_name
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
if Session.get("box") != 'draft' && doc.current_step_name
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
step_current_name_view = "<div class='flow-name'>#{flow_name}</div>"
agent_view = "";
if doc.agent_user_name && Session.get("box") == 'inbox'
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
isFavoriteSelected = Favorites.isRecordSelected("instances", doc._id)
if Favorites.isRecordSelected("instances", doc._id)
unread = '<i class="ion ion-ios-star-outline instance-favorite-selected"></i>'
else if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIcon = ""
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}
<span>#{doc.applicant_name}</span>
</div>
<div class='instance-detail'>#{step_current_name_view}
<span class='instance-modified' title='#{modifiedString}'>#{modifiedFromNow}</span>
</div>
"""
},
{
data: "applicant_organization_name",
title: t("instances_applicant_organization_name"),
visible: false,
},
{
data: "name",
title: t("instances_name"),
render: (val, type, doc) ->
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
agent_view = "";
if doc.agent_user_name
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}</div>
"""
visible: false,
orderable: false
},
{
data: "applicant_name",
title: t("instances_applicant_name"),
visible: false,
orderable: false
},
{
data: "submit_date",
title: t("instances_submit_date"),
render: (val, type, doc) ->
if doc.submit_date
return moment(doc.submit_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "flow_name",
title: t("instances_flow"),
visible: false,
orderable: false
},
{
data: "current_step_name",
title: t("instances_step_current_name"),
render: (val, type, doc) ->
if doc.state == "completed"
judge = doc.final_decision || "approved"
step_current_name = doc.current_step_name || ''
cc_tag = ''
if doc.cc_count > 0
cc_tag = TAPi18n.__('cc_tag')
return """
<div class="step-current-state #{judge}">#{step_current_name}#{cc_tag}</div>
"""
visible: false,
orderable: false
},
{
data: "modified",
title: t("instances_modified"),
render: (val, type, doc) ->
return moment(doc.modified).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "start_date",
title: t("instances_start_date"),
render: (val, type, doc) ->
if doc.start_date
return moment(doc.start_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "my_finish_date",
render: (val, type, doc) ->
if doc.my_finish_date
return moment(doc.my_finish_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "modified",
visible: false
},
{
data: "keywords",
visible: false
},
{
data: "is_archived",
render: (val, type, doc) ->
if doc?.values?.record_need && doc.values.record_need == "true"
if doc?.is_archived
return t("YES")
return t("NO")
visible: false
orderable: false
}
],
dom: do ->
# 手机上不显示一页显示多少条记录选项
if Steedos.isMobile()
'tp'
else
'tpl'
order: [[4, "desc"]],
extraFields: ["form", "flow", "inbox_users", "state", "space", "applicant", "form_version",
"flow_version", "is_cc", "cc_count", "is_read", "current_step_name", "values", "keywords", "final_decision", "flow_name", "is_hidden", "agent_user_name"],
lengthChange: true,
lengthMenu: [10,15,20,25,50,100],
pageLength: 10,
info: false,
searching: true,
responsive:
details: false
autoWidth: false,
changeSelector: (selector, userId) ->
unless userId
return {_id: -1}
space = selector.space
unless space
if selector?.$and?.length > 0
space = selector.$and.getProperty('space')[0]
unless space
return {_id: -1}
space_user = db.space_users.findOne({user: userId, space: space}, {fields: {_id: 1}})
unless space_user
return {_id: -1}
return selector
pagingType: "numbers"
}
if flowId
key = "<KEY>" + flowId
options.name = key
TabularTables.instances.fields = fields
ins_fields = _handleListFields TabularTables.instances.fields
ins_fields.forEach (f)->
if f.type != 'table' && f.is_list_display
options.columns.push
data: (f.name || f.code),
title: t(f.name || f.code),
visible: false,
orderable: false
render: (val, type, doc) ->
values = doc.values || {}
value = values[f.code]
switch f.type
when 'user'
value = value?.name
when 'group'
value = value?.fullname
when 'date'
if value
value = moment(value).format('YYYY-MM-DD')
when 'dateTime'
if value
value = moment(value).format('YYYY-MM-DD HH:mm')
when 'checkbox'
if value == true || value == 'true'
value = TAPi18n.__("form_field_checkbox_yes");
else
value = TAPi18n.__("form_field_checkbox_no");
when 'odata'
if value
if _.isArray(value)
value = _.pluck(value, '@label').toString()
else
value = value['@label']
return value
return options;
Meteor.startup ()->
TabularTables.instances = new Tabular.Table instancesListTableTabular()
GetBoxInstancesTabularOptions = (box, flowId, fields)->
key = "<KEY>
if box == "inbox"
options = _get_inbox_instances_tabular_options(flowId, fields)
else if box == "outbox"
options = _get_outbox_instances_tabular_options(flowId, fields)
else
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
if flowId
options.name = key
return options
_get_inbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
options.order = [[8, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': false
'_approve.handler': userId,
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'start_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_start_date": {$first: "$_approve.start_date"}}
ag_sort = 'approve_start_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.inbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("inbox")
_get_outbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "outbox_instances"
options.order = [[9, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': true
$or: [{'_approve.handler': userId},{'_approve.user': userId}]
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'my_finish_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_finish_date": {$last: "$_approve.finish_date"}}
ag_sort = 'approve_finish_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.outbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("outbox")
if Meteor.isClient
TabularTables.flowInstances = new ReactiveVar()
Meteor.startup ()->
Tracker.autorun (c) ->
if Meteor.isClient && !Steedos.isMobile()
if Session.get("flowId") && Session.get("box") != 'draft'
Meteor.call "newInstancesListTabular", Session.get("box"), Session.get("flowId"), (error, result) ->
newInstancesListTabular Session.get("box"), Session.get("flowId"), result
Template.instance_list._changeOrder()
newInstancesListTabular = (box, flowId, fields)->
if !fields
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
fields = _handleListFields fields
if fields?.filterProperty("is_list_display", true)?.length > 0
key = "<KEY> + <KEY> + flow<KEY>
if Meteor.isClient
TabularTables.flowInstances.set(new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields))
else
new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields)
console.log "new TabularTables ", key
if Meteor.isServer
Meteor.methods
newInstancesListTabular: (box, flowId)->
newInstancesListTabular(box, flowId)
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
return fields
| true | Steedos.subs["InstanceTabular"] = new SubsManager()
_handleListFields = (fields) ->
ins_fields = new Array();
fields?.forEach (f)->
if f.type == 'table'
console.log 'ignore opinion field in table'
else if f.type == 'section'
f?.fields?.forEach (f1)->
ins_fields.push f1
else
ins_fields.push f
return ins_fields
updateTabularTitle = ()->
# 如果columns有加减,请修改Template.instance_list._tableColumns 函数
instancesListTableTabular = (flowId, fields)->
options = {
name: "instances",
collection: db.instances,
pub: "instance_tabular",
onUnload: ()->
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
drawCallback: (settings)->
emptyTd = $(".dataTables_empty")
if emptyTd.length
emptyTd[0].colSpan = "6"
if !Steedos.isMobile() && !Steedos.isPad()
Meteor.setTimeout(Template.instance_list._tableColumns, 150)
$(".instance-list").scrollTop(0).ready ->
$(".instance-list").perfectScrollbar("update")
else
$(".instance-list").scrollTop(0)
title = t "pager_input_hint"
ellipsisLink = settings.oInstance.parent().find('.paging_numbers .pagination .disabled a')
ellipsisLink.attr("title", title).css("cursor", "pointer").click ->
if !$(this).find('input').length
input = $('<input class="paginate_input form-control input-sm" type="text" style="border: none; padding:0 2px;"/>')
if Steedos.isMobile()
input.css({
width:"52px"
height: "20px"
})
else
input.css({
width:"52px"
height: "16px"
})
input.attr("title", title).attr("placeholder", title)
$(this).empty().append input
goPage = (index)->
if index > 0
pages = Math.ceil(settings.fnRecordsDisplay() / settings._iDisplayLength)
if index > pages
# 页码超出索引时跳转到最后一页
index = pages
index--
settings.oInstance.DataTable().page(index).draw('page')
input.blur (e)->
currentPage = $(this).val()
goPage currentPage
$(this).parent().html '...'
input.keydown (e)->
if(e.keyCode.toString() == "13")
currentPage = $(this).val()
goPage currentPage
createdRow: (row, data, dataIndex) ->
if Meteor.isClient
if data._id == FlowRouter.current().params.instanceId
row.setAttribute("class", "selected")
columns: [
{
data: "_id",
orderable: false
render: (val, type, doc) ->
modifiedString = moment(doc.modified).format('YYYY-MM-DD');
modified = doc.modified
if Session.get("box") == 'inbox' && doc.state != 'draft'
modified = doc.start_date || doc.modified
if Session.get("box") == 'outbox' || Session.get("box") == 'monitor'
modified = doc.submit_date || doc.submit_date
modifiedFromNow = Steedos.momentReactiveFromNow(modified);
flow_name = doc.flow_name
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
if Session.get("box") != 'draft' && doc.current_step_name
step_current_name_view = "<div class='flow-name'>#{flow_name}<span>(#{doc.current_step_name})</span></div>"
else
step_current_name_view = "<div class='flow-name'>#{flow_name}</div>"
agent_view = "";
if doc.agent_user_name && Session.get("box") == 'inbox'
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
isFavoriteSelected = Favorites.isRecordSelected("instances", doc._id)
if Favorites.isRecordSelected("instances", doc._id)
unread = '<i class="ion ion-ios-star-outline instance-favorite-selected"></i>'
else if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIcon = ""
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}
<span>#{doc.applicant_name}</span>
</div>
<div class='instance-detail'>#{step_current_name_view}
<span class='instance-modified' title='#{modifiedString}'>#{modifiedFromNow}</span>
</div>
"""
},
{
data: "applicant_organization_name",
title: t("instances_applicant_organization_name"),
visible: false,
},
{
data: "name",
title: t("instances_name"),
render: (val, type, doc) ->
cc_view = "";
step_current_name_view = "";
# 当前用户在cc user中,但是不在inbox users时才显示'传阅'文字
if doc.is_cc && !doc.inbox_users?.includes(Meteor.userId()) && Session.get("box") == 'inbox'
cc_view = "<label class='cc-label'>(" + TAPi18n.__("instance_cc_title") + ")</label> "
agent_view = "";
if doc.agent_user_name
agent_view = "<label class='cc-label'>(" + TAPi18n.__('process_delegation_rules_description', {userName: doc.agent_user_name}) + ")</label>"
unread = ''
if Session.get("box") == 'inbox' && doc.is_read == false
unread = '<i class="ion ion-record unread"></i>'
else if Session.get("box") == 'monitor' && doc.is_hidden == true
unread = '<i class="fa fa-lock"></i>'
priorityIconClass = ""
priorityValue = doc.values?.priority
switch priorityValue
when "特急"
priorityIconClass = "danger"
when "紧急"
priorityIconClass = "warning"
when "办文"
priorityIconClass = "muted"
if priorityIconClass
instanceNamePriorityClass = "color-priority color-priority-#{priorityIconClass}"
return """
<div class='instance-read-bar'>#{unread}</div>
<div class='instance-name #{instanceNamePriorityClass}'>#{doc.name}#{cc_view}#{agent_view}</div>
"""
visible: false,
orderable: false
},
{
data: "applicant_name",
title: t("instances_applicant_name"),
visible: false,
orderable: false
},
{
data: "submit_date",
title: t("instances_submit_date"),
render: (val, type, doc) ->
if doc.submit_date
return moment(doc.submit_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "flow_name",
title: t("instances_flow"),
visible: false,
orderable: false
},
{
data: "current_step_name",
title: t("instances_step_current_name"),
render: (val, type, doc) ->
if doc.state == "completed"
judge = doc.final_decision || "approved"
step_current_name = doc.current_step_name || ''
cc_tag = ''
if doc.cc_count > 0
cc_tag = TAPi18n.__('cc_tag')
return """
<div class="step-current-state #{judge}">#{step_current_name}#{cc_tag}</div>
"""
visible: false,
orderable: false
},
{
data: "modified",
title: t("instances_modified"),
render: (val, type, doc) ->
return moment(doc.modified).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "start_date",
title: t("instances_start_date"),
render: (val, type, doc) ->
if doc.start_date
return moment(doc.start_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "my_finish_date",
render: (val, type, doc) ->
if doc.my_finish_date
return moment(doc.my_finish_date).format('YYYY-MM-DD HH:mm');
,
visible: false,
orderable: true
},
{
data: "modified",
visible: false
},
{
data: "keywords",
visible: false
},
{
data: "is_archived",
render: (val, type, doc) ->
if doc?.values?.record_need && doc.values.record_need == "true"
if doc?.is_archived
return t("YES")
return t("NO")
visible: false
orderable: false
}
],
dom: do ->
# 手机上不显示一页显示多少条记录选项
if Steedos.isMobile()
'tp'
else
'tpl'
order: [[4, "desc"]],
extraFields: ["form", "flow", "inbox_users", "state", "space", "applicant", "form_version",
"flow_version", "is_cc", "cc_count", "is_read", "current_step_name", "values", "keywords", "final_decision", "flow_name", "is_hidden", "agent_user_name"],
lengthChange: true,
lengthMenu: [10,15,20,25,50,100],
pageLength: 10,
info: false,
searching: true,
responsive:
details: false
autoWidth: false,
changeSelector: (selector, userId) ->
unless userId
return {_id: -1}
space = selector.space
unless space
if selector?.$and?.length > 0
space = selector.$and.getProperty('space')[0]
unless space
return {_id: -1}
space_user = db.space_users.findOne({user: userId, space: space}, {fields: {_id: 1}})
unless space_user
return {_id: -1}
return selector
pagingType: "numbers"
}
if flowId
key = "PI:KEY:<KEY>END_PI" + flowId
options.name = key
TabularTables.instances.fields = fields
ins_fields = _handleListFields TabularTables.instances.fields
ins_fields.forEach (f)->
if f.type != 'table' && f.is_list_display
options.columns.push
data: (f.name || f.code),
title: t(f.name || f.code),
visible: false,
orderable: false
render: (val, type, doc) ->
values = doc.values || {}
value = values[f.code]
switch f.type
when 'user'
value = value?.name
when 'group'
value = value?.fullname
when 'date'
if value
value = moment(value).format('YYYY-MM-DD')
when 'dateTime'
if value
value = moment(value).format('YYYY-MM-DD HH:mm')
when 'checkbox'
if value == true || value == 'true'
value = TAPi18n.__("form_field_checkbox_yes");
else
value = TAPi18n.__("form_field_checkbox_no");
when 'odata'
if value
if _.isArray(value)
value = _.pluck(value, '@label').toString()
else
value = value['@label']
return value
return options;
Meteor.startup ()->
TabularTables.instances = new Tabular.Table instancesListTableTabular()
GetBoxInstancesTabularOptions = (box, flowId, fields)->
key = "PI:KEY:<KEY>END_PI
if box == "inbox"
options = _get_inbox_instances_tabular_options(flowId, fields)
else if box == "outbox"
options = _get_outbox_instances_tabular_options(flowId, fields)
else
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
if flowId
options.name = key
return options
_get_inbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "inbox_instances"
options.order = [[8, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': false
'_approve.handler': userId,
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'start_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_start_date": {$first: "$_approve.start_date"}}
ag_sort = 'approve_start_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.inbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("inbox")
_get_outbox_instances_tabular_options = (flowId, fields)->
options = instancesListTableTabular(flowId, fields)
if !flowId
options.name = "outbox_instances"
options.order = [[9, "desc"]]
options.filteredRecordIds = (table, selector, sort, skip, limit, old_filteredRecordIds, userId, findOptions)->
aggregate_operation = [
{
$match: selector
},
{
$project: {
name: 1,
"_approve": '$traces.approves'
}
},
{
$unwind: "$_approve"
},
{
$unwind: "$_approve"
},
{
$match: {
'_approve.is_finished': true
$or: [{'_approve.handler': userId},{'_approve.user': userId}]
}
}
]
if sort and sort.length > 0
s1 = sort[0]
s1_0 = s1[0]
s1_1 = s1[1]
if s1_0 == 'my_finish_date'
findOptions.sort = [['modified', s1_1]]
aggregate_operation.push $group: {_id: "$_id", "approve_finish_date": {$last: "$_approve.finish_date"}}
ag_sort = 'approve_finish_date': if s1_1 == 'asc' then 1 else -1
aggregate_operation.push $sort: ag_sort
aggregate_operation.push $skip: skip
aggregate_operation.push $limit: limit
filteredRecordIds = new Array()
aggregate = (table, aggregate_operation, filteredRecordIds, cb) ->
table.collection.rawCollection().aggregate(aggregate_operation).toArray (err, data) ->
if err
throw new Error(err)
data.forEach (doc) ->
filteredRecordIds.push doc._id
return
if cb
cb()
return
return
async_aggregate = Meteor.wrapAsync(aggregate)
async_aggregate table, aggregate_operation, filteredRecordIds
return filteredRecordIds.uniq()
else
return old_filteredRecordIds
return options
Meteor.startup ()->
TabularTables.outbox_instances = new Tabular.Table GetBoxInstancesTabularOptions("outbox")
if Meteor.isClient
TabularTables.flowInstances = new ReactiveVar()
Meteor.startup ()->
Tracker.autorun (c) ->
if Meteor.isClient && !Steedos.isMobile()
if Session.get("flowId") && Session.get("box") != 'draft'
Meteor.call "newInstancesListTabular", Session.get("box"), Session.get("flowId"), (error, result) ->
newInstancesListTabular Session.get("box"), Session.get("flowId"), result
Template.instance_list._changeOrder()
newInstancesListTabular = (box, flowId, fields)->
if !fields
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
fields = _handleListFields fields
if fields?.filterProperty("is_list_display", true)?.length > 0
key = "PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI + flowPI:KEY:<KEY>END_PI
if Meteor.isClient
TabularTables.flowInstances.set(new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields))
else
new Tabular.Table GetBoxInstancesTabularOptions(box, flowId, fields)
console.log "new TabularTables ", key
if Meteor.isServer
Meteor.methods
newInstancesListTabular: (box, flowId)->
newInstancesListTabular(box, flowId)
flow = db.flows.findOne({_id: flowId}, {fields: {form: 1}})
fields = db.forms.findOne({ _id: flow?.form }, { fields: { 'current.fields': 1 } })?.current?.fields
return fields
|
[
{
"context": "@Config =\n\tname: 'Jetfile'\n\ttitle: 'Smart maintenance reports. Fast.'\n\tsubt",
"end": 25,
"score": 0.6053949594497681,
"start": 18,
"tag": "NAME",
"value": "Jetfile"
},
{
"context": "cialMedia:\n\t\ttwitter:\n\t\t\turl: 'http://twitter.com/Royal_Arse'\n\t\t\ticon: ... | both/_config/_config.coffee | DeBraid/jetfile | 0 | @Config =
name: 'Jetfile'
title: 'Smart maintenance reports. Fast.'
subtitle: 'Get back to work.'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'Coming soon...'
about: 'Coming soon...'
username: false
homeRoute: '/'
dashboardRoute: '/dashboard'
socialMedia:
twitter:
url: 'http://twitter.com/Royal_Arse'
icon: 'twitter'
github:
url: 'http://github.com/DeBraid'
icon: 'github'
info:
url: 'http://cacheflow.ca'
icon: 'link'
publicRoutes: ['home'] | 80564 | @Config =
name: '<NAME>'
title: 'Smart maintenance reports. Fast.'
subtitle: 'Get back to work.'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'Coming soon...'
about: 'Coming soon...'
username: false
homeRoute: '/'
dashboardRoute: '/dashboard'
socialMedia:
twitter:
url: 'http://twitter.com/Royal_Arse'
icon: 'twitter'
github:
url: 'http://github.com/DeBraid'
icon: 'github'
info:
url: 'http://cacheflow.ca'
icon: 'link'
publicRoutes: ['home'] | true | @Config =
name: 'PI:NAME:<NAME>END_PI'
title: 'Smart maintenance reports. Fast.'
subtitle: 'Get back to work.'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'Coming soon...'
about: 'Coming soon...'
username: false
homeRoute: '/'
dashboardRoute: '/dashboard'
socialMedia:
twitter:
url: 'http://twitter.com/Royal_Arse'
icon: 'twitter'
github:
url: 'http://github.com/DeBraid'
icon: 'github'
info:
url: 'http://cacheflow.ca'
icon: 'link'
publicRoutes: ['home'] |
[
{
"context": "ection\n device: {uuid: 'masseuse', token: 'assassin'}\n @jobManager\n @workerFunc\n }",
"end": 1414,
"score": 0.9967114329338074,
"start": 1406,
"tag": "PASSWORD",
"value": "assassin"
},
{
"context": " port: @port\n uuid: 'masseuse'\n ... | test/connect.coffee | octoblu/meshblu-server-websocket | 0 | _ = require 'lodash'
{EventEmitter} = require 'events'
MeshbluWebsocket = require 'meshblu-websocket'
async = require 'async'
UUID = require 'uuid'
Redis = require 'ioredis'
RedisNS = require '@octoblu/redis-ns'
Server = require '../src/server'
getPort = require 'get-port'
{ JobManagerResponder, JobManagerRequester } = require 'meshblu-core-job-manager'
class Connect extends EventEmitter
constructor: ({@redisUri}={}) ->
queueId = UUID.v4()
@namespace = 'ns'
@requestQueueName = "test:request:queue:#{queueId}"
@responseQueueName = "test:response:queue:#{queueId}"
@redisUri = 'redis://localhost'
@workerFunc = sinon.stub()
@jobManager = new JobManagerResponder {
@namespace
@redisUri
maxConnections: 1
jobTimeoutSeconds: 1
queueTimeoutSeconds: 1
jobLogSampleRate: 0
@requestQueueName
workerFunc: (request, callback) =>
@emit 'request', request
@workerFunc request, callback
}
connect: (callback) =>
async.series [
@startJobManager
@startServer
@createConnection
], (error) =>
return callback error if error?
callback null, {
sut: @sut
connection: @connection
device: {uuid: 'masseuse', token: 'assassin'}
@jobManager
@workerFunc
}
shutItDown: (callback=_.noop) =>
@connection.close()
@jobManager.stop()
@sut.stop()
callback()
startJobManager: (callback) =>
@jobManager.start callback
startServer: (callback) =>
getPort().then (@port) =>
@sut = new Server
port: @port
jobTimeoutSeconds: 1
jobLogRedisUri: @redisUri
jobLogQueue: 'sample-rate:0.00'
jobLogSampleRate: 0
maxConnections: 10
redisUri: @redisUri
cacheRedisUri: @redisUri
firehoseRedisUri: @redisUri
namespace: @namespace
requestQueueName: @requestQueueName
responseQueueName: @responseQueueName
@sut.run callback
.catch callback
return # nothing
createConnection: (callback) =>
@connection = new MeshbluWebsocket
hostname: 'localhost'
port: @port
uuid: 'masseuse'
token: 'assassin'
protocol: 'http'
@connection.on 'notReady', (error) => throw error
@connection.on 'error', (error) => throw error
callback()
authenticateConnection: (callback) =>
@jobManager.do (@request, next) =>
response =
metadata:
responseId: @request.metadata.responseId
code: 204
next null, response
, callback
module.exports = Connect
| 96472 | _ = require 'lodash'
{EventEmitter} = require 'events'
MeshbluWebsocket = require 'meshblu-websocket'
async = require 'async'
UUID = require 'uuid'
Redis = require 'ioredis'
RedisNS = require '@octoblu/redis-ns'
Server = require '../src/server'
getPort = require 'get-port'
{ JobManagerResponder, JobManagerRequester } = require 'meshblu-core-job-manager'
class Connect extends EventEmitter
constructor: ({@redisUri}={}) ->
queueId = UUID.v4()
@namespace = 'ns'
@requestQueueName = "test:request:queue:#{queueId}"
@responseQueueName = "test:response:queue:#{queueId}"
@redisUri = 'redis://localhost'
@workerFunc = sinon.stub()
@jobManager = new JobManagerResponder {
@namespace
@redisUri
maxConnections: 1
jobTimeoutSeconds: 1
queueTimeoutSeconds: 1
jobLogSampleRate: 0
@requestQueueName
workerFunc: (request, callback) =>
@emit 'request', request
@workerFunc request, callback
}
connect: (callback) =>
async.series [
@startJobManager
@startServer
@createConnection
], (error) =>
return callback error if error?
callback null, {
sut: @sut
connection: @connection
device: {uuid: 'masseuse', token: '<PASSWORD>'}
@jobManager
@workerFunc
}
shutItDown: (callback=_.noop) =>
@connection.close()
@jobManager.stop()
@sut.stop()
callback()
startJobManager: (callback) =>
@jobManager.start callback
startServer: (callback) =>
getPort().then (@port) =>
@sut = new Server
port: @port
jobTimeoutSeconds: 1
jobLogRedisUri: @redisUri
jobLogQueue: 'sample-rate:0.00'
jobLogSampleRate: 0
maxConnections: 10
redisUri: @redisUri
cacheRedisUri: @redisUri
firehoseRedisUri: @redisUri
namespace: @namespace
requestQueueName: @requestQueueName
responseQueueName: @responseQueueName
@sut.run callback
.catch callback
return # nothing
createConnection: (callback) =>
@connection = new MeshbluWebsocket
hostname: 'localhost'
port: @port
uuid: 'masseuse'
token: '<PASSWORD>'
protocol: 'http'
@connection.on 'notReady', (error) => throw error
@connection.on 'error', (error) => throw error
callback()
authenticateConnection: (callback) =>
@jobManager.do (@request, next) =>
response =
metadata:
responseId: @request.metadata.responseId
code: 204
next null, response
, callback
module.exports = Connect
| true | _ = require 'lodash'
{EventEmitter} = require 'events'
MeshbluWebsocket = require 'meshblu-websocket'
async = require 'async'
UUID = require 'uuid'
Redis = require 'ioredis'
RedisNS = require '@octoblu/redis-ns'
Server = require '../src/server'
getPort = require 'get-port'
{ JobManagerResponder, JobManagerRequester } = require 'meshblu-core-job-manager'
class Connect extends EventEmitter
constructor: ({@redisUri}={}) ->
queueId = UUID.v4()
@namespace = 'ns'
@requestQueueName = "test:request:queue:#{queueId}"
@responseQueueName = "test:response:queue:#{queueId}"
@redisUri = 'redis://localhost'
@workerFunc = sinon.stub()
@jobManager = new JobManagerResponder {
@namespace
@redisUri
maxConnections: 1
jobTimeoutSeconds: 1
queueTimeoutSeconds: 1
jobLogSampleRate: 0
@requestQueueName
workerFunc: (request, callback) =>
@emit 'request', request
@workerFunc request, callback
}
connect: (callback) =>
async.series [
@startJobManager
@startServer
@createConnection
], (error) =>
return callback error if error?
callback null, {
sut: @sut
connection: @connection
device: {uuid: 'masseuse', token: 'PI:PASSWORD:<PASSWORD>END_PI'}
@jobManager
@workerFunc
}
shutItDown: (callback=_.noop) =>
@connection.close()
@jobManager.stop()
@sut.stop()
callback()
startJobManager: (callback) =>
@jobManager.start callback
startServer: (callback) =>
getPort().then (@port) =>
@sut = new Server
port: @port
jobTimeoutSeconds: 1
jobLogRedisUri: @redisUri
jobLogQueue: 'sample-rate:0.00'
jobLogSampleRate: 0
maxConnections: 10
redisUri: @redisUri
cacheRedisUri: @redisUri
firehoseRedisUri: @redisUri
namespace: @namespace
requestQueueName: @requestQueueName
responseQueueName: @responseQueueName
@sut.run callback
.catch callback
return # nothing
createConnection: (callback) =>
@connection = new MeshbluWebsocket
hostname: 'localhost'
port: @port
uuid: 'masseuse'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
protocol: 'http'
@connection.on 'notReady', (error) => throw error
@connection.on 'error', (error) => throw error
callback()
authenticateConnection: (callback) =>
@jobManager.do (@request, next) =>
response =
metadata:
responseId: @request.metadata.responseId
code: 204
next null, response
, callback
module.exports = Connect
|
[
{
"context": ", and the app itself.\nclass Application\n\n name: 'Vessel'\n company: 'AWeber Communications'\n crashURL: '",
"end": 691,
"score": 0.9952524900436401,
"start": 685,
"tag": "NAME",
"value": "Vessel"
}
] | src/app/main.coffee | s1090709/vessel | 101 | # Main application entry point
app = require 'app'
crashReporter = require 'crash-reporter'
ipc = require 'ipc'
Menu = require './ui/menu'
newWindow = require './ui/window'
Startup = require './ui/startup'
TrayIcon = require './ui/tray-icon'
Config = require './ipc/config'
Docker = require './ipc/docker'
Git = require './ipc/git'
Highlighter = require './ipc/highlighter'
Manifest = require './ipc/manifest'
Vagrant = require './ipc/vagrant'
# Main Application
#
# Responsible for the management of the crash-reporter, window agnostic IPC
# objects, and the app itself.
class Application
name: 'Vessel'
company: 'AWeber Communications'
crashURL: 'https://your-domain.com/url-to-submit'
constructor: ->
# Start the Crash Reporter
#crashReporter.start {
# autoSubmit: true
# productName: @name
# companyName: @company
# crashURL: @crashURL
#}
# The startup object will ensure everything is needed to start the app
startup = new Startup
# When the app is ready, setup the main window
app.on 'ready', () ->
# Create the application menu
@menu = new Menu
# Create the tray icon
@tray = new TrayIcon
# Perform the startup initialization and wait for a callback response
startup.initialize () ->
# Open a new environment window
newWindow()
ipc.on 'app:badge:get', (event) ->
event.returnValue = app.dock.getBadge()
ipc.on 'app:badge:set', (event, value) ->
app.dock.setBadge value
event.returnValue = true
ipc.on 'app:bounce', (event) ->
event.returnValue = app.dock.bounce()
ipc.on 'app:bounce:cancel', (event, id) ->
app.dock.cancelBounce id
event.returnValue = true
ipc.on 'app:quit', (event) ->
app.quit()
# Create the new application
new Application()
| 26007 | # Main application entry point
app = require 'app'
crashReporter = require 'crash-reporter'
ipc = require 'ipc'
Menu = require './ui/menu'
newWindow = require './ui/window'
Startup = require './ui/startup'
TrayIcon = require './ui/tray-icon'
Config = require './ipc/config'
Docker = require './ipc/docker'
Git = require './ipc/git'
Highlighter = require './ipc/highlighter'
Manifest = require './ipc/manifest'
Vagrant = require './ipc/vagrant'
# Main Application
#
# Responsible for the management of the crash-reporter, window agnostic IPC
# objects, and the app itself.
class Application
name: '<NAME>'
company: 'AWeber Communications'
crashURL: 'https://your-domain.com/url-to-submit'
constructor: ->
# Start the Crash Reporter
#crashReporter.start {
# autoSubmit: true
# productName: @name
# companyName: @company
# crashURL: @crashURL
#}
# The startup object will ensure everything is needed to start the app
startup = new Startup
# When the app is ready, setup the main window
app.on 'ready', () ->
# Create the application menu
@menu = new Menu
# Create the tray icon
@tray = new TrayIcon
# Perform the startup initialization and wait for a callback response
startup.initialize () ->
# Open a new environment window
newWindow()
ipc.on 'app:badge:get', (event) ->
event.returnValue = app.dock.getBadge()
ipc.on 'app:badge:set', (event, value) ->
app.dock.setBadge value
event.returnValue = true
ipc.on 'app:bounce', (event) ->
event.returnValue = app.dock.bounce()
ipc.on 'app:bounce:cancel', (event, id) ->
app.dock.cancelBounce id
event.returnValue = true
ipc.on 'app:quit', (event) ->
app.quit()
# Create the new application
new Application()
| true | # Main application entry point
app = require 'app'
crashReporter = require 'crash-reporter'
ipc = require 'ipc'
Menu = require './ui/menu'
newWindow = require './ui/window'
Startup = require './ui/startup'
TrayIcon = require './ui/tray-icon'
Config = require './ipc/config'
Docker = require './ipc/docker'
Git = require './ipc/git'
Highlighter = require './ipc/highlighter'
Manifest = require './ipc/manifest'
Vagrant = require './ipc/vagrant'
# Main Application
#
# Responsible for the management of the crash-reporter, window agnostic IPC
# objects, and the app itself.
class Application
name: 'PI:NAME:<NAME>END_PI'
company: 'AWeber Communications'
crashURL: 'https://your-domain.com/url-to-submit'
constructor: ->
# Start the Crash Reporter
#crashReporter.start {
# autoSubmit: true
# productName: @name
# companyName: @company
# crashURL: @crashURL
#}
# The startup object will ensure everything is needed to start the app
startup = new Startup
# When the app is ready, setup the main window
app.on 'ready', () ->
# Create the application menu
@menu = new Menu
# Create the tray icon
@tray = new TrayIcon
# Perform the startup initialization and wait for a callback response
startup.initialize () ->
# Open a new environment window
newWindow()
ipc.on 'app:badge:get', (event) ->
event.returnValue = app.dock.getBadge()
ipc.on 'app:badge:set', (event, value) ->
app.dock.setBadge value
event.returnValue = true
ipc.on 'app:bounce', (event) ->
event.returnValue = app.dock.bounce()
ipc.on 'app:bounce:cancel', (event, id) ->
app.dock.cancelBounce id
event.returnValue = true
ipc.on 'app:quit', (event) ->
app.quit()
# Create the new application
new Application()
|
[
{
"context": "password) ->\n this.native().settings.userName = user\n this.native().settings.password = password\n ",
"end": 5564,
"score": 0.9741864204406738,
"start": 5560,
"tag": "USERNAME",
"value": "user"
},
{
"context": "rName = user\n this.native().settings.password ... | lib/capybara/poltergeist/client/web_page.coffee | Nix-wie-weg/poltergeist | 0 | class Poltergeist.WebPage
@CALLBACKS = ['onConsoleMessage','onError',
'onLoadFinished', 'onInitialized', 'onLoadStarted',
'onResourceRequested', 'onResourceReceived', 'onResourceError',
'onNavigationRequested', 'onUrlChanged', 'onPageCreated',
'onClosing']
@DELEGATES = ['open', 'sendEvent', 'uploadFile', 'release', 'render',
'renderBase64', 'goBack', 'goForward']
@COMMANDS = ['currentUrl', 'find', 'nodeCall', 'documentSize',
'beforeUpload', 'afterUpload', 'clearLocalStorage']
@EXTENSIONS = []
constructor: (@_native) ->
@_native or= require('webpage').create()
@id = 0
@source = null
@closed = false
@state = 'default'
@urlWhitelist = []
@urlBlacklist = []
@errors = []
@_networkTraffic = {}
@_tempHeaders = {}
@_blockedUrls = []
@_requestedResources = {}
@_responseHeaders = []
for callback in WebPage.CALLBACKS
this.bindCallback(callback)
if phantom.version.major < 2
@._overrideNativeEvaluate()
for command in @COMMANDS
do (command) =>
this.prototype[command] =
(args...) -> this.runCommand(command, args)
for delegate in @DELEGATES
do (delegate) =>
this.prototype[delegate] =
-> @_native[delegate].apply(@_native, arguments)
onInitializedNative: ->
@id += 1
@source = null
@injectAgent()
this.removeTempHeaders()
this.setScrollPosition(left: 0, top: 0)
onClosingNative: ->
@handle = null
@closed = true
onConsoleMessageNative: (message) ->
if message == '__DOMContentLoaded'
@source = @_native.content
false
else
console.log(message)
onLoadStartedNative: ->
@state = 'loading'
@requestId = @lastRequestId
@_requestedResources = {}
onLoadFinishedNative: (@status) ->
@state = 'default'
@source or= @_native.content
onErrorNative: (message, stack) ->
stackString = message
stack.forEach (frame) ->
stackString += "\n"
stackString += " at #{frame.file}:#{frame.line}"
stackString += " in #{frame.function}" if frame.function && frame.function != ''
@errors.push(message: message, stack: stackString)
return true
onResourceRequestedNative: (request, net) ->
useWhitelist = @urlWhitelist.length > 0
whitelisted = @urlWhitelist.some (whitelisted_regex) ->
whitelisted_regex.test request.url
blacklisted = @urlBlacklist.some (blacklisted_regex) ->
blacklisted_regex.test request.url
abort = false
if useWhitelist && !whitelisted
abort = true
if blacklisted
abort = true
if abort
@_blockedUrls.push request.url unless request.url in @_blockedUrls
net.abort()
else
@lastRequestId = request.id
if @normalizeURL(request.url) == @redirectURL
@redirectURL = null
@requestId = request.id
@_networkTraffic[request.id] = {
request: request,
responseParts: []
error: null
}
@_requestedResources[request.id] = request.url
return true
onResourceReceivedNative: (response) ->
@_networkTraffic[response.id]?.responseParts.push(response)
if response.stage == 'end'
delete @_requestedResources[response.id]
if @requestId == response.id
if response.redirectURL
@redirectURL = @normalizeURL(response.redirectURL)
else
@statusCode = response.status
@_responseHeaders = response.headers
return true
onResourceErrorNative: (errorResponse) ->
@_networkTraffic[errorResponse.id]?.error = errorResponse
delete @_requestedResources[errorResponse.id]
return true
injectAgent: ->
if this.native().evaluate(-> typeof __poltergeist) == "undefined"
this.native().injectJs "#{phantom.libraryPath}/agent.js"
for extension in WebPage.EXTENSIONS
this.native().injectJs extension
return true
return false
injectExtension: (file) ->
WebPage.EXTENSIONS.push file
this.native().injectJs file
native: ->
if @closed
throw new Poltergeist.NoSuchWindowError
else
@_native
windowName: ->
this.native().windowName
keyCode: (name) ->
name = "Control" if name == "Ctrl"
this.native().event.key[name]
keyModifierCode: (names) ->
modifiers = this.native().event.modifier
names.split(',').map((name) -> modifiers[name]).reduce((n1,n2) -> n1 | n2)
keyModifierKeys: (names) ->
for name in names.split(',') when name isnt 'keypad'
name = name.charAt(0).toUpperCase() + name.substring(1)
this.keyCode(name)
_waitState_until: (state, callback, timeout, timeout_callback) ->
if (@state == state)
callback.call(this)
else
if new Date().getTime() > timeout
timeout_callback.call(this)
else
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
waitState: (state, callback, max_wait=0, timeout_callback) ->
# callback and timeout_callback will be called with this == the current page
if @state == state
callback.call(this)
else
if max_wait != 0
timeout = new Date().getTime() + (max_wait*1000)
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
else
setTimeout (=> @waitState(state, callback)), 100
setHttpAuth: (user, password) ->
this.native().settings.userName = user
this.native().settings.password = password
return true
networkTraffic: ->
@_networkTraffic
clearNetworkTraffic: ->
@_networkTraffic = {}
return true
blockedUrls: ->
@_blockedUrls
clearBlockedUrls: ->
@_blockedUrls = []
return true
openResourceRequests: ->
url for own id, url of @_requestedResources
content: ->
this.native().frameContent
title: ->
this.native().frameTitle
frameUrl: (frameNameOrId) ->
query = (frameNameOrId) ->
document.querySelector("iframe[name='#{frameNameOrId}'], iframe[id='#{frameNameOrId}']")?.src
this.evaluate(query, frameNameOrId)
clearErrors: ->
@errors = []
return true
responseHeaders: ->
headers = {}
@_responseHeaders.forEach (item) ->
headers[item.name] = item.value
headers
cookies: ->
this.native().cookies
deleteCookie: (name) ->
this.native().deleteCookie(name)
viewportSize: ->
this.native().viewportSize
setViewportSize: (size) ->
this.native().viewportSize = size
setZoomFactor: (zoom_factor) ->
this.native().zoomFactor = zoom_factor
setPaperSize: (size) ->
this.native().paperSize = size
scrollPosition: ->
this.native().scrollPosition
setScrollPosition: (pos) ->
this.native().scrollPosition = pos
clipRect: ->
this.native().clipRect
setClipRect: (rect) ->
this.native().clipRect = rect
elementBounds: (selector) ->
this.native().evaluate(
(selector) ->
document.querySelector(selector).getBoundingClientRect()
, selector
)
setUserAgent: (userAgent) ->
this.native().settings.userAgent = userAgent
getCustomHeaders: ->
this.native().customHeaders
setCustomHeaders: (headers) ->
this.native().customHeaders = headers
addTempHeader: (header) ->
for name, value of header
@_tempHeaders[name] = value
@_tempHeaders
removeTempHeaders: ->
allHeaders = this.getCustomHeaders()
for name, value of @_tempHeaders
delete allHeaders[name]
this.setCustomHeaders(allHeaders)
pushFrame: (name) ->
return true if this.native().switchToFrame(name)
# if switch by name fails - find index and try again
frame_no = this.native().evaluate(
(frame_name) ->
frames = document.querySelectorAll("iframe, frame")
(idx for f, idx in frames when f?['name'] == frame_name or f?['id'] == frame_name)[0]
, name)
frame_no? and this.native().switchToFrame(frame_no)
popFrame: (pop_all = false)->
if pop_all
this.native().switchToMainFrame()
else
this.native().switchToParentFrame()
dimensions: ->
scroll = this.scrollPosition()
viewport = this.viewportSize()
top: scroll.top, bottom: scroll.top + viewport.height,
left: scroll.left, right: scroll.left + viewport.width,
viewport: viewport
document: this.documentSize()
# A work around for http://code.google.com/p/phantomjs/issues/detail?id=277
validatedDimensions: ->
dimensions = this.dimensions()
document = dimensions.document
if dimensions.right > document.width
dimensions.left = Math.max(0, dimensions.left - (dimensions.right - document.width))
dimensions.right = document.width
if dimensions.bottom > document.height
dimensions.top = Math.max(0, dimensions.top - (dimensions.bottom - document.height))
dimensions.bottom = document.height
this.setScrollPosition(left: dimensions.left, top: dimensions.top)
dimensions
get: (id) ->
new Poltergeist.Node(this, id)
# Before each mouse event we make sure that the mouse is moved to where the
# event will take place. This deals with e.g. :hover changes.
mouseEvent: (name, x, y, button = 'left') ->
this.sendEvent('mousemove', x, y)
this.sendEvent(name, x, y, button)
evaluate: (fn, args...) ->
this.injectAgent()
result = this.native().evaluate("function() {
var page_id = arguments[0];
var args = [];
for(var i=1; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
args.push(window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element);
} else {
args.push(arguments[i])
}
}
var _result = #{this.stringifyCall(fn, "args")};
return window.__poltergeist.wrapResults(_result, page_id); }", @id, args...)
result
execute: (fn, args...) ->
this.native().evaluate("function() {
for(var i=0; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
arguments[i] = window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element;
}
}
#{this.stringifyCall(fn)} }", args...)
stringifyCall: (fn, args_name = "arguments") ->
"(#{fn.toString()}).apply(this, #{args_name})"
bindCallback: (name) ->
@native()[name] = =>
result = @[name + 'Native'].apply(@, arguments) if @[name + 'Native']? # For internal callbacks
@[name].apply(@, arguments) if result != false && @[name]? # For externally set callbacks
return true
# Any error raised here or inside the evaluate will get reported to
# phantom.onError. If result is null, that means there was an error
# inside the agent.
runCommand: (name, args) ->
result = this.evaluate(
(name, args) -> __poltergeist.externalCall(name, args),
name, args
)
if result?.error?
switch result.error.message
when 'PoltergeistAgent.ObsoleteNode'
throw new Poltergeist.ObsoleteNode
when 'PoltergeistAgent.InvalidSelector'
[method, selector] = args
throw new Poltergeist.InvalidSelector(method, selector)
else
throw new Poltergeist.BrowserError(result.error.message, result.error.stack)
else
result?.value
canGoBack: ->
this.native().canGoBack
canGoForward: ->
this.native().canGoForward
normalizeURL: (url) ->
parser = document.createElement('a')
parser.href = url
return parser.href
clearMemoryCache: ->
clearMemoryCache = this.native().clearMemoryCache
if typeof clearMemoryCache == "function"
clearMemoryCache()
else
throw new Poltergeist.UnsupportedFeature("clearMemoryCache is supported since PhantomJS 2.0.0")
_overrideNativeEvaluate: ->
# PhantomJS 1.9.x WebPage#evaluate depends on the browser context JSON, this replaces it
# with the evaluate from 2.1.1 which uses the PhantomJS JSON
@_native.evaluate = `function (func, args) {
function quoteString(str) {
var c, i, l = str.length, o = '"';
for (i = 0; i < l; i += 1) {
c = str.charAt(i);
if (c >= ' ') {
if (c === '\\' || c === '"') {
o += '\\';
}
o += c;
} else {
switch (c) {
case '\b':
o += '\\b';
break;
case '\f':
o += '\\f';
break;
case '\n':
o += '\\n';
break;
case '\r':
o += '\\r';
break;
case '\t':
o += '\\t';
break;
default:
c = c.charCodeAt();
o += '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}
}
}
return o + '"';
}
function detectType(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
} else if (value instanceof RegExp) {
s = 'regexp';
} else if (value instanceof Date) {
s = 'date';
}
} else {
s = 'null';
}
}
return s;
}
var str, arg, argType, i, l;
if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) {
throw "Wrong use of WebPage#evaluate";
}
str = 'function() { return (' + func.toString() + ')(';
for (i = 1, l = arguments.length; i < l; i++) {
arg = arguments[i];
argType = detectType(arg);
switch (argType) {
case "object": //< for type "object"
case "array": //< for type "array"
str += JSON.stringify(arg) + ","
break;
case "date": //< for type "date"
str += "new Date(" + JSON.stringify(arg) + "),"
break;
case "string": //< for type "string"
str += quoteString(arg) + ',';
break;
default: // for types: "null", "number", "function", "regexp", "undefined"
str += arg + ',';
break;
}
}
str = str.replace(/,$/, '') + '); }';
return this.evaluateJavaScript(str);
};`
| 148968 | class Poltergeist.WebPage
@CALLBACKS = ['onConsoleMessage','onError',
'onLoadFinished', 'onInitialized', 'onLoadStarted',
'onResourceRequested', 'onResourceReceived', 'onResourceError',
'onNavigationRequested', 'onUrlChanged', 'onPageCreated',
'onClosing']
@DELEGATES = ['open', 'sendEvent', 'uploadFile', 'release', 'render',
'renderBase64', 'goBack', 'goForward']
@COMMANDS = ['currentUrl', 'find', 'nodeCall', 'documentSize',
'beforeUpload', 'afterUpload', 'clearLocalStorage']
@EXTENSIONS = []
constructor: (@_native) ->
@_native or= require('webpage').create()
@id = 0
@source = null
@closed = false
@state = 'default'
@urlWhitelist = []
@urlBlacklist = []
@errors = []
@_networkTraffic = {}
@_tempHeaders = {}
@_blockedUrls = []
@_requestedResources = {}
@_responseHeaders = []
for callback in WebPage.CALLBACKS
this.bindCallback(callback)
if phantom.version.major < 2
@._overrideNativeEvaluate()
for command in @COMMANDS
do (command) =>
this.prototype[command] =
(args...) -> this.runCommand(command, args)
for delegate in @DELEGATES
do (delegate) =>
this.prototype[delegate] =
-> @_native[delegate].apply(@_native, arguments)
onInitializedNative: ->
@id += 1
@source = null
@injectAgent()
this.removeTempHeaders()
this.setScrollPosition(left: 0, top: 0)
onClosingNative: ->
@handle = null
@closed = true
onConsoleMessageNative: (message) ->
if message == '__DOMContentLoaded'
@source = @_native.content
false
else
console.log(message)
onLoadStartedNative: ->
@state = 'loading'
@requestId = @lastRequestId
@_requestedResources = {}
onLoadFinishedNative: (@status) ->
@state = 'default'
@source or= @_native.content
onErrorNative: (message, stack) ->
stackString = message
stack.forEach (frame) ->
stackString += "\n"
stackString += " at #{frame.file}:#{frame.line}"
stackString += " in #{frame.function}" if frame.function && frame.function != ''
@errors.push(message: message, stack: stackString)
return true
onResourceRequestedNative: (request, net) ->
useWhitelist = @urlWhitelist.length > 0
whitelisted = @urlWhitelist.some (whitelisted_regex) ->
whitelisted_regex.test request.url
blacklisted = @urlBlacklist.some (blacklisted_regex) ->
blacklisted_regex.test request.url
abort = false
if useWhitelist && !whitelisted
abort = true
if blacklisted
abort = true
if abort
@_blockedUrls.push request.url unless request.url in @_blockedUrls
net.abort()
else
@lastRequestId = request.id
if @normalizeURL(request.url) == @redirectURL
@redirectURL = null
@requestId = request.id
@_networkTraffic[request.id] = {
request: request,
responseParts: []
error: null
}
@_requestedResources[request.id] = request.url
return true
onResourceReceivedNative: (response) ->
@_networkTraffic[response.id]?.responseParts.push(response)
if response.stage == 'end'
delete @_requestedResources[response.id]
if @requestId == response.id
if response.redirectURL
@redirectURL = @normalizeURL(response.redirectURL)
else
@statusCode = response.status
@_responseHeaders = response.headers
return true
onResourceErrorNative: (errorResponse) ->
@_networkTraffic[errorResponse.id]?.error = errorResponse
delete @_requestedResources[errorResponse.id]
return true
injectAgent: ->
if this.native().evaluate(-> typeof __poltergeist) == "undefined"
this.native().injectJs "#{phantom.libraryPath}/agent.js"
for extension in WebPage.EXTENSIONS
this.native().injectJs extension
return true
return false
injectExtension: (file) ->
WebPage.EXTENSIONS.push file
this.native().injectJs file
native: ->
if @closed
throw new Poltergeist.NoSuchWindowError
else
@_native
windowName: ->
this.native().windowName
keyCode: (name) ->
name = "Control" if name == "Ctrl"
this.native().event.key[name]
keyModifierCode: (names) ->
modifiers = this.native().event.modifier
names.split(',').map((name) -> modifiers[name]).reduce((n1,n2) -> n1 | n2)
keyModifierKeys: (names) ->
for name in names.split(',') when name isnt 'keypad'
name = name.charAt(0).toUpperCase() + name.substring(1)
this.keyCode(name)
_waitState_until: (state, callback, timeout, timeout_callback) ->
if (@state == state)
callback.call(this)
else
if new Date().getTime() > timeout
timeout_callback.call(this)
else
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
waitState: (state, callback, max_wait=0, timeout_callback) ->
# callback and timeout_callback will be called with this == the current page
if @state == state
callback.call(this)
else
if max_wait != 0
timeout = new Date().getTime() + (max_wait*1000)
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
else
setTimeout (=> @waitState(state, callback)), 100
setHttpAuth: (user, password) ->
this.native().settings.userName = user
this.native().settings.password = <PASSWORD>
return true
networkTraffic: ->
@_networkTraffic
clearNetworkTraffic: ->
@_networkTraffic = {}
return true
blockedUrls: ->
@_blockedUrls
clearBlockedUrls: ->
@_blockedUrls = []
return true
openResourceRequests: ->
url for own id, url of @_requestedResources
content: ->
this.native().frameContent
title: ->
this.native().frameTitle
frameUrl: (frameNameOrId) ->
query = (frameNameOrId) ->
document.querySelector("iframe[name='#{frameNameOrId}'], iframe[id='#{frameNameOrId}']")?.src
this.evaluate(query, frameNameOrId)
clearErrors: ->
@errors = []
return true
responseHeaders: ->
headers = {}
@_responseHeaders.forEach (item) ->
headers[item.name] = item.value
headers
cookies: ->
this.native().cookies
deleteCookie: (name) ->
this.native().deleteCookie(name)
viewportSize: ->
this.native().viewportSize
setViewportSize: (size) ->
this.native().viewportSize = size
setZoomFactor: (zoom_factor) ->
this.native().zoomFactor = zoom_factor
setPaperSize: (size) ->
this.native().paperSize = size
scrollPosition: ->
this.native().scrollPosition
setScrollPosition: (pos) ->
this.native().scrollPosition = pos
clipRect: ->
this.native().clipRect
setClipRect: (rect) ->
this.native().clipRect = rect
elementBounds: (selector) ->
this.native().evaluate(
(selector) ->
document.querySelector(selector).getBoundingClientRect()
, selector
)
setUserAgent: (userAgent) ->
this.native().settings.userAgent = userAgent
getCustomHeaders: ->
this.native().customHeaders
setCustomHeaders: (headers) ->
this.native().customHeaders = headers
addTempHeader: (header) ->
for name, value of header
@_tempHeaders[name] = value
@_tempHeaders
removeTempHeaders: ->
allHeaders = this.getCustomHeaders()
for name, value of @_tempHeaders
delete allHeaders[name]
this.setCustomHeaders(allHeaders)
pushFrame: (name) ->
return true if this.native().switchToFrame(name)
# if switch by name fails - find index and try again
frame_no = this.native().evaluate(
(frame_name) ->
frames = document.querySelectorAll("iframe, frame")
(idx for f, idx in frames when f?['name'] == frame_name or f?['id'] == frame_name)[0]
, name)
frame_no? and this.native().switchToFrame(frame_no)
popFrame: (pop_all = false)->
if pop_all
this.native().switchToMainFrame()
else
this.native().switchToParentFrame()
dimensions: ->
scroll = this.scrollPosition()
viewport = this.viewportSize()
top: scroll.top, bottom: scroll.top + viewport.height,
left: scroll.left, right: scroll.left + viewport.width,
viewport: viewport
document: this.documentSize()
# A work around for http://code.google.com/p/phantomjs/issues/detail?id=277
validatedDimensions: ->
dimensions = this.dimensions()
document = dimensions.document
if dimensions.right > document.width
dimensions.left = Math.max(0, dimensions.left - (dimensions.right - document.width))
dimensions.right = document.width
if dimensions.bottom > document.height
dimensions.top = Math.max(0, dimensions.top - (dimensions.bottom - document.height))
dimensions.bottom = document.height
this.setScrollPosition(left: dimensions.left, top: dimensions.top)
dimensions
get: (id) ->
new Poltergeist.Node(this, id)
# Before each mouse event we make sure that the mouse is moved to where the
# event will take place. This deals with e.g. :hover changes.
mouseEvent: (name, x, y, button = 'left') ->
this.sendEvent('mousemove', x, y)
this.sendEvent(name, x, y, button)
evaluate: (fn, args...) ->
this.injectAgent()
result = this.native().evaluate("function() {
var page_id = arguments[0];
var args = [];
for(var i=1; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
args.push(window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element);
} else {
args.push(arguments[i])
}
}
var _result = #{this.stringifyCall(fn, "args")};
return window.__poltergeist.wrapResults(_result, page_id); }", @id, args...)
result
execute: (fn, args...) ->
this.native().evaluate("function() {
for(var i=0; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
arguments[i] = window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element;
}
}
#{this.stringifyCall(fn)} }", args...)
stringifyCall: (fn, args_name = "arguments") ->
"(#{fn.toString()}).apply(this, #{args_name})"
bindCallback: (name) ->
@native()[name] = =>
result = @[name + 'Native'].apply(@, arguments) if @[name + 'Native']? # For internal callbacks
@[name].apply(@, arguments) if result != false && @[name]? # For externally set callbacks
return true
# Any error raised here or inside the evaluate will get reported to
# phantom.onError. If result is null, that means there was an error
# inside the agent.
runCommand: (name, args) ->
result = this.evaluate(
(name, args) -> __poltergeist.externalCall(name, args),
name, args
)
if result?.error?
switch result.error.message
when 'PoltergeistAgent.ObsoleteNode'
throw new Poltergeist.ObsoleteNode
when 'PoltergeistAgent.InvalidSelector'
[method, selector] = args
throw new Poltergeist.InvalidSelector(method, selector)
else
throw new Poltergeist.BrowserError(result.error.message, result.error.stack)
else
result?.value
canGoBack: ->
this.native().canGoBack
canGoForward: ->
this.native().canGoForward
normalizeURL: (url) ->
parser = document.createElement('a')
parser.href = url
return parser.href
clearMemoryCache: ->
clearMemoryCache = this.native().clearMemoryCache
if typeof clearMemoryCache == "function"
clearMemoryCache()
else
throw new Poltergeist.UnsupportedFeature("clearMemoryCache is supported since PhantomJS 2.0.0")
_overrideNativeEvaluate: ->
# PhantomJS 1.9.x WebPage#evaluate depends on the browser context JSON, this replaces it
# with the evaluate from 2.1.1 which uses the PhantomJS JSON
@_native.evaluate = `function (func, args) {
function quoteString(str) {
var c, i, l = str.length, o = '"';
for (i = 0; i < l; i += 1) {
c = str.charAt(i);
if (c >= ' ') {
if (c === '\\' || c === '"') {
o += '\\';
}
o += c;
} else {
switch (c) {
case '\b':
o += '\\b';
break;
case '\f':
o += '\\f';
break;
case '\n':
o += '\\n';
break;
case '\r':
o += '\\r';
break;
case '\t':
o += '\\t';
break;
default:
c = c.charCodeAt();
o += '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}
}
}
return o + '"';
}
function detectType(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
} else if (value instanceof RegExp) {
s = 'regexp';
} else if (value instanceof Date) {
s = 'date';
}
} else {
s = 'null';
}
}
return s;
}
var str, arg, argType, i, l;
if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) {
throw "Wrong use of WebPage#evaluate";
}
str = 'function() { return (' + func.toString() + ')(';
for (i = 1, l = arguments.length; i < l; i++) {
arg = arguments[i];
argType = detectType(arg);
switch (argType) {
case "object": //< for type "object"
case "array": //< for type "array"
str += JSON.stringify(arg) + ","
break;
case "date": //< for type "date"
str += "new Date(" + JSON.stringify(arg) + "),"
break;
case "string": //< for type "string"
str += quoteString(arg) + ',';
break;
default: // for types: "null", "number", "function", "regexp", "undefined"
str += arg + ',';
break;
}
}
str = str.replace(/,$/, '') + '); }';
return this.evaluateJavaScript(str);
};`
| true | class Poltergeist.WebPage
@CALLBACKS = ['onConsoleMessage','onError',
'onLoadFinished', 'onInitialized', 'onLoadStarted',
'onResourceRequested', 'onResourceReceived', 'onResourceError',
'onNavigationRequested', 'onUrlChanged', 'onPageCreated',
'onClosing']
@DELEGATES = ['open', 'sendEvent', 'uploadFile', 'release', 'render',
'renderBase64', 'goBack', 'goForward']
@COMMANDS = ['currentUrl', 'find', 'nodeCall', 'documentSize',
'beforeUpload', 'afterUpload', 'clearLocalStorage']
@EXTENSIONS = []
constructor: (@_native) ->
@_native or= require('webpage').create()
@id = 0
@source = null
@closed = false
@state = 'default'
@urlWhitelist = []
@urlBlacklist = []
@errors = []
@_networkTraffic = {}
@_tempHeaders = {}
@_blockedUrls = []
@_requestedResources = {}
@_responseHeaders = []
for callback in WebPage.CALLBACKS
this.bindCallback(callback)
if phantom.version.major < 2
@._overrideNativeEvaluate()
for command in @COMMANDS
do (command) =>
this.prototype[command] =
(args...) -> this.runCommand(command, args)
for delegate in @DELEGATES
do (delegate) =>
this.prototype[delegate] =
-> @_native[delegate].apply(@_native, arguments)
onInitializedNative: ->
@id += 1
@source = null
@injectAgent()
this.removeTempHeaders()
this.setScrollPosition(left: 0, top: 0)
onClosingNative: ->
@handle = null
@closed = true
onConsoleMessageNative: (message) ->
if message == '__DOMContentLoaded'
@source = @_native.content
false
else
console.log(message)
onLoadStartedNative: ->
@state = 'loading'
@requestId = @lastRequestId
@_requestedResources = {}
onLoadFinishedNative: (@status) ->
@state = 'default'
@source or= @_native.content
onErrorNative: (message, stack) ->
stackString = message
stack.forEach (frame) ->
stackString += "\n"
stackString += " at #{frame.file}:#{frame.line}"
stackString += " in #{frame.function}" if frame.function && frame.function != ''
@errors.push(message: message, stack: stackString)
return true
onResourceRequestedNative: (request, net) ->
useWhitelist = @urlWhitelist.length > 0
whitelisted = @urlWhitelist.some (whitelisted_regex) ->
whitelisted_regex.test request.url
blacklisted = @urlBlacklist.some (blacklisted_regex) ->
blacklisted_regex.test request.url
abort = false
if useWhitelist && !whitelisted
abort = true
if blacklisted
abort = true
if abort
@_blockedUrls.push request.url unless request.url in @_blockedUrls
net.abort()
else
@lastRequestId = request.id
if @normalizeURL(request.url) == @redirectURL
@redirectURL = null
@requestId = request.id
@_networkTraffic[request.id] = {
request: request,
responseParts: []
error: null
}
@_requestedResources[request.id] = request.url
return true
onResourceReceivedNative: (response) ->
@_networkTraffic[response.id]?.responseParts.push(response)
if response.stage == 'end'
delete @_requestedResources[response.id]
if @requestId == response.id
if response.redirectURL
@redirectURL = @normalizeURL(response.redirectURL)
else
@statusCode = response.status
@_responseHeaders = response.headers
return true
onResourceErrorNative: (errorResponse) ->
@_networkTraffic[errorResponse.id]?.error = errorResponse
delete @_requestedResources[errorResponse.id]
return true
injectAgent: ->
if this.native().evaluate(-> typeof __poltergeist) == "undefined"
this.native().injectJs "#{phantom.libraryPath}/agent.js"
for extension in WebPage.EXTENSIONS
this.native().injectJs extension
return true
return false
injectExtension: (file) ->
WebPage.EXTENSIONS.push file
this.native().injectJs file
native: ->
if @closed
throw new Poltergeist.NoSuchWindowError
else
@_native
windowName: ->
this.native().windowName
keyCode: (name) ->
name = "Control" if name == "Ctrl"
this.native().event.key[name]
keyModifierCode: (names) ->
modifiers = this.native().event.modifier
names.split(',').map((name) -> modifiers[name]).reduce((n1,n2) -> n1 | n2)
keyModifierKeys: (names) ->
for name in names.split(',') when name isnt 'keypad'
name = name.charAt(0).toUpperCase() + name.substring(1)
this.keyCode(name)
_waitState_until: (state, callback, timeout, timeout_callback) ->
if (@state == state)
callback.call(this)
else
if new Date().getTime() > timeout
timeout_callback.call(this)
else
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
waitState: (state, callback, max_wait=0, timeout_callback) ->
# callback and timeout_callback will be called with this == the current page
if @state == state
callback.call(this)
else
if max_wait != 0
timeout = new Date().getTime() + (max_wait*1000)
setTimeout (=> @_waitState_until(state, callback, timeout, timeout_callback)), 100
else
setTimeout (=> @waitState(state, callback)), 100
setHttpAuth: (user, password) ->
this.native().settings.userName = user
this.native().settings.password = PI:PASSWORD:<PASSWORD>END_PI
return true
networkTraffic: ->
@_networkTraffic
clearNetworkTraffic: ->
@_networkTraffic = {}
return true
blockedUrls: ->
@_blockedUrls
clearBlockedUrls: ->
@_blockedUrls = []
return true
openResourceRequests: ->
url for own id, url of @_requestedResources
content: ->
this.native().frameContent
title: ->
this.native().frameTitle
frameUrl: (frameNameOrId) ->
query = (frameNameOrId) ->
document.querySelector("iframe[name='#{frameNameOrId}'], iframe[id='#{frameNameOrId}']")?.src
this.evaluate(query, frameNameOrId)
clearErrors: ->
@errors = []
return true
responseHeaders: ->
headers = {}
@_responseHeaders.forEach (item) ->
headers[item.name] = item.value
headers
cookies: ->
this.native().cookies
deleteCookie: (name) ->
this.native().deleteCookie(name)
viewportSize: ->
this.native().viewportSize
setViewportSize: (size) ->
this.native().viewportSize = size
setZoomFactor: (zoom_factor) ->
this.native().zoomFactor = zoom_factor
setPaperSize: (size) ->
this.native().paperSize = size
scrollPosition: ->
this.native().scrollPosition
setScrollPosition: (pos) ->
this.native().scrollPosition = pos
clipRect: ->
this.native().clipRect
setClipRect: (rect) ->
this.native().clipRect = rect
elementBounds: (selector) ->
this.native().evaluate(
(selector) ->
document.querySelector(selector).getBoundingClientRect()
, selector
)
setUserAgent: (userAgent) ->
this.native().settings.userAgent = userAgent
getCustomHeaders: ->
this.native().customHeaders
setCustomHeaders: (headers) ->
this.native().customHeaders = headers
addTempHeader: (header) ->
for name, value of header
@_tempHeaders[name] = value
@_tempHeaders
removeTempHeaders: ->
allHeaders = this.getCustomHeaders()
for name, value of @_tempHeaders
delete allHeaders[name]
this.setCustomHeaders(allHeaders)
pushFrame: (name) ->
return true if this.native().switchToFrame(name)
# if switch by name fails - find index and try again
frame_no = this.native().evaluate(
(frame_name) ->
frames = document.querySelectorAll("iframe, frame")
(idx for f, idx in frames when f?['name'] == frame_name or f?['id'] == frame_name)[0]
, name)
frame_no? and this.native().switchToFrame(frame_no)
popFrame: (pop_all = false)->
if pop_all
this.native().switchToMainFrame()
else
this.native().switchToParentFrame()
dimensions: ->
scroll = this.scrollPosition()
viewport = this.viewportSize()
top: scroll.top, bottom: scroll.top + viewport.height,
left: scroll.left, right: scroll.left + viewport.width,
viewport: viewport
document: this.documentSize()
# A work around for http://code.google.com/p/phantomjs/issues/detail?id=277
validatedDimensions: ->
dimensions = this.dimensions()
document = dimensions.document
if dimensions.right > document.width
dimensions.left = Math.max(0, dimensions.left - (dimensions.right - document.width))
dimensions.right = document.width
if dimensions.bottom > document.height
dimensions.top = Math.max(0, dimensions.top - (dimensions.bottom - document.height))
dimensions.bottom = document.height
this.setScrollPosition(left: dimensions.left, top: dimensions.top)
dimensions
get: (id) ->
new Poltergeist.Node(this, id)
# Before each mouse event we make sure that the mouse is moved to where the
# event will take place. This deals with e.g. :hover changes.
mouseEvent: (name, x, y, button = 'left') ->
this.sendEvent('mousemove', x, y)
this.sendEvent(name, x, y, button)
evaluate: (fn, args...) ->
this.injectAgent()
result = this.native().evaluate("function() {
var page_id = arguments[0];
var args = [];
for(var i=1; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
args.push(window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element);
} else {
args.push(arguments[i])
}
}
var _result = #{this.stringifyCall(fn, "args")};
return window.__poltergeist.wrapResults(_result, page_id); }", @id, args...)
result
execute: (fn, args...) ->
this.native().evaluate("function() {
for(var i=0; i < arguments.length; i++){
if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){
arguments[i] = window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element;
}
}
#{this.stringifyCall(fn)} }", args...)
stringifyCall: (fn, args_name = "arguments") ->
"(#{fn.toString()}).apply(this, #{args_name})"
bindCallback: (name) ->
@native()[name] = =>
result = @[name + 'Native'].apply(@, arguments) if @[name + 'Native']? # For internal callbacks
@[name].apply(@, arguments) if result != false && @[name]? # For externally set callbacks
return true
# Any error raised here or inside the evaluate will get reported to
# phantom.onError. If result is null, that means there was an error
# inside the agent.
runCommand: (name, args) ->
result = this.evaluate(
(name, args) -> __poltergeist.externalCall(name, args),
name, args
)
if result?.error?
switch result.error.message
when 'PoltergeistAgent.ObsoleteNode'
throw new Poltergeist.ObsoleteNode
when 'PoltergeistAgent.InvalidSelector'
[method, selector] = args
throw new Poltergeist.InvalidSelector(method, selector)
else
throw new Poltergeist.BrowserError(result.error.message, result.error.stack)
else
result?.value
canGoBack: ->
this.native().canGoBack
canGoForward: ->
this.native().canGoForward
normalizeURL: (url) ->
parser = document.createElement('a')
parser.href = url
return parser.href
clearMemoryCache: ->
clearMemoryCache = this.native().clearMemoryCache
if typeof clearMemoryCache == "function"
clearMemoryCache()
else
throw new Poltergeist.UnsupportedFeature("clearMemoryCache is supported since PhantomJS 2.0.0")
_overrideNativeEvaluate: ->
# PhantomJS 1.9.x WebPage#evaluate depends on the browser context JSON, this replaces it
# with the evaluate from 2.1.1 which uses the PhantomJS JSON
@_native.evaluate = `function (func, args) {
function quoteString(str) {
var c, i, l = str.length, o = '"';
for (i = 0; i < l; i += 1) {
c = str.charAt(i);
if (c >= ' ') {
if (c === '\\' || c === '"') {
o += '\\';
}
o += c;
} else {
switch (c) {
case '\b':
o += '\\b';
break;
case '\f':
o += '\\f';
break;
case '\n':
o += '\\n';
break;
case '\r':
o += '\\r';
break;
case '\t':
o += '\\t';
break;
default:
c = c.charCodeAt();
o += '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}
}
}
return o + '"';
}
function detectType(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
} else if (value instanceof RegExp) {
s = 'regexp';
} else if (value instanceof Date) {
s = 'date';
}
} else {
s = 'null';
}
}
return s;
}
var str, arg, argType, i, l;
if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) {
throw "Wrong use of WebPage#evaluate";
}
str = 'function() { return (' + func.toString() + ')(';
for (i = 1, l = arguments.length; i < l; i++) {
arg = arguments[i];
argType = detectType(arg);
switch (argType) {
case "object": //< for type "object"
case "array": //< for type "array"
str += JSON.stringify(arg) + ","
break;
case "date": //< for type "date"
str += "new Date(" + JSON.stringify(arg) + "),"
break;
case "string": //< for type "string"
str += quoteString(arg) + ',';
break;
default: // for types: "null", "number", "function", "regexp", "undefined"
str += arg + ',';
break;
}
}
str = str.replace(/,$/, '') + '); }';
return this.evaluateJavaScript(str);
};`
|
[
{
"context": "odel'\n\n\nclass Task extends Model\n brainstemKey: \"tasks\"\n paramRoot: 'task'\n urlRoot: '/api/tasks'\n\n @",
"end": 86,
"score": 0.8911499977111816,
"start": 81,
"tag": "KEY",
"value": "tasks"
},
{
"context": "iations:\n project: \"projects\"\n assignees:... | spec/helpers/models/task.coffee | mavenlink/brainstem-js | 8 | Model = require '../../../src/model'
class Task extends Model
brainstemKey: "tasks"
paramRoot: 'task'
urlRoot: '/api/tasks'
@associations:
project: "projects"
assignees: ["users"]
sub_tasks: ["tasks"]
parent: "tasks"
module.exports = Task
| 163523 | Model = require '../../../src/model'
class Task extends Model
brainstemKey: "<KEY>"
paramRoot: 'task'
urlRoot: '/api/tasks'
@associations:
project: "projects"
assignees: ["users"]
sub_tasks: ["tasks"]
parent: "tasks"
module.exports = Task
| true | Model = require '../../../src/model'
class Task extends Model
brainstemKey: "PI:KEY:<KEY>END_PI"
paramRoot: 'task'
urlRoot: '/api/tasks'
@associations:
project: "projects"
assignees: ["users"]
sub_tasks: ["tasks"]
parent: "tasks"
module.exports = Task
|
[
{
"context": "email.</i></p>\n <Input type=\"text\" name=\"username\" valueLink={@props.username} addonBefore={userGly",
"end": 820,
"score": 0.9977279305458069,
"start": 812,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ps.username} addonBefore={userGlyph} placeh... | picoCTF-web/web/coffee/front-page.coffee | archituiet/picoCTF | 0 | Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
Glyphicon = ReactBootstrap.Glyphicon
ButtonInput = ReactBootstrap.ButtonInput
ButtonGroup = ReactBootstrap.ButtonGroup
Alert = ReactBootstrap.Alert
update = React.addons.update
Recaptcha = ReactRecaptcha
LoginForm = React.createClass
render: ->
userGlyph = <Glyphicon glyph="user"/>
lockGlyph = <Glyphicon glyph="lock"/>
formButton = if @props.status == "Login" then \
q = "'" #My syntax highlighting can't handle literal quotes in jsx. :(
if @props.status == "Reset"
<Panel>
<form onSubmit={@props.onPasswordReset}>
<p><i>A password reset link will be sent the user{q}s email.</i></p>
<Input type="text" name="username" valueLink={@props.username} addonBefore={userGlyph} placeholder="Username" required/>
<div style={{height: "70px"}}/>
<Row>
<Col md={6}>
<ButtonInput type="submit">Reset Password</ButtonInput>
</Col>
<Col md={6}>
<span className="pull-right pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
</Col>
</Row>
</form>
</Panel>
else
showGroupMessage = (->
<Alert bsStyle="info">
You are registering as a member of <strong>{@props.groupName}</strong>.
</Alert>
).bind this
showEmailFilter = (->
<Alert bsStyle="warning">
You can register provided you have an email for one of these domains: <strong>{@props.emailFilter.join ", "}</strong>.
</Alert>
).bind this
generateRecaptcha = ( ->
if @props.reCAPTCHA_public_key
<Recaptcha sitekey={@props.reCAPTCHA_public_key} verifyCallback={@props.onRecaptchaSuccess} expiredCallback={@props.onRecaptchaExpire} render="explicit" />
).bind this
# Toggle input fields according to user type
showOrHide = ((prop, inputName) ->
inputs = {
firstname: false
lastname: false
url: false
grade: false
teacherlevel: false
subjectstaught: false
schoolcountry: false
residencecountry: true
affiliation: true
zipcode: false
studentOnly: false
teacherOnly: false
referrer: false
gender: true
}
switch @props.usertype.value
when "student"
inputs.grade = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.studentOnly = true
inputs.referrer = true
inputs.url = true
when "college"
inputs.schoolcountry = true
inputs.zipcode = true
inputs.url = true
when "teacher"
inputs.teacherlevel = true
inputs.subjectstaught = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.teacherOnly = true
inputs.referrer = true
inputs.url = true
when "other"
inputs.url = true
else
inputs.affiliation = false
show = inputs[inputName]
if prop == "class"
if show then 'show' else 'hide'
else if prop == "disabled"
if show then false else true
).bind this
generateCountries = ( ->
countryList =
"United States": "US"
"Canada": "CA"
"Afghanistan": "AF"
"Albania": "AL"
"Algeria": "DZ"
"Andorra": "AD"
"Angola": "AO"
"Antigua and Barbuda": "AG"
"Argentina": "AR"
"Armenia": "AM"
"Aruba": "AW"
"Australia": "AU"
"Austria": "AT"
"Azerbaijan": "AZ"
"Bahamas, The": "BS"
"Bahrain": "BH"
"Bangladesh": "BD"
"Barbados": "BB"
"Belarus": "BY"
"Belgium": "BE"
"Belize": "BZ"
"Benin": "BJ"
"Bhutan": "BT"
"Bolivia": "BO"
"Bosnia and Herzegovina": "BA"
"Botswana": "BW"
"Brazil": "BR"
"Brunei": "BN"
"Bulgaria": "BG"
"Burkina Faso": "BF"
"Burma": "MM"
"Burundi": "BI"
"Cabo Verde": "CV"
"Cambodia": "KH"
"Cameroon": "CM"
"Central African Republic":"CF"
"Chad": "TD"
"Chile": "CL"
"China": "CN"
"Colombia": "CO"
"Comoros": "KM"
"Congo (Brazzaville)": "CG"
"Congo (Kinshasa)": "CD"
"Costa Rica": "CR"
"Côte d'Ivoire": "CI"
"Croatia": "HR"
"Cuba": "CU"
"Curacao": "CW"
"Cyprus": "CY"
"Czechia": "CZ"
"Denmark": "DK"
"Djibouti": "DJ"
"Dominica": "DM"
"Dominican Republic": "DO"
"Ecuador": "EC"
"Egypt": "EG"
"El Salvador": "SV"
"Equatorial Guinea": "GQ"
"Eritrea": "ER"
"Estonia": "EE"
"Eswatini": "SZ"
"Ethiopia": "ET"
"Fiji": "FJ"
"Finland": "FI"
"France": "FR"
"Gabon": "GA"
"Gambia, The": "GM"
"Georgia": "GE"
"Germany": "DE"
"Ghana": "GH"
"Greece": "GR"
"Grenada": "GD"
"Guatemala": "GT"
"Guinea": "GN"
"Guinea-Bissau": "GW"
"Guyana": "GY"
"Haiti": "HT"
"Holy See": "VA"
"Honduras": "HN"
"Hong Kong": "HK"
"Hungary": "HU"
"Iceland": "IS"
"India": "IN"
"Indonesia": "ID"
"Iran": "IR"
"Iraq": "IQ"
"Ireland": "IE"
"Israel": "IL"
"Italy": "IT"
"Jamaica": "JM"
"Japan": "JP"
"Jordan": "JO"
"Kazakhstan": "KZ"
"Kenya": "KE"
"Kiribati": "KI"
"Korea, North": "KP"
"Korea, South": "KR"
"Kosovo": "XK"
"Kuwait": "KW"
"Kyrgyzstan": "KG"
"Laos": "LA"
"Latvia": "LV"
"Lebanon": "LB"
"Lesotho": "LS"
"Liberia": "LR"
"Libya": "LY"
"Liechtenstein": "LI"
"Lithuania": "LT"
"Luxembourg": "LU"
"Macau": "MO"
"Macedonia": "MK"
"Madagascar": "MG"
"Malawi": "MW"
"Malaysia": "MY"
"Maldives": "MV"
"Mali": "ML"
"Malta": "MT"
"Marshall Islands": "MH"
"Mauritania": "MR"
"Mauritius": "MU"
"Mexico": "MX"
"Micronesia": "FM"
"Moldova": "MD"
"Monaco": "MC"
"Mongolia": "MN"
"Montenegro": "ME"
"Morocco": "MA"
"Mozambique": "MZ"
"Namibia": "NA"
"Nauru": "NR"
"Nepal": "NP"
"Netherlands": "NL"
"New Zealand": "NZ"
"Nicaragua": "NI"
"Niger": "NE"
"Nigeria": "NG"
"Norway": "NO"
"Oman": "OM"
"Pakistan": "PK"
"Palau": "PW"
"Palestine": "PS"
"Panama": "PA"
"Papua New Guinea": "PG"
"Paraguay": "PY"
"Peru": "PE"
"Philippines": "PH"
"Poland": "PL"
"Portugal": "PT"
"Qatar": "QA"
"Romania": "RO"
"Russia": "RU"
"Rwanda": "RW"
"Saint Kitts and Nevis": "KN"
"Saint Lucia": "LC"
"Saint Vincent and the Grenadines": "VC"
"Samoa": "WS"
"San Marino": "SM"
"Sao Tome and Principe": "ST"
"Saudi Arabia": "SA"
"Senegal": "SN"
"Serbia": "RS"
"Seychelles": "SC"
"Sierra Leone": "SL"
"Singapore": "SG"
"Sint Maarten": "SX"
"Slovakia": "SK"
"Slovenia": "SI"
"Solomon Islands": "SB"
"Somalia": "SO"
"South Africa": "ZA"
"South Sudan": "SS"
"Spain": "ES"
"Sri Lanka": "LK"
"Sudan": "SD"
"Suriname": "SR"
"Sweden": "SE"
"Switzerland": "CH"
"Syria": "SY"
"Taiwan": "TW"
"Tajikistan": "TJ"
"Tanzania": "TZ"
"Thailand": "TH"
"Timor-Leste": "TL"
"Togo": "TG"
"Tonga": "TO"
"Trinidad and Tobago": "TT"
"Tunisia": "TN"
"Turkey": "TR"
"Turkmenistan": "TM"
"Tuvalu": "TV"
"Uganda": "UG"
"Ukraine": "UA"
"United Arab Emirates": "AE"
"United Kingdom": "GB"
"Uruguay": "UY"
"Uzbekistan": "UZ"
"Vanuatu": "VU"
"Venezuela": "VE"
"Vietnam": "VN"
"Yemen": "YE"
"Zambia": "ZM"
"Zimbabwe": "ZW"
for country, abbrev of countryList
<option value=abbrev>{country}</option>
)
registrationForm = if @props.status == "Register" then \
<div>
<Row>
<div>
{if @props.groupName.length > 0 then showGroupMessage() else <span/>}
{if @props.emailFilter.length > 0 and not @props.rid then showEmailFilter() else <span/>}
<br/>
</div>
<Col md={6} className={showOrHide('class', 'firstname')}>
<Input type="text" id="firstname" valueLink={@props.firstname} label="First Name" placeholder="Jane"/>
</Col>
<Col md={6} className={showOrHide('class', 'lastname')}>
<Input type="text" id="lastname" valueLink={@props.lastname} label="Last Name" placeholder="Doe"/>
</Col>
<Col md={12}>
<Input type="email" name="email" id="email" valueLink={@props.email} label="E-mail *" placeholder="email@example.com" required/>
</Col>
</Row>
<Row>
<Col md={12} className={showOrHide('class', 'residencecountry')}>
<Input type="select" name="residencecountry" id="residencecountry" defaultValue="" valueLink={@props.residencecountry} label="Country/Region of Residence *" placeholder="Country of Residence" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="usertype" id="usertype" defaultValue="" label="Status *" required valueLink={@props.usertype}>
<option value="" disabled>-Select Category-</option>
<option value="student">Middle/High School Student</option>
<option value="teacher">Teacher/Instructor</option>
<option value="college">College Student</option>
<option value="other">Other</option>
</Input>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'affiliation')}>
<Input type="text" name="affiliation" id="affiliation" valueLink={@props.affiliation} label={if @props.usertype.value == "other" then "Organization Name *" else "School Name *"} placeholder="Example School, Pittsburgh, PA" maxlength="50" required/>
<p className="help-block">
Your school or organization name may be visible to other users.
</p>
</Col>
<Col md={6} className={showOrHide('class', 'url')}>
<Input type="text" name="url" disabled={showOrHide( 'disabled', 'url')} id="url" valueLink={@props.url} label={if @props.usertype.value == "other" then "Organization URL (optional)" else "School URL (optional)"} placeholder={if @props.usertype.value == "other" then "Organization URL" else "School URL"}/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'grade')}>
<Input type="number" min="1" max="12" name="grade" disabled={showOrHide('disabled','grade')} id="grade" valueLink={@props.grade} label="Your Current Grade/Year (1-12) *" placeholder="Your Current Grade/Year" required/>
</Col>
<Col md={6} className={showOrHide('class', 'teacherlevel')}>
<label>I teach *</label>
<Input type="checkbox" checkedLink={@props.teacher_middleschool} label="Middle School"/>
<Input type="checkbox" checkedLink={@props.teacher_highschool} label="High School"/>
<Input type="checkbox" checkedLink={@props.teacher_afterschoolclub} label="After School or Club"/>
<Input type="checkbox" checkedLink={@props.teacher_homeschool} label="Home School"/>
</Col>
<Col md={6} className={showOrHide('class', 'subjectstaught')}>
<Input type="text" name="subjectstaught" disabled={showOrHide('disabled', 'subjectstaught')} id="subjectstaught" valueLink={@props.subjectstaught} label="Subjects Taught *" required/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'zipcode')}>
<Input type="text" name="zipcode" disabled={showOrHide('disabled','zipcode')} id="zipcode" valueLink={@props.zipcode} label="School Zip Code/Postal Code *" placeholder="School Zipcode/Postal Code" required/>
</Col>
<Col md={6} className={showOrHide('class', 'schoolcountry')}>
<Input type="select" name="schoolcountry" disabled={showOrHide('disabled','schoolcountry')} defaultValue="" id="schoolcountry" valueLink={@props.schoolcountry} label="School Country *" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'referrer')}>
<Col md={12}>
<Input className={showOrHide('disabled', 'referrer')} type="select" name="referrer" defaultValue="" id="referrer" label="How did you hear about picoCTF?" valueLink={@props.referrer}>
<option value="" disabled>-Select-</option>
<option value="socialmedia">Social Media</option>
<option className={showOrHide('class', 'studentOnly')} value="friends">Friends</option>
<option <option className={showOrHide('class', 'studentOnly')} value="teacher">Teacher</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="students">Students</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="colleagues_groupemail">Colleagues or group email</option>
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'gender')}>
<Col md={if @props.gender.value == "other" then 6 else 12}>
<Input type="select" id="gender" name="gender" defaultValue="" label="Which gender identity do you most identify with?" valueLink={@props.gender}>
<option value="">-Select-</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
<option value="transgenderwoman">Transgender Woman</option>
<option value="transgenderman">Transgender Man</option>
<option value="gfnc">Gender Fluid/Non-Conforming</option>
<option value="other">I prefer: (fill in)</option>
</Input>
</Col>
<Col md={6} className={if @props.gender.value == "other" then "show" else "hide"}>
<br/>
<Input type="text" name="genderother" disabled={if @props.gender.value == "other" then false else true} id="genderother" valueLink={@props.genderother} label="Gender preference" placeholder=""/>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="age" id="age" defaultValue="" label="What is your age? *" valueLink={@props.age} required>
<option value="">-Select-</option>
<option value="13-17">I am between 13 and 17 years of age</option>
<option value="18+">I am 18 years of age or older</option>
</Input>
</Col>
</Row>
<Row className={if @props.age.value == "13-17" then "show" else "hide"}>
<Col md={12}>
<p className="help-block">
Parent or legal guardian must insert contact email address. By inserting email address and finalizing
registration, parent/legal guardian is hereby consenting to their child’s registration under the Terms of
Use, Privacy Statement and any applicable Competition Rules.
</p>
<Input type="email" name="parentemail" disabled={if @props.age.value == "13-17" then false else true} id="parentemail" valueLink={@props.parentemail} label="Parent's E-mail *" required placeholder="email@example.com" />
</Col>
</Row>
<Row>
<Col md={8}>
{generateRecaptcha()}
</Col>
<Col md={4} className="text-right">
<ButtonInput className="btn-primary" type="submit">Register</ButtonInput>
</Col>
</Row>
</div> else <span/>
<Panel>
<form key={@props.status} onSubmit={if @props.status == "Login" then @props.onLogin else @props.onRegistration}>
<Input type="text" id="username" valueLink={@props.username} addonBefore={userGlyph} label="Username" required/>
<p className={if @props.status == "Login" then "hide" else "help-block"}>Your username may be visible to other users.
Do not include your real name or any other personal information.</p>
<Input type="password" id="password" valueLink={@props.password} addonBefore={lockGlyph} label="Password" required/>
<Row>
<Col md={6}>
{if @props.status == "Register" then \
<span className="pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
else <span>
<Button type="submit">Login</Button>
<Button id="set-register" onClick={@props.setPage.bind null, "Register"}>Register</Button>
</span>}
</Col>
<Col md={6}>
<a className="pad" onClick={@props.setPage.bind null, "Reset"}>Need to reset your password?</a>
</Col>
</Row>
{registrationForm}
</form>
</Panel>
TeamManagementForm = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
team_name: ""
team_password: ""
onTeamRegistration: (e) ->
e.preventDefault()
if (!@state.team_name || !@state.team_password)
apiNotify({status: 0, message: "Invalid team name or password."})
else
data = {team_name: @state.team_name, team_password: @state.team_password}
apiCall "POST", "/api/v1/teams", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onTeamJoin: (e) ->
e.preventDefault()
data = {team_name: @state.team_name, team_password: @state.team_password}
apiCall "POST", "/api/v1/team/join", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
render: ->
towerGlyph = <Glyphicon glyph="tower"/>
lockGlyph = <Glyphicon glyph="lock"/>
<Panel>
<p>Your team name may be visible to other users. Do not include your real name or any other personal information.
Also, to avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p>
<form onSubmit={@onTeamJoin}>
<Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/>
<Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/>
<Col md={6}>
<span> <Button type="submit">Join Team</Button>
<Button onClick={@onTeamRegistration}>Register Team</Button>
</span>
</Col>
<Col md={6}>
<a href="#" onClick={() -> document.location.href = "/profile"}>Play as an individual.</a>
</Col>
</form>
</Panel>
AuthPanel = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
params = $.deparam $.param.fragment()
page: "Login"
settings: {}
gid: params.g
rid: params.r
status: params.status
groupName: ""
captcha: ""
regStats: {}
componentWillMount: ->
if @state.status == "verified"
apiNotify({status: 1, message: "Your account has been successfully verified. Please login."})
else if @state.status == "verification_error"
apiNotify({status: 0, message: "Invalid verification code. Please contact an administrator."})
if @state.gid
apiCall "GET", "/api/v1/groups/" + @state.gid
.success ((data) ->
@setState update @state,
groupName: $set: data.name
affiliation: $set: data.name
settings: $merge: data.settings
page: $set: "Register"
).bind this
else
apiCall "GET", "/api/v1/status"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/user"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/stats/registration"
.success ((data) ->
@setState update @state,
regStats: $set: data
).bind this
onRegistration: (e) ->
e.preventDefault()
if @state.settings.enable_captcha && @state.captcha == ""
apiNotify {status: 0, message: "ReCAPTCHA required."}
return
form = {}
form.gid = @state.gid
form.rid = @state.rid
form.username = @state.username
form.password = @state.password
form.firstname = @state.firstname
form.lastname = @state.lastname
form.email = @state.email
form.affiliation = @state.affiliation
form.usertype = @state.usertype
form.demo = {}
if @state.demo_gender == "other"
@state.demo_gender = @state.demo_genderother
delete @state.demo_genderother
for k,v of @state
if k.substr(0,5) == "demo_"
form.demo[k.substr(5)] = v
if @state.usertype in ["student", "teacher"]
form.country = form.demo.schoolcountry
else
form.country = form.demo.residencecountry
form['g-recaptcha-response'] = @state.captcha
apiCall "POST", "/api/v1/users", form
.success ((data) ->
verificationAlert =
status: 1
message: "You have been sent a verification email. You will need to complete this step before logging in."
successAlert =
status: 1
message: "User " + @state.username + " registered successfully!"
if @state.settings.email_verification and not @state.rid
apiNotify verificationAlert
@setPage "Login"
if @state.settings.max_team_size > 1
document.location.hash = "#team-builder"
else
apiCall "POST", "/api/v1/user/login", {"username": @state.username, "password": @state.password}
.success ((loginData) ->
apiCall "GET", "/api/v1/user"
.success ((userData) ->
if data.teacher
apiNotify successAlert, "/profile"
else if @state.settings.max_team_size > 1
apiNotify successAlert
@setPage "Team Management"
else
apiNotify successAlert, "/profile"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onPasswordReset: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/reset_password/request", {username: @state.username}
.success ((resp) ->
apiNotify {status: 1, message: "A password reset link has been sent to the email address provided during registration."}
@setPage "Login"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onLogin: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/login", {username: @state.username, password: @state.password}
.success ->
# Get teacher status
apiCall "GET", "/api/v1/user"
.success ((data) ->
if document.location.hash == "#team-builder" and not data.teacher
@setPage "Team Management"
else
if data.teacher
document.location.href = "/classroom"
else
document.location.href = "/profile"
)
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
setPage: (page) ->
@setState update @state,
page: $set: page
onRecaptchaSuccess: (captcha) ->
@setState update @state,
captcha: $set: captcha
onRecaptchaExpire: () ->
@setState update @state,
captcha: $set: ""
render: ->
links =
username: @linkState "username"
password: @linkState "password"
lastname: @linkState "lastname"
firstname: @linkState "firstname"
email: @linkState "email"
affiliation: @linkState "affiliation"
usertype: @linkState "usertype"
age: @linkState "demo_age"
url: @linkState "demo_url"
residencecountry: @linkState "demo_residencecountry"
schoolcountry: @linkState "demo_schoolcountry"
zipcode: @linkState "demo_zipcode"
grade: @linkState "demo_grade"
referrer: @linkState "demo_referrer"
gender: @linkState "demo_gender"
genderother: @linkState "demo_genderother"
teacher_middleschool: @linkState "demo_teacher_middleschool"
teacher_highschool: @linkState "demo_teacher_highscool"
teacher_afterschoolclub: @linkState "demo_teacher_afterschool"
teacher_homeschool: @linkState "demo_teacher_homeschool"
subjectstaught: @linkState "demo_subjectstaught"
parentemail: @linkState "demo_parentemail"
showRegStats = (()->
if @state.regStats
<Panel>
<h4><strong>Registration Statistics</strong></h4>
<p>
<strong>{@state.regStats.users}</strong> users have registered, <strong>{@state.regStats.teamed_users}</strong> of
which have formed <strong>{@state.regStats.teams}</strong> teams.<br />
<strong>{@state.regStats.groups}</strong> classrooms have been created by teachers.
</p>
</Panel>
).bind this
if @state.page == "Team Management"
<div>
<Row>
<Col md={6} mdOffset={3}>
<TeamManagementForm/>
</Col>
</Row>
</div>
else
<div>
<Row>
<Col md={6} mdOffset={3}>
<LoginForm setPage={@setPage} onRecaptchaSuccess={@onRecaptchaSuccess} onRecaptchaExpire={@onRecaptchaExpire}
status={@state.page} reCAPTCHA_public_key={@state.settings.reCAPTCHA_public_key}
onRegistration={@onRegistration} onLogin={@onLogin} onPasswordReset={@onPasswordReset}
emailFilter={@state.settings.email_filter} groupName={@state.groupName} rid={@state.rid}
gid={@state.gid} {...links}/>
{showRegStats()}
</Col>
</Row>
</div>
$ ->
redirectIfLoggedIn()
React.render <AuthPanel/>, document.getElementById("auth-box")
| 179966 | Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
Glyphicon = ReactBootstrap.Glyphicon
ButtonInput = ReactBootstrap.ButtonInput
ButtonGroup = ReactBootstrap.ButtonGroup
Alert = ReactBootstrap.Alert
update = React.addons.update
Recaptcha = ReactRecaptcha
LoginForm = React.createClass
render: ->
userGlyph = <Glyphicon glyph="user"/>
lockGlyph = <Glyphicon glyph="lock"/>
formButton = if @props.status == "Login" then \
q = "'" #My syntax highlighting can't handle literal quotes in jsx. :(
if @props.status == "Reset"
<Panel>
<form onSubmit={@props.onPasswordReset}>
<p><i>A password reset link will be sent the user{q}s email.</i></p>
<Input type="text" name="username" valueLink={@props.username} addonBefore={userGlyph} placeholder="Username" required/>
<div style={{height: "70px"}}/>
<Row>
<Col md={6}>
<ButtonInput type="submit">Reset Password</ButtonInput>
</Col>
<Col md={6}>
<span className="pull-right pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
</Col>
</Row>
</form>
</Panel>
else
showGroupMessage = (->
<Alert bsStyle="info">
You are registering as a member of <strong>{@props.groupName}</strong>.
</Alert>
).bind this
showEmailFilter = (->
<Alert bsStyle="warning">
You can register provided you have an email for one of these domains: <strong>{@props.emailFilter.join ", "}</strong>.
</Alert>
).bind this
generateRecaptcha = ( ->
if @props.reCAPTCHA_public_key
<Recaptcha sitekey={@props.reCAPTCHA_public_key} verifyCallback={@props.onRecaptchaSuccess} expiredCallback={@props.onRecaptchaExpire} render="explicit" />
).bind this
# Toggle input fields according to user type
showOrHide = ((prop, inputName) ->
inputs = {
firstname: false
lastname: false
url: false
grade: false
teacherlevel: false
subjectstaught: false
schoolcountry: false
residencecountry: true
affiliation: true
zipcode: false
studentOnly: false
teacherOnly: false
referrer: false
gender: true
}
switch @props.usertype.value
when "student"
inputs.grade = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.studentOnly = true
inputs.referrer = true
inputs.url = true
when "college"
inputs.schoolcountry = true
inputs.zipcode = true
inputs.url = true
when "teacher"
inputs.teacherlevel = true
inputs.subjectstaught = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.teacherOnly = true
inputs.referrer = true
inputs.url = true
when "other"
inputs.url = true
else
inputs.affiliation = false
show = inputs[inputName]
if prop == "class"
if show then 'show' else 'hide'
else if prop == "disabled"
if show then false else true
).bind this
generateCountries = ( ->
countryList =
"United States": "US"
"Canada": "CA"
"Afghanistan": "AF"
"Albania": "AL"
"Algeria": "DZ"
"Andorra": "AD"
"Angola": "AO"
"Antigua and Barbuda": "AG"
"Argentina": "AR"
"Armenia": "AM"
"Aruba": "AW"
"Australia": "AU"
"Austria": "AT"
"Azerbaijan": "AZ"
"Bahamas, The": "BS"
"Bahrain": "BH"
"Bangladesh": "BD"
"Barbados": "BB"
"Belarus": "BY"
"Belgium": "BE"
"Belize": "BZ"
"Benin": "BJ"
"Bhutan": "BT"
"Bolivia": "BO"
"Bosnia and Herzegovina": "BA"
"Botswana": "BW"
"Brazil": "BR"
"Brunei": "BN"
"Bulgaria": "BG"
"Burkina Faso": "BF"
"Burma": "MM"
"Burundi": "BI"
"Cabo Verde": "CV"
"Cambodia": "KH"
"Cameroon": "CM"
"Central African Republic":"CF"
"Chad": "TD"
"Chile": "CL"
"China": "CN"
"Colombia": "CO"
"Comoros": "KM"
"Congo (Brazzaville)": "CG"
"Congo (Kinshasa)": "CD"
"Costa Rica": "CR"
"Côte d'Ivoire": "CI"
"Croatia": "HR"
"Cuba": "CU"
"Curacao": "CW"
"Cyprus": "CY"
"Czechia": "CZ"
"Denmark": "DK"
"Djibouti": "DJ"
"Dominica": "DM"
"Dominican Republic": "DO"
"Ecuador": "EC"
"Egypt": "EG"
"El Salvador": "SV"
"Equatorial Guinea": "GQ"
"Eritrea": "ER"
"Estonia": "EE"
"Eswatini": "SZ"
"Ethiopia": "ET"
"Fiji": "FJ"
"Finland": "FI"
"France": "FR"
"Gabon": "GA"
"Gambia, The": "GM"
"Georgia": "GE"
"Germany": "DE"
"Ghana": "GH"
"Greece": "GR"
"Grenada": "GD"
"Guatemala": "GT"
"Guinea": "GN"
"Guinea-Bissau": "GW"
"Guyana": "GY"
"Haiti": "HT"
"Holy See": "VA"
"Honduras": "HN"
"Hong Kong": "HK"
"Hungary": "HU"
"Iceland": "IS"
"India": "IN"
"Indonesia": "ID"
"Iran": "IR"
"Iraq": "IQ"
"Ireland": "IE"
"Israel": "IL"
"Italy": "IT"
"Jamaica": "JM"
"Japan": "JP"
"Jordan": "JO"
"Kazakhstan": "KZ"
"Kenya": "KE"
"Kiribati": "KI"
"Korea, North": "KP"
"Korea, South": "KR"
"Kosovo": "XK"
"Kuwait": "KW"
"Kyrgyzstan": "KG"
"Laos": "LA"
"Latvia": "LV"
"Lebanon": "LB"
"Lesotho": "LS"
"Liberia": "LR"
"Libya": "LY"
"Liechtenstein": "LI"
"Lithuania": "LT"
"Luxembourg": "LU"
"Macau": "MO"
"Macedonia": "MK"
"Madagascar": "MG"
"Malawi": "MW"
"Malaysia": "MY"
"Maldives": "MV"
"Mali": "ML"
"Malta": "MT"
"Marshall Islands": "MH"
"Mauritania": "MR"
"Mauritius": "MU"
"Mexico": "MX"
"Micronesia": "FM"
"Moldova": "MD"
"Monaco": "MC"
"Mongolia": "MN"
"Montenegro": "ME"
"Morocco": "MA"
"Mozambique": "MZ"
"Namibia": "NA"
"Nauru": "NR"
"Nepal": "NP"
"Netherlands": "NL"
"New Zealand": "NZ"
"Nicaragua": "NI"
"Niger": "NE"
"Nigeria": "NG"
"Norway": "NO"
"Oman": "OM"
"Pakistan": "PK"
"Palau": "PW"
"Palestine": "PS"
"Panama": "PA"
"Papua New Guinea": "PG"
"Paraguay": "PY"
"Peru": "PE"
"Philippines": "PH"
"Poland": "PL"
"Portugal": "PT"
"Qatar": "QA"
"Romania": "RO"
"Russia": "RU"
"Rwanda": "RW"
"Saint Kitts and Nevis": "KN"
"Saint Lucia": "LC"
"Saint Vincent and the Grenadines": "VC"
"Samoa": "WS"
"San Marino": "SM"
"Sao Tome and Principe": "ST"
"Saudi Arabia": "SA"
"Senegal": "SN"
"Serbia": "RS"
"Seychelles": "SC"
"Sierra Leone": "SL"
"Singapore": "SG"
"Sint Maarten": "SX"
"Slovakia": "SK"
"Slovenia": "SI"
"Solomon Islands": "SB"
"Somalia": "SO"
"South Africa": "ZA"
"South Sudan": "SS"
"Spain": "ES"
"Sri Lanka": "LK"
"Sudan": "SD"
"Suriname": "SR"
"Sweden": "SE"
"Switzerland": "CH"
"Syria": "SY"
"Taiwan": "TW"
"Tajikistan": "TJ"
"Tanzania": "TZ"
"Thailand": "TH"
"Timor-Leste": "TL"
"Togo": "TG"
"Tonga": "TO"
"Trinidad and Tobago": "TT"
"Tunisia": "TN"
"Turkey": "TR"
"Turkmenistan": "TM"
"Tuvalu": "TV"
"Uganda": "UG"
"Ukraine": "UA"
"United Arab Emirates": "AE"
"United Kingdom": "GB"
"Uruguay": "UY"
"Uzbekistan": "UZ"
"Vanuatu": "VU"
"Venezuela": "VE"
"Vietnam": "VN"
"Yemen": "YE"
"Zambia": "ZM"
"Zimbabwe": "ZW"
for country, abbrev of countryList
<option value=abbrev>{country}</option>
)
registrationForm = if @props.status == "Register" then \
<div>
<Row>
<div>
{if @props.groupName.length > 0 then showGroupMessage() else <span/>}
{if @props.emailFilter.length > 0 and not @props.rid then showEmailFilter() else <span/>}
<br/>
</div>
<Col md={6} className={showOrHide('class', 'firstname')}>
<Input type="text" id="firstname" valueLink={@props.firstname} label="First Name" placeholder="<NAME>"/>
</Col>
<Col md={6} className={showOrHide('class', 'lastname')}>
<Input type="text" id="lastname" valueLink={@props.lastname} label="Last Name" placeholder="<NAME>"/>
</Col>
<Col md={12}>
<Input type="email" name="email" id="email" valueLink={@props.email} label="E-mail *" placeholder="<EMAIL>" required/>
</Col>
</Row>
<Row>
<Col md={12} className={showOrHide('class', 'residencecountry')}>
<Input type="select" name="residencecountry" id="residencecountry" defaultValue="" valueLink={@props.residencecountry} label="Country/Region of Residence *" placeholder="Country of Residence" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="usertype" id="usertype" defaultValue="" label="Status *" required valueLink={@props.usertype}>
<option value="" disabled>-Select Category-</option>
<option value="student">Middle/High School Student</option>
<option value="teacher">Teacher/Instructor</option>
<option value="college">College Student</option>
<option value="other">Other</option>
</Input>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'affiliation')}>
<Input type="text" name="affiliation" id="affiliation" valueLink={@props.affiliation} label={if @props.usertype.value == "other" then "Organization Name *" else "School Name *"} placeholder="Example School, Pittsburgh, PA" maxlength="50" required/>
<p className="help-block">
Your school or organization name may be visible to other users.
</p>
</Col>
<Col md={6} className={showOrHide('class', 'url')}>
<Input type="text" name="url" disabled={showOrHide( 'disabled', 'url')} id="url" valueLink={@props.url} label={if @props.usertype.value == "other" then "Organization URL (optional)" else "School URL (optional)"} placeholder={if @props.usertype.value == "other" then "Organization URL" else "School URL"}/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'grade')}>
<Input type="number" min="1" max="12" name="grade" disabled={showOrHide('disabled','grade')} id="grade" valueLink={@props.grade} label="Your Current Grade/Year (1-12) *" placeholder="Your Current Grade/Year" required/>
</Col>
<Col md={6} className={showOrHide('class', 'teacherlevel')}>
<label>I teach *</label>
<Input type="checkbox" checkedLink={@props.teacher_middleschool} label="Middle School"/>
<Input type="checkbox" checkedLink={@props.teacher_highschool} label="High School"/>
<Input type="checkbox" checkedLink={@props.teacher_afterschoolclub} label="After School or Club"/>
<Input type="checkbox" checkedLink={@props.teacher_homeschool} label="Home School"/>
</Col>
<Col md={6} className={showOrHide('class', 'subjectstaught')}>
<Input type="text" name="subjectstaught" disabled={showOrHide('disabled', 'subjectstaught')} id="subjectstaught" valueLink={@props.subjectstaught} label="Subjects Taught *" required/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'zipcode')}>
<Input type="text" name="zipcode" disabled={showOrHide('disabled','zipcode')} id="zipcode" valueLink={@props.zipcode} label="School Zip Code/Postal Code *" placeholder="School Zipcode/Postal Code" required/>
</Col>
<Col md={6} className={showOrHide('class', 'schoolcountry')}>
<Input type="select" name="schoolcountry" disabled={showOrHide('disabled','schoolcountry')} defaultValue="" id="schoolcountry" valueLink={@props.schoolcountry} label="School Country *" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'referrer')}>
<Col md={12}>
<Input className={showOrHide('disabled', 'referrer')} type="select" name="referrer" defaultValue="" id="referrer" label="How did you hear about picoCTF?" valueLink={@props.referrer}>
<option value="" disabled>-Select-</option>
<option value="socialmedia">Social Media</option>
<option className={showOrHide('class', 'studentOnly')} value="friends">Friends</option>
<option <option className={showOrHide('class', 'studentOnly')} value="teacher">Teacher</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="students">Students</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="colleagues_groupemail">Colleagues or group email</option>
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'gender')}>
<Col md={if @props.gender.value == "other" then 6 else 12}>
<Input type="select" id="gender" name="gender" defaultValue="" label="Which gender identity do you most identify with?" valueLink={@props.gender}>
<option value="">-Select-</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
<option value="transgenderwoman">Transgender Woman</option>
<option value="transgenderman">Transgender Man</option>
<option value="gfnc">Gender Fluid/Non-Conforming</option>
<option value="other">I prefer: (fill in)</option>
</Input>
</Col>
<Col md={6} className={if @props.gender.value == "other" then "show" else "hide"}>
<br/>
<Input type="text" name="genderother" disabled={if @props.gender.value == "other" then false else true} id="genderother" valueLink={@props.genderother} label="Gender preference" placeholder=""/>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="age" id="age" defaultValue="" label="What is your age? *" valueLink={@props.age} required>
<option value="">-Select-</option>
<option value="13-17">I am between 13 and 17 years of age</option>
<option value="18+">I am 18 years of age or older</option>
</Input>
</Col>
</Row>
<Row className={if @props.age.value == "13-17" then "show" else "hide"}>
<Col md={12}>
<p className="help-block">
Parent or legal guardian must insert contact email address. By inserting email address and finalizing
registration, parent/legal guardian is hereby consenting to their child’s registration under the Terms of
Use, Privacy Statement and any applicable Competition Rules.
</p>
<Input type="email" name="parentemail" disabled={if @props.age.value == "13-17" then false else true} id="parentemail" valueLink={@props.parentemail} label="Parent's E-mail *" required placeholder="<EMAIL>" />
</Col>
</Row>
<Row>
<Col md={8}>
{generateRecaptcha()}
</Col>
<Col md={4} className="text-right">
<ButtonInput className="btn-primary" type="submit">Register</ButtonInput>
</Col>
</Row>
</div> else <span/>
<Panel>
<form key={@props.status} onSubmit={if @props.status == "Login" then @props.onLogin else @props.onRegistration}>
<Input type="text" id="username" valueLink={@props.username} addonBefore={userGlyph} label="Username" required/>
<p className={if @props.status == "Login" then "hide" else "help-block"}>Your username may be visible to other users.
Do not include your real name or any other personal information.</p>
<Input type="<PASSWORD>" id="password" valueLink={@props.password} addonBefore={lockGlyph} label="Password" required/>
<Row>
<Col md={6}>
{if @props.status == "Register" then \
<span className="pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
else <span>
<Button type="submit">Login</Button>
<Button id="set-register" onClick={@props.setPage.bind null, "Register"}>Register</Button>
</span>}
</Col>
<Col md={6}>
<a className="pad" onClick={@props.setPage.bind null, "Reset"}>Need to reset your password?</a>
</Col>
</Row>
{registrationForm}
</form>
</Panel>
TeamManagementForm = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
team_name: ""
team_password: ""
onTeamRegistration: (e) ->
e.preventDefault()
if (!@state.team_name || !@state.team_password)
apiNotify({status: 0, message: "Invalid team name or password."})
else
data = {team_name: @state.team_name, team_password: @state.team_password}
apiCall "POST", "/api/v1/teams", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onTeamJoin: (e) ->
e.preventDefault()
data = {team_name: @state.team_name, team_password: <PASSWORD>}
apiCall "POST", "/api/v1/team/join", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
render: ->
towerGlyph = <Glyphicon glyph="tower"/>
lockGlyph = <Glyphicon glyph="lock"/>
<Panel>
<p>Your team name may be visible to other users. Do not include your real name or any other personal information.
Also, to avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p>
<form onSubmit={@onTeamJoin}>
<Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/>
<Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/>
<Col md={6}>
<span> <Button type="submit">Join Team</Button>
<Button onClick={@onTeamRegistration}>Register Team</Button>
</span>
</Col>
<Col md={6}>
<a href="#" onClick={() -> document.location.href = "/profile"}>Play as an individual.</a>
</Col>
</form>
</Panel>
AuthPanel = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
params = $.deparam $.param.fragment()
page: "Login"
settings: {}
gid: params.g
rid: params.r
status: params.status
groupName: ""
captcha: ""
regStats: {}
componentWillMount: ->
if @state.status == "verified"
apiNotify({status: 1, message: "Your account has been successfully verified. Please login."})
else if @state.status == "verification_error"
apiNotify({status: 0, message: "Invalid verification code. Please contact an administrator."})
if @state.gid
apiCall "GET", "/api/v1/groups/" + @state.gid
.success ((data) ->
@setState update @state,
groupName: $set: data.name
affiliation: $set: data.name
settings: $merge: data.settings
page: $set: "Register"
).bind this
else
apiCall "GET", "/api/v1/status"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/user"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/stats/registration"
.success ((data) ->
@setState update @state,
regStats: $set: data
).bind this
onRegistration: (e) ->
e.preventDefault()
if @state.settings.enable_captcha && @state.captcha == ""
apiNotify {status: 0, message: "ReCAPTCHA required."}
return
form = {}
form.gid = @state.gid
form.rid = @state.rid
form.username = @state.username
form.password = <PASSWORD>
form.firstname = @state.firstname
form.lastname = @state.lastname
form.email = @state.email
form.affiliation = @state.affiliation
form.usertype = @state.usertype
form.demo = {}
if @state.demo_gender == "other"
@state.demo_gender = @state.demo_genderother
delete @state.demo_genderother
for k,v of @state
if k.substr(0,5) == "demo_"
form.demo[k.substr(5)] = v
if @state.usertype in ["student", "teacher"]
form.country = form.demo.schoolcountry
else
form.country = form.demo.residencecountry
form['g-recaptcha-response'] = @state.captcha
apiCall "POST", "/api/v1/users", form
.success ((data) ->
verificationAlert =
status: 1
message: "You have been sent a verification email. You will need to complete this step before logging in."
successAlert =
status: 1
message: "User " + @state.username + " registered successfully!"
if @state.settings.email_verification and not @state.rid
apiNotify verificationAlert
@setPage "Login"
if @state.settings.max_team_size > 1
document.location.hash = "#team-builder"
else
apiCall "POST", "/api/v1/user/login", {"username": @state.username, "password": <PASSWORD>}
.success ((loginData) ->
apiCall "GET", "/api/v1/user"
.success ((userData) ->
if data.teacher
apiNotify successAlert, "/profile"
else if @state.settings.max_team_size > 1
apiNotify successAlert
@setPage "Team Management"
else
apiNotify successAlert, "/profile"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onPasswordReset: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/reset_password/request", {username: @state.username}
.success ((resp) ->
apiNotify {status: 1, message: "A password reset link has been sent to the email address provided during registration."}
@setPage "Login"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onLogin: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/login", {username: @state.username, password:<PASSWORD> @state.<PASSWORD>}
.success ->
# Get teacher status
apiCall "GET", "/api/v1/user"
.success ((data) ->
if document.location.hash == "#team-builder" and not data.teacher
@setPage "Team Management"
else
if data.teacher
document.location.href = "/classroom"
else
document.location.href = "/profile"
)
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
setPage: (page) ->
@setState update @state,
page: $set: page
onRecaptchaSuccess: (captcha) ->
@setState update @state,
captcha: $set: captcha
onRecaptchaExpire: () ->
@setState update @state,
captcha: $set: ""
render: ->
links =
username: @linkState "username"
password: <PASSWORD> "<PASSWORD>"
lastname: @linkState "lastname"
firstname: @linkState "firstname"
email: @linkState "email"
affiliation: @linkState "affiliation"
usertype: @linkState "usertype"
age: @linkState "demo_age"
url: @linkState "demo_url"
residencecountry: @linkState "demo_residencecountry"
schoolcountry: @linkState "demo_schoolcountry"
zipcode: @linkState "demo_zipcode"
grade: @linkState "demo_grade"
referrer: @linkState "demo_referrer"
gender: @linkState "demo_gender"
genderother: @linkState "demo_genderother"
teacher_middleschool: @linkState "demo_teacher_middleschool"
teacher_highschool: @linkState "demo_teacher_highscool"
teacher_afterschoolclub: @linkState "demo_teacher_afterschool"
teacher_homeschool: @linkState "demo_teacher_homeschool"
subjectstaught: @linkState "demo_subjectstaught"
parentemail: @linkState "demo_parentemail"
showRegStats = (()->
if @state.regStats
<Panel>
<h4><strong>Registration Statistics</strong></h4>
<p>
<strong>{@state.regStats.users}</strong> users have registered, <strong>{@state.regStats.teamed_users}</strong> of
which have formed <strong>{@state.regStats.teams}</strong> teams.<br />
<strong>{@state.regStats.groups}</strong> classrooms have been created by teachers.
</p>
</Panel>
).bind this
if @state.page == "Team Management"
<div>
<Row>
<Col md={6} mdOffset={3}>
<TeamManagementForm/>
</Col>
</Row>
</div>
else
<div>
<Row>
<Col md={6} mdOffset={3}>
<LoginForm setPage={@setPage} onRecaptchaSuccess={@onRecaptchaSuccess} onRecaptchaExpire={@onRecaptchaExpire}
status={@state.page} reCAPTCHA_public_key={@state.settings.reCAPTCHA_public_key}
onRegistration={@onRegistration} onLogin={@onLogin} onPasswordReset={@onPasswordReset}
emailFilter={@state.settings.email_filter} groupName={@state.groupName} rid={@state.rid}
gid={@state.gid} {...links}/>
{showRegStats()}
</Col>
</Row>
</div>
$ ->
redirectIfLoggedIn()
React.render <AuthPanel/>, document.getElementById("auth-box")
| true | Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
Glyphicon = ReactBootstrap.Glyphicon
ButtonInput = ReactBootstrap.ButtonInput
ButtonGroup = ReactBootstrap.ButtonGroup
Alert = ReactBootstrap.Alert
update = React.addons.update
Recaptcha = ReactRecaptcha
LoginForm = React.createClass
render: ->
userGlyph = <Glyphicon glyph="user"/>
lockGlyph = <Glyphicon glyph="lock"/>
formButton = if @props.status == "Login" then \
q = "'" #My syntax highlighting can't handle literal quotes in jsx. :(
if @props.status == "Reset"
<Panel>
<form onSubmit={@props.onPasswordReset}>
<p><i>A password reset link will be sent the user{q}s email.</i></p>
<Input type="text" name="username" valueLink={@props.username} addonBefore={userGlyph} placeholder="Username" required/>
<div style={{height: "70px"}}/>
<Row>
<Col md={6}>
<ButtonInput type="submit">Reset Password</ButtonInput>
</Col>
<Col md={6}>
<span className="pull-right pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
</Col>
</Row>
</form>
</Panel>
else
showGroupMessage = (->
<Alert bsStyle="info">
You are registering as a member of <strong>{@props.groupName}</strong>.
</Alert>
).bind this
showEmailFilter = (->
<Alert bsStyle="warning">
You can register provided you have an email for one of these domains: <strong>{@props.emailFilter.join ", "}</strong>.
</Alert>
).bind this
generateRecaptcha = ( ->
if @props.reCAPTCHA_public_key
<Recaptcha sitekey={@props.reCAPTCHA_public_key} verifyCallback={@props.onRecaptchaSuccess} expiredCallback={@props.onRecaptchaExpire} render="explicit" />
).bind this
# Toggle input fields according to user type
showOrHide = ((prop, inputName) ->
inputs = {
firstname: false
lastname: false
url: false
grade: false
teacherlevel: false
subjectstaught: false
schoolcountry: false
residencecountry: true
affiliation: true
zipcode: false
studentOnly: false
teacherOnly: false
referrer: false
gender: true
}
switch @props.usertype.value
when "student"
inputs.grade = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.studentOnly = true
inputs.referrer = true
inputs.url = true
when "college"
inputs.schoolcountry = true
inputs.zipcode = true
inputs.url = true
when "teacher"
inputs.teacherlevel = true
inputs.subjectstaught = true
inputs.schoolcountry = true
inputs.zipcode = true
inputs.teacherOnly = true
inputs.referrer = true
inputs.url = true
when "other"
inputs.url = true
else
inputs.affiliation = false
show = inputs[inputName]
if prop == "class"
if show then 'show' else 'hide'
else if prop == "disabled"
if show then false else true
).bind this
generateCountries = ( ->
countryList =
"United States": "US"
"Canada": "CA"
"Afghanistan": "AF"
"Albania": "AL"
"Algeria": "DZ"
"Andorra": "AD"
"Angola": "AO"
"Antigua and Barbuda": "AG"
"Argentina": "AR"
"Armenia": "AM"
"Aruba": "AW"
"Australia": "AU"
"Austria": "AT"
"Azerbaijan": "AZ"
"Bahamas, The": "BS"
"Bahrain": "BH"
"Bangladesh": "BD"
"Barbados": "BB"
"Belarus": "BY"
"Belgium": "BE"
"Belize": "BZ"
"Benin": "BJ"
"Bhutan": "BT"
"Bolivia": "BO"
"Bosnia and Herzegovina": "BA"
"Botswana": "BW"
"Brazil": "BR"
"Brunei": "BN"
"Bulgaria": "BG"
"Burkina Faso": "BF"
"Burma": "MM"
"Burundi": "BI"
"Cabo Verde": "CV"
"Cambodia": "KH"
"Cameroon": "CM"
"Central African Republic":"CF"
"Chad": "TD"
"Chile": "CL"
"China": "CN"
"Colombia": "CO"
"Comoros": "KM"
"Congo (Brazzaville)": "CG"
"Congo (Kinshasa)": "CD"
"Costa Rica": "CR"
"Côte d'Ivoire": "CI"
"Croatia": "HR"
"Cuba": "CU"
"Curacao": "CW"
"Cyprus": "CY"
"Czechia": "CZ"
"Denmark": "DK"
"Djibouti": "DJ"
"Dominica": "DM"
"Dominican Republic": "DO"
"Ecuador": "EC"
"Egypt": "EG"
"El Salvador": "SV"
"Equatorial Guinea": "GQ"
"Eritrea": "ER"
"Estonia": "EE"
"Eswatini": "SZ"
"Ethiopia": "ET"
"Fiji": "FJ"
"Finland": "FI"
"France": "FR"
"Gabon": "GA"
"Gambia, The": "GM"
"Georgia": "GE"
"Germany": "DE"
"Ghana": "GH"
"Greece": "GR"
"Grenada": "GD"
"Guatemala": "GT"
"Guinea": "GN"
"Guinea-Bissau": "GW"
"Guyana": "GY"
"Haiti": "HT"
"Holy See": "VA"
"Honduras": "HN"
"Hong Kong": "HK"
"Hungary": "HU"
"Iceland": "IS"
"India": "IN"
"Indonesia": "ID"
"Iran": "IR"
"Iraq": "IQ"
"Ireland": "IE"
"Israel": "IL"
"Italy": "IT"
"Jamaica": "JM"
"Japan": "JP"
"Jordan": "JO"
"Kazakhstan": "KZ"
"Kenya": "KE"
"Kiribati": "KI"
"Korea, North": "KP"
"Korea, South": "KR"
"Kosovo": "XK"
"Kuwait": "KW"
"Kyrgyzstan": "KG"
"Laos": "LA"
"Latvia": "LV"
"Lebanon": "LB"
"Lesotho": "LS"
"Liberia": "LR"
"Libya": "LY"
"Liechtenstein": "LI"
"Lithuania": "LT"
"Luxembourg": "LU"
"Macau": "MO"
"Macedonia": "MK"
"Madagascar": "MG"
"Malawi": "MW"
"Malaysia": "MY"
"Maldives": "MV"
"Mali": "ML"
"Malta": "MT"
"Marshall Islands": "MH"
"Mauritania": "MR"
"Mauritius": "MU"
"Mexico": "MX"
"Micronesia": "FM"
"Moldova": "MD"
"Monaco": "MC"
"Mongolia": "MN"
"Montenegro": "ME"
"Morocco": "MA"
"Mozambique": "MZ"
"Namibia": "NA"
"Nauru": "NR"
"Nepal": "NP"
"Netherlands": "NL"
"New Zealand": "NZ"
"Nicaragua": "NI"
"Niger": "NE"
"Nigeria": "NG"
"Norway": "NO"
"Oman": "OM"
"Pakistan": "PK"
"Palau": "PW"
"Palestine": "PS"
"Panama": "PA"
"Papua New Guinea": "PG"
"Paraguay": "PY"
"Peru": "PE"
"Philippines": "PH"
"Poland": "PL"
"Portugal": "PT"
"Qatar": "QA"
"Romania": "RO"
"Russia": "RU"
"Rwanda": "RW"
"Saint Kitts and Nevis": "KN"
"Saint Lucia": "LC"
"Saint Vincent and the Grenadines": "VC"
"Samoa": "WS"
"San Marino": "SM"
"Sao Tome and Principe": "ST"
"Saudi Arabia": "SA"
"Senegal": "SN"
"Serbia": "RS"
"Seychelles": "SC"
"Sierra Leone": "SL"
"Singapore": "SG"
"Sint Maarten": "SX"
"Slovakia": "SK"
"Slovenia": "SI"
"Solomon Islands": "SB"
"Somalia": "SO"
"South Africa": "ZA"
"South Sudan": "SS"
"Spain": "ES"
"Sri Lanka": "LK"
"Sudan": "SD"
"Suriname": "SR"
"Sweden": "SE"
"Switzerland": "CH"
"Syria": "SY"
"Taiwan": "TW"
"Tajikistan": "TJ"
"Tanzania": "TZ"
"Thailand": "TH"
"Timor-Leste": "TL"
"Togo": "TG"
"Tonga": "TO"
"Trinidad and Tobago": "TT"
"Tunisia": "TN"
"Turkey": "TR"
"Turkmenistan": "TM"
"Tuvalu": "TV"
"Uganda": "UG"
"Ukraine": "UA"
"United Arab Emirates": "AE"
"United Kingdom": "GB"
"Uruguay": "UY"
"Uzbekistan": "UZ"
"Vanuatu": "VU"
"Venezuela": "VE"
"Vietnam": "VN"
"Yemen": "YE"
"Zambia": "ZM"
"Zimbabwe": "ZW"
for country, abbrev of countryList
<option value=abbrev>{country}</option>
)
registrationForm = if @props.status == "Register" then \
<div>
<Row>
<div>
{if @props.groupName.length > 0 then showGroupMessage() else <span/>}
{if @props.emailFilter.length > 0 and not @props.rid then showEmailFilter() else <span/>}
<br/>
</div>
<Col md={6} className={showOrHide('class', 'firstname')}>
<Input type="text" id="firstname" valueLink={@props.firstname} label="First Name" placeholder="PI:NAME:<NAME>END_PI"/>
</Col>
<Col md={6} className={showOrHide('class', 'lastname')}>
<Input type="text" id="lastname" valueLink={@props.lastname} label="Last Name" placeholder="PI:NAME:<NAME>END_PI"/>
</Col>
<Col md={12}>
<Input type="email" name="email" id="email" valueLink={@props.email} label="E-mail *" placeholder="PI:EMAIL:<EMAIL>END_PI" required/>
</Col>
</Row>
<Row>
<Col md={12} className={showOrHide('class', 'residencecountry')}>
<Input type="select" name="residencecountry" id="residencecountry" defaultValue="" valueLink={@props.residencecountry} label="Country/Region of Residence *" placeholder="Country of Residence" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="usertype" id="usertype" defaultValue="" label="Status *" required valueLink={@props.usertype}>
<option value="" disabled>-Select Category-</option>
<option value="student">Middle/High School Student</option>
<option value="teacher">Teacher/Instructor</option>
<option value="college">College Student</option>
<option value="other">Other</option>
</Input>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'affiliation')}>
<Input type="text" name="affiliation" id="affiliation" valueLink={@props.affiliation} label={if @props.usertype.value == "other" then "Organization Name *" else "School Name *"} placeholder="Example School, Pittsburgh, PA" maxlength="50" required/>
<p className="help-block">
Your school or organization name may be visible to other users.
</p>
</Col>
<Col md={6} className={showOrHide('class', 'url')}>
<Input type="text" name="url" disabled={showOrHide( 'disabled', 'url')} id="url" valueLink={@props.url} label={if @props.usertype.value == "other" then "Organization URL (optional)" else "School URL (optional)"} placeholder={if @props.usertype.value == "other" then "Organization URL" else "School URL"}/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'grade')}>
<Input type="number" min="1" max="12" name="grade" disabled={showOrHide('disabled','grade')} id="grade" valueLink={@props.grade} label="Your Current Grade/Year (1-12) *" placeholder="Your Current Grade/Year" required/>
</Col>
<Col md={6} className={showOrHide('class', 'teacherlevel')}>
<label>I teach *</label>
<Input type="checkbox" checkedLink={@props.teacher_middleschool} label="Middle School"/>
<Input type="checkbox" checkedLink={@props.teacher_highschool} label="High School"/>
<Input type="checkbox" checkedLink={@props.teacher_afterschoolclub} label="After School or Club"/>
<Input type="checkbox" checkedLink={@props.teacher_homeschool} label="Home School"/>
</Col>
<Col md={6} className={showOrHide('class', 'subjectstaught')}>
<Input type="text" name="subjectstaught" disabled={showOrHide('disabled', 'subjectstaught')} id="subjectstaught" valueLink={@props.subjectstaught} label="Subjects Taught *" required/>
</Col>
</Row>
<Row>
<Col md={6} className={showOrHide('class', 'zipcode')}>
<Input type="text" name="zipcode" disabled={showOrHide('disabled','zipcode')} id="zipcode" valueLink={@props.zipcode} label="School Zip Code/Postal Code *" placeholder="School Zipcode/Postal Code" required/>
</Col>
<Col md={6} className={showOrHide('class', 'schoolcountry')}>
<Input type="select" name="schoolcountry" disabled={showOrHide('disabled','schoolcountry')} defaultValue="" id="schoolcountry" valueLink={@props.schoolcountry} label="School Country *" required>
<option value="" disabled>-Select-</option>
{generateCountries()}
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'referrer')}>
<Col md={12}>
<Input className={showOrHide('disabled', 'referrer')} type="select" name="referrer" defaultValue="" id="referrer" label="How did you hear about picoCTF?" valueLink={@props.referrer}>
<option value="" disabled>-Select-</option>
<option value="socialmedia">Social Media</option>
<option className={showOrHide('class', 'studentOnly')} value="friends">Friends</option>
<option <option className={showOrHide('class', 'studentOnly')} value="teacher">Teacher</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="students">Students</option>
<option <option className={showOrHide('class', 'teacherOnly')} value="colleagues_groupemail">Colleagues or group email</option>
</Input>
</Col>
</Row>
<Row className={showOrHide('class', 'gender')}>
<Col md={if @props.gender.value == "other" then 6 else 12}>
<Input type="select" id="gender" name="gender" defaultValue="" label="Which gender identity do you most identify with?" valueLink={@props.gender}>
<option value="">-Select-</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
<option value="transgenderwoman">Transgender Woman</option>
<option value="transgenderman">Transgender Man</option>
<option value="gfnc">Gender Fluid/Non-Conforming</option>
<option value="other">I prefer: (fill in)</option>
</Input>
</Col>
<Col md={6} className={if @props.gender.value == "other" then "show" else "hide"}>
<br/>
<Input type="text" name="genderother" disabled={if @props.gender.value == "other" then false else true} id="genderother" valueLink={@props.genderother} label="Gender preference" placeholder=""/>
</Col>
</Row>
<Row>
<Col md={12}>
<Input type="select" name="age" id="age" defaultValue="" label="What is your age? *" valueLink={@props.age} required>
<option value="">-Select-</option>
<option value="13-17">I am between 13 and 17 years of age</option>
<option value="18+">I am 18 years of age or older</option>
</Input>
</Col>
</Row>
<Row className={if @props.age.value == "13-17" then "show" else "hide"}>
<Col md={12}>
<p className="help-block">
Parent or legal guardian must insert contact email address. By inserting email address and finalizing
registration, parent/legal guardian is hereby consenting to their child’s registration under the Terms of
Use, Privacy Statement and any applicable Competition Rules.
</p>
<Input type="email" name="parentemail" disabled={if @props.age.value == "13-17" then false else true} id="parentemail" valueLink={@props.parentemail} label="Parent's E-mail *" required placeholder="PI:EMAIL:<EMAIL>END_PI" />
</Col>
</Row>
<Row>
<Col md={8}>
{generateRecaptcha()}
</Col>
<Col md={4} className="text-right">
<ButtonInput className="btn-primary" type="submit">Register</ButtonInput>
</Col>
</Row>
</div> else <span/>
<Panel>
<form key={@props.status} onSubmit={if @props.status == "Login" then @props.onLogin else @props.onRegistration}>
<Input type="text" id="username" valueLink={@props.username} addonBefore={userGlyph} label="Username" required/>
<p className={if @props.status == "Login" then "hide" else "help-block"}>Your username may be visible to other users.
Do not include your real name or any other personal information.</p>
<Input type="PI:PASSWORD:<PASSWORD>END_PI" id="password" valueLink={@props.password} addonBefore={lockGlyph} label="Password" required/>
<Row>
<Col md={6}>
{if @props.status == "Register" then \
<span className="pad">Go back to <a onClick={@props.setPage.bind null, "Login"}>Login</a>.</span>
else <span>
<Button type="submit">Login</Button>
<Button id="set-register" onClick={@props.setPage.bind null, "Register"}>Register</Button>
</span>}
</Col>
<Col md={6}>
<a className="pad" onClick={@props.setPage.bind null, "Reset"}>Need to reset your password?</a>
</Col>
</Row>
{registrationForm}
</form>
</Panel>
TeamManagementForm = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
team_name: ""
team_password: ""
onTeamRegistration: (e) ->
e.preventDefault()
if (!@state.team_name || !@state.team_password)
apiNotify({status: 0, message: "Invalid team name or password."})
else
data = {team_name: @state.team_name, team_password: @state.team_password}
apiCall "POST", "/api/v1/teams", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onTeamJoin: (e) ->
e.preventDefault()
data = {team_name: @state.team_name, team_password: PI:PASSWORD:<PASSWORD>END_PI}
apiCall "POST", "/api/v1/team/join", data
.success (data) ->
document.location.href = "/profile"
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
render: ->
towerGlyph = <Glyphicon glyph="tower"/>
lockGlyph = <Glyphicon glyph="lock"/>
<Panel>
<p>Your team name may be visible to other users. Do not include your real name or any other personal information.
Also, to avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p>
<form onSubmit={@onTeamJoin}>
<Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/>
<Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/>
<Col md={6}>
<span> <Button type="submit">Join Team</Button>
<Button onClick={@onTeamRegistration}>Register Team</Button>
</span>
</Col>
<Col md={6}>
<a href="#" onClick={() -> document.location.href = "/profile"}>Play as an individual.</a>
</Col>
</form>
</Panel>
AuthPanel = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: ->
params = $.deparam $.param.fragment()
page: "Login"
settings: {}
gid: params.g
rid: params.r
status: params.status
groupName: ""
captcha: ""
regStats: {}
componentWillMount: ->
if @state.status == "verified"
apiNotify({status: 1, message: "Your account has been successfully verified. Please login."})
else if @state.status == "verification_error"
apiNotify({status: 0, message: "Invalid verification code. Please contact an administrator."})
if @state.gid
apiCall "GET", "/api/v1/groups/" + @state.gid
.success ((data) ->
@setState update @state,
groupName: $set: data.name
affiliation: $set: data.name
settings: $merge: data.settings
page: $set: "Register"
).bind this
else
apiCall "GET", "/api/v1/status"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/user"
.success ((data) ->
@setState update @state,
settings: $merge: data
).bind this
apiCall "GET", "/api/v1/stats/registration"
.success ((data) ->
@setState update @state,
regStats: $set: data
).bind this
onRegistration: (e) ->
e.preventDefault()
if @state.settings.enable_captcha && @state.captcha == ""
apiNotify {status: 0, message: "ReCAPTCHA required."}
return
form = {}
form.gid = @state.gid
form.rid = @state.rid
form.username = @state.username
form.password = PI:PASSWORD:<PASSWORD>END_PI
form.firstname = @state.firstname
form.lastname = @state.lastname
form.email = @state.email
form.affiliation = @state.affiliation
form.usertype = @state.usertype
form.demo = {}
if @state.demo_gender == "other"
@state.demo_gender = @state.demo_genderother
delete @state.demo_genderother
for k,v of @state
if k.substr(0,5) == "demo_"
form.demo[k.substr(5)] = v
if @state.usertype in ["student", "teacher"]
form.country = form.demo.schoolcountry
else
form.country = form.demo.residencecountry
form['g-recaptcha-response'] = @state.captcha
apiCall "POST", "/api/v1/users", form
.success ((data) ->
verificationAlert =
status: 1
message: "You have been sent a verification email. You will need to complete this step before logging in."
successAlert =
status: 1
message: "User " + @state.username + " registered successfully!"
if @state.settings.email_verification and not @state.rid
apiNotify verificationAlert
@setPage "Login"
if @state.settings.max_team_size > 1
document.location.hash = "#team-builder"
else
apiCall "POST", "/api/v1/user/login", {"username": @state.username, "password": PI:PASSWORD:<PASSWORD>END_PI}
.success ((loginData) ->
apiCall "GET", "/api/v1/user"
.success ((userData) ->
if data.teacher
apiNotify successAlert, "/profile"
else if @state.settings.max_team_size > 1
apiNotify successAlert
@setPage "Team Management"
else
apiNotify successAlert, "/profile"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onPasswordReset: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/reset_password/request", {username: @state.username}
.success ((resp) ->
apiNotify {status: 1, message: "A password reset link has been sent to the email address provided during registration."}
@setPage "Login"
).bind this
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
onLogin: (e) ->
e.preventDefault()
apiCall "POST", "/api/v1/user/login", {username: @state.username, password:PI:PASSWORD:<PASSWORD>END_PI @state.PI:PASSWORD:<PASSWORD>END_PI}
.success ->
# Get teacher status
apiCall "GET", "/api/v1/user"
.success ((data) ->
if document.location.hash == "#team-builder" and not data.teacher
@setPage "Team Management"
else
if data.teacher
document.location.href = "/classroom"
else
document.location.href = "/profile"
)
.error (jqXHR) ->
apiNotify {"status": 0, "message": jqXHR.responseJSON.message}
setPage: (page) ->
@setState update @state,
page: $set: page
onRecaptchaSuccess: (captcha) ->
@setState update @state,
captcha: $set: captcha
onRecaptchaExpire: () ->
@setState update @state,
captcha: $set: ""
render: ->
links =
username: @linkState "username"
password: PI:PASSWORD:<PASSWORD>END_PI "PI:PASSWORD:<PASSWORD>END_PI"
lastname: @linkState "lastname"
firstname: @linkState "firstname"
email: @linkState "email"
affiliation: @linkState "affiliation"
usertype: @linkState "usertype"
age: @linkState "demo_age"
url: @linkState "demo_url"
residencecountry: @linkState "demo_residencecountry"
schoolcountry: @linkState "demo_schoolcountry"
zipcode: @linkState "demo_zipcode"
grade: @linkState "demo_grade"
referrer: @linkState "demo_referrer"
gender: @linkState "demo_gender"
genderother: @linkState "demo_genderother"
teacher_middleschool: @linkState "demo_teacher_middleschool"
teacher_highschool: @linkState "demo_teacher_highscool"
teacher_afterschoolclub: @linkState "demo_teacher_afterschool"
teacher_homeschool: @linkState "demo_teacher_homeschool"
subjectstaught: @linkState "demo_subjectstaught"
parentemail: @linkState "demo_parentemail"
showRegStats = (()->
if @state.regStats
<Panel>
<h4><strong>Registration Statistics</strong></h4>
<p>
<strong>{@state.regStats.users}</strong> users have registered, <strong>{@state.regStats.teamed_users}</strong> of
which have formed <strong>{@state.regStats.teams}</strong> teams.<br />
<strong>{@state.regStats.groups}</strong> classrooms have been created by teachers.
</p>
</Panel>
).bind this
if @state.page == "Team Management"
<div>
<Row>
<Col md={6} mdOffset={3}>
<TeamManagementForm/>
</Col>
</Row>
</div>
else
<div>
<Row>
<Col md={6} mdOffset={3}>
<LoginForm setPage={@setPage} onRecaptchaSuccess={@onRecaptchaSuccess} onRecaptchaExpire={@onRecaptchaExpire}
status={@state.page} reCAPTCHA_public_key={@state.settings.reCAPTCHA_public_key}
onRegistration={@onRegistration} onLogin={@onLogin} onPasswordReset={@onPasswordReset}
emailFilter={@state.settings.email_filter} groupName={@state.groupName} rid={@state.rid}
gid={@state.gid} {...links}/>
{showRegStats()}
</Col>
</Row>
</div>
$ ->
redirectIfLoggedIn()
React.render <AuthPanel/>, document.getElementById("auth-box")
|
[
{
"context": "rd.replace /^MD5_/, ''\n else\n md5_password = @MD5 @password\n signature = \"#{opt.method}&/#{@bucke",
"end": 3228,
"score": 0.607719898223877,
"start": 3226,
"tag": "PASSWORD",
"value": "MD"
},
{
"context": " signature\n opt.headers[\"Authorization\"] = \"UpYun ... | source/javascripts/all.coffee | 2947721120/manager-for-upyun | 1 | # = require_tree .
# = require jquery
# = require jquery-serialize-object
# = require bootstrap
# = require underscore
# = require underscore.string/dist/underscore.string.min
# = require messenger/build/js/messenger
# = require messenger/build/js/messenger-theme-future
# = require ace-builds/src-noconflict/ace.js
if @require?
@request = @require 'request'
@moment = @require 'moment'
@moment.lang 'zh-cn'
@async = @require 'async'
@fs = @require 'fs'
@os = @require 'os'
@path = @require 'path'
@mkdirp = @require 'mkdirp'
@gui = @require 'nw.gui'
@MD5 = require 'MD5'
@url = require 'url'
try
@m_favs = JSON.parse(localStorage.favs)||{}
catch
@m_favs = {}
@refresh_favs = =>
$ '#favs'
.empty()
for k, fav of @m_favs
$ li = document.createElement 'li'
.appendTo '#favs'
$ document.createElement 'a'
.appendTo li
.text k
.attr href: '#'
.data 'fav', fav
.click (ev)=>
ev.preventDefault()
$(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active'
for k, v of $(ev.currentTarget).data 'fav'
$ "#input#{_.str.capitalize k}"
.val v
$ '#formLogin'
.submit()
$ document.createElement 'button'
.appendTo li
.prepend @createIcon 'trash-o'
.addClass 'btn btn-danger btn-xs'
.attr 'title', '删除这条收藏记录'
.tooltip placement: 'bottom'
.data 'fav', fav
.click (ev)=>
fav = $(ev.currentTarget).data 'fav'
delete @m_favs["#{fav.username}@#{fav.bucket}"]
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
@humanFileSize = (bytes, si) ->
thresh = (if si then 1000 else 1024)
return bytes + " B" if bytes < thresh
units = (if si then [
"kB"
"MB"
"GB"
"TB"
"PB"
"EB"
"ZB"
"YB"
] else [
"KiB"
"MiB"
"GiB"
"TiB"
"PiB"
"EiB"
"ZiB"
"YiB"
])
u = -1
loop
bytes /= thresh
++u
break unless bytes >= thresh
bytes.toFixed(1) + " " + units[u]
@upyun_messages =
'200 OK': '操作成功'
'404': '找不到文件'
'400 Bad Request': '错误请求(如 URL 缺少空间名)'
'401 Unauthorized': '访问未授权'
'401 Sign error': '签名错误(操作员和密码,或签名格式错误)'
'401 Need Date Header': '发起的请求缺少 Date 头信息'
'401 Date offset error': '发起请求的服务器时间错误,请检查服务器时间是否与世界时间一致'
'403 Not Access': '权限错误(如非图片文件上传到图片空间)'
'403 File size too max': '单个文件超出大小(100Mb 以内)'
'403 Not a Picture File': '图片类空间错误码,非图片文件或图片文件格式错误。针对图片空间只允许上传 jpg/png/gif/bmp/tif 格式。'
'403 Picture Size too max': '图片类空间错误码,图片尺寸太大。针对图片空间,图片总像素在 200000000 以内。'
'403 Bucket full': '空间已用满'
'403 Bucket blocked': '空间被禁用,请联系管理员'
'403 User blocked': '操作员被禁用'
'403 Image Rotate Invalid Parameters': '图片旋转参数错误'
'403 Image Crop Invalid Parameters': '图片裁剪参数错误'
'404 Not Found': '获取文件或目录不存在;上传文件或目录时上级目录不存在'
'406 Not Acceptable(path)': '目录错误(创建目录时已存在同名文件;或上传文件时存在同名目录)'
'503 System Error': '系统错误'
@_upyun_api = (opt, cb)=>
opt.headers?= {}
opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD']
date = new Date().toUTCString()
if @password.match /^MD5_/
md5_password = @password.replace /^MD5_/, ''
else
md5_password = @MD5 @password
signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}&#{opt.length || opt.data?.length ||0}&#{md5_password}"
signature = @MD5 signature
opt.headers["Authorization"] = "UpYun #{@username}:#{signature}"
opt.headers["Date"] = date
@_upyun_api_req = req = @request
method: opt.method
url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}"
headers: opt.headers
body: opt.data
, (e, res, data)=>
return cb e if e
if res.statusCode == 200
cb null, data
else
status = String res.statusCode
if res.body
statusMatch = res.body.match(/\<h\d\>\d+\s(.+)\<\/\s*h\d\>/)
if status = statusMatch?[1]
status = "#{res.statusCode} #{status}"
else
status = res.body
status = @upyun_messages[status]||status
cb new Error status
opt.source?.pipe req
req.pipe opt.pipe if opt.pipe
req.on 'data', opt.onData if opt.onData
return =>
req.abort()
cb new Error '操作已取消'
@upyun_api = (opt, cb)=>
start = Date.now()
@_upyun_api opt, (e, data)=>
console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)"
cb e, data
Messenger.options =
extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right'
theme: 'future'
messageDefaults:
showCloseButton: true
hideAfter: 10
retry:
label: '重试'
phrase: 'TIME秒钟后重试'
auto: true
delay: 5
@createIcon = (icon)=>
$ document.createElement 'i'
.addClass "fa fa-#{icon}"
@shortOperation = (title, operation)=>
@shortOperationBusy = true
$ '#loadingText'
.text title||''
.append '<br />'
$ 'body'
.addClass 'loading'
$ btnCancel = document.createElement 'button'
.appendTo '#loadingText'
.addClass 'btn btn-default btn-xs btn-inline'
.text '取消'
.hide()
operationDone = (e)=>
@shortOperationBusy = false
$ 'body'
.removeClass 'loading'
if e
msg = Messenger().post
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@shortOperation title, operation
operation operationDone, $ btnCancel
@taskOperation = (title, operation)=>
msg = Messenger(
instance: @messengerTasks
extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom'
).post
hideAfter: 0
message: title
actions:
cancel:
label: '取消'
action: =>
$progresslabel1 = $ document.createElement 'span'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'pull-right'
$progressbar = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'progress progress-striped active'
.css margin: 0
.append $(document.createElement 'div').addClass('progress-bar').width '100%'
.append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%'
$progresslabel2 = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
operationProgress = (progress, progresstext)=>
$progresslabel2.text progresstext if progresstext
$progresslabel1.text "#{progress}%" if progress?
$progressbar
.toggleClass 'active', !progress?
$progressbar.children ':not(.progress-bar-success)'
.toggle !progress?
$progressbar.children '.progress-bar-success'
.toggle progress?
.width "#{progress}%"
operationDone = (e)=>
return unless msg
if e
msg.update
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@taskOperation title, operation
else
msg.hide()
operationProgress null
operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a')
@upyun_readdir = (url, cb)=>
@upyun_api
method: "GET"
url: url
, (e, data)=>
return cb e if e
files = data.split('\n').map (line)->
line = line.split '\t'
return null unless line.length == 4
return (
filename: line[0]
url: url + encodeURIComponent line[0]
isDirectory: line[1]=='F'
length: Number line[2]
mtime: 1000 * Number line[3]
)
cb null, files.filter (file)-> file?
@upyun_find_abort = ->
@upyun_find = (url, cb)=>
results = []
@upyun_find_abort = @upyun_readdir url, (e, files)=>
return cb e if e
@async.eachSeries files, (file, doneEach)=>
if file.isDirectory
@upyun_find file.url + '/', (e, tmp)=>
return doneEach e if e
results.push item for item in tmp
results.push file
doneEach null
else
results.push file
_.defer => doneEach null
, (e)=>
@upyun_find_abort = ->
cb e, results
@uypun_upload = (url, files, onProgress, cb)=>
aborted = false
api_aborting = null
aborting = =>
aborted = true
api_aborting?()
status =
total_files: files.length
total_bytes: files.reduce ((a, b)-> a + b.length), 0
current_files: 0
current_bytes: 0
@async.eachSeries files, (file, doneEach)=>
fs.stat file.path, (e, stats)=>
return doneEach (new Error '操作已取消') if aborted
return doneEach e if e
file_length = stats.size
file_stream = fs.createReadStream file.path
api_aborting = @upyun_api
method: "PUT"
headers:
'mkdir': 'true'
url: url + file.url
length: file_length
, (e)=>
status.current_files+= 1
onProgress status
doneEach e
req = @_upyun_api_req
file_stream.pipe req
file_stream.on 'data', (data)=>
status.current_bytes+= data.length
onProgress status
, cb
return aborting
@action_downloadFolder = (filename, url)=>
unless filename || filename = url.match(/([^\/]+)\/$/)?[1]
filename = @bucket
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
@nw_directory (savepath)=>
@taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
total_files = files.length
total_bytes = files.reduce ((a, b)-> a + b.length), 0
current_files = 0
current_bytes = 0
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
@async.eachSeries files, ((file, doneEach)=>
return (_.defer => doneEach null) if file.isDirectory
segs = file.url.substring(url.length).split '/'
segs = segs.map decodeURIComponent
destpath = @path.join savepath, filename, @path.join.apply @path, segs
@mkdirp @path.dirname(destpath), (e)=>
return doneEach e if e
stream = @fs.createWriteStream destpath
stream.on 'error', doneEach
stream.on 'open', =>
current_files+= 1
aborting = @upyun_api
method: 'GET'
url: file.url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * (current_bytes + stream.bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + stream.bytesWritten} / #{@humanFileSize total_bytes})"
, (e)=>
current_bytes+= file.length unless e
doneEach e
), (e)=>
aborting = null
doneTransfer e
unless e
msg = Messenger().post
message: "目录 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
@action_uploadFile = (filepath, filename, destpath)=>
@taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
files = []
loadfileSync = (file)=>
stat = @fs.statSync(file.path)
if stat.isFile()
file.length = stat.size
files.push file
if stat.isDirectory()
for filename in @fs.readdirSync file.path
loadfileSync
path: @path.join(file.path, filename)
url: file.url + '/' + encodeURIComponent filename
try
loadfileSync path: filepath, url: ''
catch e
return doneTransfer e if e
$btnCancelTransfer.show().click @uypun_upload destpath, files, (status)=>
progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})"
, (e)=>
doneTransfer e
unless e
@m_changed_path = destpath.replace /[^\/]+$/, ''
msg = Messenger().post
message: "文件 #{filename} 上传完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
@action_show_url = (title, url)=>
msg = Messenger().post
message: "#{title}<pre>#{url}</pre>"
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@action_share = (url)=>
url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}"
msg = Messenger().post
message: """
您可以通过以下地址向其他人分享该目录:
<pre>#{url}</pre>
注意:<ol>
<li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li>
<li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li>
</ol>
"""
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@nw_saveas = (filename, cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwsaveas: filename
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_directory = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwdirectory: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_selectfiles = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', multiple: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val.split ';'
.trigger 'click'
@jump_login = =>
@m_path = '/'
@m_active = false
@refresh_favs()
$ '#filelist, #editor'
.hide()
$ '#login'
.fadeIn()
@jump_filelist = =>
@jump_path '/'
@jump_path = (path)=>
@m_path = path
@m_changed_path = path
@m_active = true
@m_files = null
$ '#filelist .preloader'
.css
opacity: 1
$ '#inputFilter'
.val ''
$ '#login, #editor'
.hide()
$ '#filelist'
.fadeIn()
segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, ''
segs = segs.map decodeURIComponent
$ '#path'
.empty()
$ li = document.createElement 'li'
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @username
.prepend @createIcon 'user'
.attr 'href', '#'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ li = document.createElement 'li'
.toggleClass 'active', !segs.length
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @bucket
.prepend @createIcon 'cloud'
.attr 'href', "http://#{bucket}.b0.upaiyun.com/"
.data 'url', '/'
for seg, i in segs
url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/'
$ li = document.createElement 'li'
.toggleClass 'active', i == segs.length - 1
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text seg
.prepend @createIcon 'folder'
.attr 'href', "http://#{bucket}.b0.upaiyun.com#{url}"
.data 'url', url
$ '#path li:not(:first-child)>a'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data 'url'
@refresh_filelist = (cb)=>
cur_path = @m_path
@upyun_readdir cur_path, (e, files)=>
return cb e if e
if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files)
$('#filelist tbody').empty()
$('#filelist .preloader').css
opacity: 0
for file in @m_files = files
$ tr = document.createElement 'tr'
.appendTo '#filelist tbody'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ a = document.createElement 'a'
.appendTo td
.text file.filename
.prepend @createIcon 'folder'
.attr 'href', "#"
.data 'url', file.url + '/'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data('url')
else
$ td
.text file.filename
.prepend @createIcon 'file'
$ document.createElement 'td'
.appendTo tr
.text if file.isDirectory then '' else @humanFileSize file.length
$ document.createElement 'td'
.appendTo tr
.text @moment(file.mtime).format 'LLL'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '删除该目录'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url + '/'
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
files_deleting = 0
async.eachSeries files, (file, doneEach)=>
files_deleting+= 1
@shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: file.url
, (e)=>
operationDone e
doneEach e
, (e)=>
unless e
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /[^\/]+\/$/, ''
operationDone e
else
$ document.createElement 'button'
.appendTo td
.attr title: '删除该文件'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
url = $(ev.currentTarget).data('url')
filename = $(ev.currentTarget).data('filename')
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /\/[^\/]+$/, '/'
operationDone e
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '下载该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url + '/'
.data 'filename', file.filename
.click (ev)=>
@action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url')
$ document.createElement 'button'
.appendTo td
.attr title: '向其他人分享该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'share'
.data 'url', file.url + '/'
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@action_share url
else
$ document.createElement 'button'
.appendTo td
.attr title: '下载该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url
.data 'filename', file.filename
.data 'length', file.length
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
length = $(ev.currentTarget).data 'length'
@nw_saveas filename, (savepath)=>
@taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
stream = @fs.createWriteStream savepath
stream.on 'error', doneTransfer
stream.on 'open', =>
aborting = @upyun_api
method: "GET"
url: url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * stream.bytesWritten / length), "#{@humanFileSize stream.bytesWritten} / #{@humanFileSize length}"
, (e, data)=>
doneTransfer e
unless e
msg = Messenger().post
message: "文件 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
showItemInFolder:
label: "打开目录"
action: =>
msg.hide()
@gui.Shell.showItemInFolder savepath
$ document.createElement 'button'
.appendTo td
.attr title: '在浏览器中访问该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'globe'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@gui.Shell.openExternal url
$ document.createElement 'button'
.appendTo td
.attr title: '公共地址'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'code'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.data 'filename', file.filename
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@action_show_url "文件 #{filename} 的公共地址(URL)", url
$ document.createElement 'button'
.appendTo td
.attr title: '用文本编辑器打开该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'edit'
.data 'url', file.url
.data 'filename', file.filename
.click (ev)=>
@open '?' + $.param
username: @username
password: @password
bucket: @bucket
default_action: 'editor'
editor_url: $(ev.currentTarget).data 'url'
editor_filename: $(ev.currentTarget).data 'filename'
$('#filelist tbody [title]')
.tooltip
placement: 'bottom'
trigger: 'hover'
cb null
@jump_editor = =>
$ '#login, #filelist'
.hide()
$ '#editor'
.show()
@document.title = @editor_filename
@editor = @ace.edit $('#editor .editor')[0]
$('#btnReloadEditor').click()
window.ondragover = window.ondrop = (ev)->
ev.preventDefault()
return false
$ =>
@messengerTasks = $ document.createElement 'ul'
.appendTo 'body'
.messenger()
forverCounter = 0
@async.forever (doneForever)=>
if @m_active && !@shortOperationBusy
forverCounter += 1
if forverCounter == 20 || @m_changed_path == @m_path
forverCounter = 0
@m_changed_path = null
return @refresh_filelist (e)=>
if e
msg = Messenger().post
message: e.message
type: 'error'
actions:
ok:
label: '确定'
action: =>
msg.hide()
@jump_login()
setTimeout (=>doneForever null), 100
setTimeout (=>doneForever null), 100
, (e)=>
throw e
$ '#btnAddFav'
.click =>
fav = $('#formLogin').serializeObject()
fav.password = "MD5_" + @MD5 fav.password unless fav.password.match /^MD5_/
@m_favs["#{fav.username}@#{fav.bucket}"] = fav
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
$ '#formLogin'
.submit (ev)=>
ev.preventDefault()
@[k] = v for k, v of $(ev.currentTarget).serializeObject()
@password = "MD5_" + @MD5 @password unless @password.match /^MD5_/
$ '#filelist tbody'
.empty()
@jump_filelist()
$ window
.on 'dragover', -> $('body').addClass 'drag_hover'
.on 'dragleave', -> $('body').removeClass 'drag_hover'
.on 'dragend', -> $('body').removeClass 'drag_hover'
.on 'drop', (ev)=>
$('body').removeClass 'drag_hover'
ev.preventDefault()
for file in ev.originalEvent.dataTransfer.files
@action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}"
$ '#inputFilter'
.keydown =>
_.defer =>
val = String $('#inputFilter').val()
$ "#filelist tbody tr:contains(#{JSON.stringify val})"
.removeClass 'filtered'
$ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))"
.addClass 'filtered'
$ '#btnDownloadFolder'
.click (ev)=>
ev.preventDefault()
@action_downloadFolder null, @m_path
$ '#btnUploadFiles'
.click (ev)=>
ev.preventDefault()
@nw_selectfiles (files)=>
for filepath in files
filename = @path.basename filepath
@action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}"
$ '#btnUploadFolder'
.click (ev)=>
ev.preventDefault()
@nw_directory (dirpath)=>
@action_uploadFile dirpath, @path.basename(dirpath), @m_path
$ '#btnCreateFolder'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新目录的名称"
@shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=>
cur_path = @m_path
$btnCancelCreateing.click @upyun_api
url: "#{cur_path}#{filename}"
method: "POST"
headers:
'Folder': 'true'
, (e, data)=>
doneCreating e
@m_changed_path = cur_path
$ '#btnCreateFile'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新文件的文件名"
@open '?' + $.param
username: @username
password: @password
bucket: @bucket
default_action: 'editor'
editor_url: "#{@m_path}#{filename}"
editor_filename: filename
$ '#btnReloadEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在加载文件 #{editor_filename} ...", (doneReloading, $btnCancelReloading)=>
$btnCancelReloading.click @upyun_api
url: @editor_url
method: 'GET'
, (e, data)=>
if e
data = ''
else
data = data.toString 'utf8'
doneReloading null
unless e
@editor.setValue data
$ '#btnShareFolder'
.click (ev)=>
@action_share @m_path
$ '#btnSaveEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在保存文件 #{editor_filename} ...", (doneSaving, $btnCancelSaving)=>
$btnCancelSaving.click @upyun_api
url: @editor_url
method: 'PUT'
data: new Buffer @editor.getValue(), 'utf8'
, (e)=>
doneSaving e
unless e
msg = Messenger().post
message: "成功保存文件 #{editor_filename}"
actions:
ok:
label: '确定'
action: =>
msg.hide()
$ '#btnLogout'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ '#btnIssues'
.click (ev)=>
ev.preventDefault()
@gui.Shell.openExternal "https://gitcafe.com/layerssss/manager-for-upyun/tickets"
$ '[title]'
.tooltip
placement: 'bottom'
trigger: 'hover'
if (url = @gui.App.argv.pop()) && (url = @url.parse url).protocol.toLowerCase() == 'upyun:' && (auth = url.auth?.split ':')?.length == 2
newSearch = "?username=#{encodeURIComponent auth[0]}&password=#{encodeURIComponent auth[1]}&bucket=#{url.hostname}&m_path=#{encodeURIComponent url.pathname}&default_action=#{encodeURIComponent (url.hash?.replace /^\#/, '')||'filelist'}"
return location.search = newSearch unless location.search == newSearch
for m in location.search.match(/([^\&?]+)\=([^\&]+)/g)||[]
m = m.split '='
@[decodeURIComponent m[0]] = decodeURIComponent m[1]
(@["jump_#{@default_action}"]||@jump_login)()
| 6005 | # = require_tree .
# = require jquery
# = require jquery-serialize-object
# = require bootstrap
# = require underscore
# = require underscore.string/dist/underscore.string.min
# = require messenger/build/js/messenger
# = require messenger/build/js/messenger-theme-future
# = require ace-builds/src-noconflict/ace.js
if @require?
@request = @require 'request'
@moment = @require 'moment'
@moment.lang 'zh-cn'
@async = @require 'async'
@fs = @require 'fs'
@os = @require 'os'
@path = @require 'path'
@mkdirp = @require 'mkdirp'
@gui = @require 'nw.gui'
@MD5 = require 'MD5'
@url = require 'url'
try
@m_favs = JSON.parse(localStorage.favs)||{}
catch
@m_favs = {}
@refresh_favs = =>
$ '#favs'
.empty()
for k, fav of @m_favs
$ li = document.createElement 'li'
.appendTo '#favs'
$ document.createElement 'a'
.appendTo li
.text k
.attr href: '#'
.data 'fav', fav
.click (ev)=>
ev.preventDefault()
$(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active'
for k, v of $(ev.currentTarget).data 'fav'
$ "#input#{_.str.capitalize k}"
.val v
$ '#formLogin'
.submit()
$ document.createElement 'button'
.appendTo li
.prepend @createIcon 'trash-o'
.addClass 'btn btn-danger btn-xs'
.attr 'title', '删除这条收藏记录'
.tooltip placement: 'bottom'
.data 'fav', fav
.click (ev)=>
fav = $(ev.currentTarget).data 'fav'
delete @m_favs["#{fav.username}@#{fav.bucket}"]
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
@humanFileSize = (bytes, si) ->
thresh = (if si then 1000 else 1024)
return bytes + " B" if bytes < thresh
units = (if si then [
"kB"
"MB"
"GB"
"TB"
"PB"
"EB"
"ZB"
"YB"
] else [
"KiB"
"MiB"
"GiB"
"TiB"
"PiB"
"EiB"
"ZiB"
"YiB"
])
u = -1
loop
bytes /= thresh
++u
break unless bytes >= thresh
bytes.toFixed(1) + " " + units[u]
@upyun_messages =
'200 OK': '操作成功'
'404': '找不到文件'
'400 Bad Request': '错误请求(如 URL 缺少空间名)'
'401 Unauthorized': '访问未授权'
'401 Sign error': '签名错误(操作员和密码,或签名格式错误)'
'401 Need Date Header': '发起的请求缺少 Date 头信息'
'401 Date offset error': '发起请求的服务器时间错误,请检查服务器时间是否与世界时间一致'
'403 Not Access': '权限错误(如非图片文件上传到图片空间)'
'403 File size too max': '单个文件超出大小(100Mb 以内)'
'403 Not a Picture File': '图片类空间错误码,非图片文件或图片文件格式错误。针对图片空间只允许上传 jpg/png/gif/bmp/tif 格式。'
'403 Picture Size too max': '图片类空间错误码,图片尺寸太大。针对图片空间,图片总像素在 200000000 以内。'
'403 Bucket full': '空间已用满'
'403 Bucket blocked': '空间被禁用,请联系管理员'
'403 User blocked': '操作员被禁用'
'403 Image Rotate Invalid Parameters': '图片旋转参数错误'
'403 Image Crop Invalid Parameters': '图片裁剪参数错误'
'404 Not Found': '获取文件或目录不存在;上传文件或目录时上级目录不存在'
'406 Not Acceptable(path)': '目录错误(创建目录时已存在同名文件;或上传文件时存在同名目录)'
'503 System Error': '系统错误'
@_upyun_api = (opt, cb)=>
opt.headers?= {}
opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD']
date = new Date().toUTCString()
if @password.match /^MD5_/
md5_password = @password.replace /^MD5_/, ''
else
md5_password = @<PASSWORD>5 @password
signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}&#{opt.length || opt.data?.length ||0}&#{md5_password}"
signature = @MD5 signature
opt.headers["Authorization"] = "UpYun #{@username}:#{signature}"
opt.headers["Date"] = date
@_upyun_api_req = req = @request
method: opt.method
url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}"
headers: opt.headers
body: opt.data
, (e, res, data)=>
return cb e if e
if res.statusCode == 200
cb null, data
else
status = String res.statusCode
if res.body
statusMatch = res.body.match(/\<h\d\>\d+\s(.+)\<\/\s*h\d\>/)
if status = statusMatch?[1]
status = "#{res.statusCode} #{status}"
else
status = res.body
status = @upyun_messages[status]||status
cb new Error status
opt.source?.pipe req
req.pipe opt.pipe if opt.pipe
req.on 'data', opt.onData if opt.onData
return =>
req.abort()
cb new Error '操作已取消'
@upyun_api = (opt, cb)=>
start = Date.now()
@_upyun_api opt, (e, data)=>
console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)"
cb e, data
Messenger.options =
extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right'
theme: 'future'
messageDefaults:
showCloseButton: true
hideAfter: 10
retry:
label: '重试'
phrase: 'TIME秒钟后重试'
auto: true
delay: 5
@createIcon = (icon)=>
$ document.createElement 'i'
.addClass "fa fa-#{icon}"
@shortOperation = (title, operation)=>
@shortOperationBusy = true
$ '#loadingText'
.text title||''
.append '<br />'
$ 'body'
.addClass 'loading'
$ btnCancel = document.createElement 'button'
.appendTo '#loadingText'
.addClass 'btn btn-default btn-xs btn-inline'
.text '取消'
.hide()
operationDone = (e)=>
@shortOperationBusy = false
$ 'body'
.removeClass 'loading'
if e
msg = Messenger().post
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@shortOperation title, operation
operation operationDone, $ btnCancel
@taskOperation = (title, operation)=>
msg = Messenger(
instance: @messengerTasks
extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom'
).post
hideAfter: 0
message: title
actions:
cancel:
label: '取消'
action: =>
$progresslabel1 = $ document.createElement 'span'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'pull-right'
$progressbar = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'progress progress-striped active'
.css margin: 0
.append $(document.createElement 'div').addClass('progress-bar').width '100%'
.append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%'
$progresslabel2 = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
operationProgress = (progress, progresstext)=>
$progresslabel2.text progresstext if progresstext
$progresslabel1.text "#{progress}%" if progress?
$progressbar
.toggleClass 'active', !progress?
$progressbar.children ':not(.progress-bar-success)'
.toggle !progress?
$progressbar.children '.progress-bar-success'
.toggle progress?
.width "#{progress}%"
operationDone = (e)=>
return unless msg
if e
msg.update
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@taskOperation title, operation
else
msg.hide()
operationProgress null
operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a')
@upyun_readdir = (url, cb)=>
@upyun_api
method: "GET"
url: url
, (e, data)=>
return cb e if e
files = data.split('\n').map (line)->
line = line.split '\t'
return null unless line.length == 4
return (
filename: line[0]
url: url + encodeURIComponent line[0]
isDirectory: line[1]=='F'
length: Number line[2]
mtime: 1000 * Number line[3]
)
cb null, files.filter (file)-> file?
@upyun_find_abort = ->
@upyun_find = (url, cb)=>
results = []
@upyun_find_abort = @upyun_readdir url, (e, files)=>
return cb e if e
@async.eachSeries files, (file, doneEach)=>
if file.isDirectory
@upyun_find file.url + '/', (e, tmp)=>
return doneEach e if e
results.push item for item in tmp
results.push file
doneEach null
else
results.push file
_.defer => doneEach null
, (e)=>
@upyun_find_abort = ->
cb e, results
@uypun_upload = (url, files, onProgress, cb)=>
aborted = false
api_aborting = null
aborting = =>
aborted = true
api_aborting?()
status =
total_files: files.length
total_bytes: files.reduce ((a, b)-> a + b.length), 0
current_files: 0
current_bytes: 0
@async.eachSeries files, (file, doneEach)=>
fs.stat file.path, (e, stats)=>
return doneEach (new Error '操作已取消') if aborted
return doneEach e if e
file_length = stats.size
file_stream = fs.createReadStream file.path
api_aborting = @upyun_api
method: "PUT"
headers:
'mkdir': 'true'
url: url + file.url
length: file_length
, (e)=>
status.current_files+= 1
onProgress status
doneEach e
req = @_upyun_api_req
file_stream.pipe req
file_stream.on 'data', (data)=>
status.current_bytes+= data.length
onProgress status
, cb
return aborting
@action_downloadFolder = (filename, url)=>
unless filename || filename = url.match(/([^\/]+)\/$/)?[1]
filename = @bucket
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
@nw_directory (savepath)=>
@taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
total_files = files.length
total_bytes = files.reduce ((a, b)-> a + b.length), 0
current_files = 0
current_bytes = 0
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
@async.eachSeries files, ((file, doneEach)=>
return (_.defer => doneEach null) if file.isDirectory
segs = file.url.substring(url.length).split '/'
segs = segs.map decodeURIComponent
destpath = @path.join savepath, filename, @path.join.apply @path, segs
@mkdirp @path.dirname(destpath), (e)=>
return doneEach e if e
stream = @fs.createWriteStream destpath
stream.on 'error', doneEach
stream.on 'open', =>
current_files+= 1
aborting = @upyun_api
method: 'GET'
url: file.url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * (current_bytes + stream.bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + stream.bytesWritten} / #{@humanFileSize total_bytes})"
, (e)=>
current_bytes+= file.length unless e
doneEach e
), (e)=>
aborting = null
doneTransfer e
unless e
msg = Messenger().post
message: "目录 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
@action_uploadFile = (filepath, filename, destpath)=>
@taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
files = []
loadfileSync = (file)=>
stat = @fs.statSync(file.path)
if stat.isFile()
file.length = stat.size
files.push file
if stat.isDirectory()
for filename in @fs.readdirSync file.path
loadfileSync
path: @path.join(file.path, filename)
url: file.url + '/' + encodeURIComponent filename
try
loadfileSync path: filepath, url: ''
catch e
return doneTransfer e if e
$btnCancelTransfer.show().click @uypun_upload destpath, files, (status)=>
progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})"
, (e)=>
doneTransfer e
unless e
@m_changed_path = destpath.replace /[^\/]+$/, ''
msg = Messenger().post
message: "文件 #{filename} 上传完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
@action_show_url = (title, url)=>
msg = Messenger().post
message: "#{title}<pre>#{url}</pre>"
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@action_share = (url)=>
url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}"
msg = Messenger().post
message: """
您可以通过以下地址向其他人分享该目录:
<pre>#{url}</pre>
注意:<ol>
<li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li>
<li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li>
</ol>
"""
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@nw_saveas = (filename, cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwsaveas: filename
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_directory = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwdirectory: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_selectfiles = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', multiple: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val.split ';'
.trigger 'click'
@jump_login = =>
@m_path = '/'
@m_active = false
@refresh_favs()
$ '#filelist, #editor'
.hide()
$ '#login'
.fadeIn()
@jump_filelist = =>
@jump_path '/'
@jump_path = (path)=>
@m_path = path
@m_changed_path = path
@m_active = true
@m_files = null
$ '#filelist .preloader'
.css
opacity: 1
$ '#inputFilter'
.val ''
$ '#login, #editor'
.hide()
$ '#filelist'
.fadeIn()
segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, ''
segs = segs.map decodeURIComponent
$ '#path'
.empty()
$ li = document.createElement 'li'
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @username
.prepend @createIcon 'user'
.attr 'href', '#'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ li = document.createElement 'li'
.toggleClass 'active', !segs.length
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @bucket
.prepend @createIcon 'cloud'
.attr 'href', "http://#{bucket}.b0.upaiyun.com/"
.data 'url', '/'
for seg, i in segs
url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/'
$ li = document.createElement 'li'
.toggleClass 'active', i == segs.length - 1
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text seg
.prepend @createIcon 'folder'
.attr 'href', "http://#{bucket}.b0.upaiyun.com#{url}"
.data 'url', url
$ '#path li:not(:first-child)>a'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data 'url'
@refresh_filelist = (cb)=>
cur_path = @m_path
@upyun_readdir cur_path, (e, files)=>
return cb e if e
if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files)
$('#filelist tbody').empty()
$('#filelist .preloader').css
opacity: 0
for file in @m_files = files
$ tr = document.createElement 'tr'
.appendTo '#filelist tbody'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ a = document.createElement 'a'
.appendTo td
.text file.filename
.prepend @createIcon 'folder'
.attr 'href', "#"
.data 'url', file.url + '/'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data('url')
else
$ td
.text file.filename
.prepend @createIcon 'file'
$ document.createElement 'td'
.appendTo tr
.text if file.isDirectory then '' else @humanFileSize file.length
$ document.createElement 'td'
.appendTo tr
.text @moment(file.mtime).format 'LLL'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '删除该目录'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url + '/'
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
files_deleting = 0
async.eachSeries files, (file, doneEach)=>
files_deleting+= 1
@shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: file.url
, (e)=>
operationDone e
doneEach e
, (e)=>
unless e
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /[^\/]+\/$/, ''
operationDone e
else
$ document.createElement 'button'
.appendTo td
.attr title: '删除该文件'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
url = $(ev.currentTarget).data('url')
filename = $(ev.currentTarget).data('filename')
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /\/[^\/]+$/, '/'
operationDone e
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '下载该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url + '/'
.data 'filename', file.filename
.click (ev)=>
@action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url')
$ document.createElement 'button'
.appendTo td
.attr title: '向其他人分享该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'share'
.data 'url', file.url + '/'
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@action_share url
else
$ document.createElement 'button'
.appendTo td
.attr title: '下载该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url
.data 'filename', file.filename
.data 'length', file.length
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
length = $(ev.currentTarget).data 'length'
@nw_saveas filename, (savepath)=>
@taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
stream = @fs.createWriteStream savepath
stream.on 'error', doneTransfer
stream.on 'open', =>
aborting = @upyun_api
method: "GET"
url: url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * stream.bytesWritten / length), "#{@humanFileSize stream.bytesWritten} / #{@humanFileSize length}"
, (e, data)=>
doneTransfer e
unless e
msg = Messenger().post
message: "文件 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
showItemInFolder:
label: "打开目录"
action: =>
msg.hide()
@gui.Shell.showItemInFolder savepath
$ document.createElement 'button'
.appendTo td
.attr title: '在浏览器中访问该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'globe'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@gui.Shell.openExternal url
$ document.createElement 'button'
.appendTo td
.attr title: '公共地址'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'code'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.data 'filename', file.filename
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@action_show_url "文件 #{filename} 的公共地址(URL)", url
$ document.createElement 'button'
.appendTo td
.attr title: '用文本编辑器打开该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'edit'
.data 'url', file.url
.data 'filename', file.filename
.click (ev)=>
@open '?' + $.param
username: @username
password: <PASSWORD>
bucket: @bucket
default_action: 'editor'
editor_url: $(ev.currentTarget).data 'url'
editor_filename: $(ev.currentTarget).data 'filename'
$('#filelist tbody [title]')
.tooltip
placement: 'bottom'
trigger: 'hover'
cb null
@jump_editor = =>
$ '#login, #filelist'
.hide()
$ '#editor'
.show()
@document.title = @editor_filename
@editor = @ace.edit $('#editor .editor')[0]
$('#btnReloadEditor').click()
window.ondragover = window.ondrop = (ev)->
ev.preventDefault()
return false
$ =>
@messengerTasks = $ document.createElement 'ul'
.appendTo 'body'
.messenger()
forverCounter = 0
@async.forever (doneForever)=>
if @m_active && !@shortOperationBusy
forverCounter += 1
if forverCounter == 20 || @m_changed_path == @m_path
forverCounter = 0
@m_changed_path = null
return @refresh_filelist (e)=>
if e
msg = Messenger().post
message: e.message
type: 'error'
actions:
ok:
label: '确定'
action: =>
msg.hide()
@jump_login()
setTimeout (=>doneForever null), 100
setTimeout (=>doneForever null), 100
, (e)=>
throw e
$ '#btnAddFav'
.click =>
fav = $('#formLogin').serializeObject()
fav.password = "<PASSWORD>" + @<PASSWORD>5 fav.password unless fav.password.match /^<PASSWORD>_/
@m_favs["#{fav.username}@#{fav.bucket}"] = fav
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
$ '#formLogin'
.submit (ev)=>
ev.preventDefault()
@[k] = v for k, v of $(ev.currentTarget).serializeObject()
@password = "<PASSWORD>" + @MD5 @password unless @password.match /^<PASSWORD>_/
$ '#filelist tbody'
.empty()
@jump_filelist()
$ window
.on 'dragover', -> $('body').addClass 'drag_hover'
.on 'dragleave', -> $('body').removeClass 'drag_hover'
.on 'dragend', -> $('body').removeClass 'drag_hover'
.on 'drop', (ev)=>
$('body').removeClass 'drag_hover'
ev.preventDefault()
for file in ev.originalEvent.dataTransfer.files
@action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}"
$ '#inputFilter'
.keydown =>
_.defer =>
val = String $('#inputFilter').val()
$ "#filelist tbody tr:contains(#{JSON.stringify val})"
.removeClass 'filtered'
$ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))"
.addClass 'filtered'
$ '#btnDownloadFolder'
.click (ev)=>
ev.preventDefault()
@action_downloadFolder null, @m_path
$ '#btnUploadFiles'
.click (ev)=>
ev.preventDefault()
@nw_selectfiles (files)=>
for filepath in files
filename = @path.basename filepath
@action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}"
$ '#btnUploadFolder'
.click (ev)=>
ev.preventDefault()
@nw_directory (dirpath)=>
@action_uploadFile dirpath, @path.basename(dirpath), @m_path
$ '#btnCreateFolder'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新目录的名称"
@shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=>
cur_path = @m_path
$btnCancelCreateing.click @upyun_api
url: "#{cur_path}#{filename}"
method: "POST"
headers:
'Folder': 'true'
, (e, data)=>
doneCreating e
@m_changed_path = cur_path
$ '#btnCreateFile'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新文件的文件名"
@open '?' + $.param
username: @username
password: <PASSWORD>
bucket: @bucket
default_action: 'editor'
editor_url: "#{@m_path}#{filename}"
editor_filename: filename
$ '#btnReloadEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在加载文件 #{editor_filename} ...", (doneReloading, $btnCancelReloading)=>
$btnCancelReloading.click @upyun_api
url: @editor_url
method: 'GET'
, (e, data)=>
if e
data = ''
else
data = data.toString 'utf8'
doneReloading null
unless e
@editor.setValue data
$ '#btnShareFolder'
.click (ev)=>
@action_share @m_path
$ '#btnSaveEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在保存文件 #{editor_filename} ...", (doneSaving, $btnCancelSaving)=>
$btnCancelSaving.click @upyun_api
url: @editor_url
method: 'PUT'
data: new Buffer @editor.getValue(), 'utf8'
, (e)=>
doneSaving e
unless e
msg = Messenger().post
message: "成功保存文件 #{editor_filename}"
actions:
ok:
label: '确定'
action: =>
msg.hide()
$ '#btnLogout'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ '#btnIssues'
.click (ev)=>
ev.preventDefault()
@gui.Shell.openExternal "https://gitcafe.com/layerssss/manager-for-upyun/tickets"
$ '[title]'
.tooltip
placement: 'bottom'
trigger: 'hover'
if (url = @gui.App.argv.pop()) && (url = @url.parse url).protocol.toLowerCase() == 'upyun:' && (auth = url.auth?.split ':')?.length == 2
newSearch = "?username=#{encodeURIComponent auth[0]}&password=#{encodeURIComponent auth[1]}&bucket=#{url.hostname}&m_path=#{encodeURIComponent url.pathname}&default_action=#{encodeURIComponent (url.hash?.replace /^\#/, '')||'filelist'}"
return location.search = newSearch unless location.search == newSearch
for m in location.search.match(/([^\&?]+)\=([^\&]+)/g)||[]
m = m.split '='
@[decodeURIComponent m[0]] = decodeURIComponent m[1]
(@["jump_#{@default_action}"]||@jump_login)()
| true | # = require_tree .
# = require jquery
# = require jquery-serialize-object
# = require bootstrap
# = require underscore
# = require underscore.string/dist/underscore.string.min
# = require messenger/build/js/messenger
# = require messenger/build/js/messenger-theme-future
# = require ace-builds/src-noconflict/ace.js
if @require?
@request = @require 'request'
@moment = @require 'moment'
@moment.lang 'zh-cn'
@async = @require 'async'
@fs = @require 'fs'
@os = @require 'os'
@path = @require 'path'
@mkdirp = @require 'mkdirp'
@gui = @require 'nw.gui'
@MD5 = require 'MD5'
@url = require 'url'
try
@m_favs = JSON.parse(localStorage.favs)||{}
catch
@m_favs = {}
@refresh_favs = =>
$ '#favs'
.empty()
for k, fav of @m_favs
$ li = document.createElement 'li'
.appendTo '#favs'
$ document.createElement 'a'
.appendTo li
.text k
.attr href: '#'
.data 'fav', fav
.click (ev)=>
ev.preventDefault()
$(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active'
for k, v of $(ev.currentTarget).data 'fav'
$ "#input#{_.str.capitalize k}"
.val v
$ '#formLogin'
.submit()
$ document.createElement 'button'
.appendTo li
.prepend @createIcon 'trash-o'
.addClass 'btn btn-danger btn-xs'
.attr 'title', '删除这条收藏记录'
.tooltip placement: 'bottom'
.data 'fav', fav
.click (ev)=>
fav = $(ev.currentTarget).data 'fav'
delete @m_favs["#{fav.username}@#{fav.bucket}"]
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
@humanFileSize = (bytes, si) ->
thresh = (if si then 1000 else 1024)
return bytes + " B" if bytes < thresh
units = (if si then [
"kB"
"MB"
"GB"
"TB"
"PB"
"EB"
"ZB"
"YB"
] else [
"KiB"
"MiB"
"GiB"
"TiB"
"PiB"
"EiB"
"ZiB"
"YiB"
])
u = -1
loop
bytes /= thresh
++u
break unless bytes >= thresh
bytes.toFixed(1) + " " + units[u]
@upyun_messages =
'200 OK': '操作成功'
'404': '找不到文件'
'400 Bad Request': '错误请求(如 URL 缺少空间名)'
'401 Unauthorized': '访问未授权'
'401 Sign error': '签名错误(操作员和密码,或签名格式错误)'
'401 Need Date Header': '发起的请求缺少 Date 头信息'
'401 Date offset error': '发起请求的服务器时间错误,请检查服务器时间是否与世界时间一致'
'403 Not Access': '权限错误(如非图片文件上传到图片空间)'
'403 File size too max': '单个文件超出大小(100Mb 以内)'
'403 Not a Picture File': '图片类空间错误码,非图片文件或图片文件格式错误。针对图片空间只允许上传 jpg/png/gif/bmp/tif 格式。'
'403 Picture Size too max': '图片类空间错误码,图片尺寸太大。针对图片空间,图片总像素在 200000000 以内。'
'403 Bucket full': '空间已用满'
'403 Bucket blocked': '空间被禁用,请联系管理员'
'403 User blocked': '操作员被禁用'
'403 Image Rotate Invalid Parameters': '图片旋转参数错误'
'403 Image Crop Invalid Parameters': '图片裁剪参数错误'
'404 Not Found': '获取文件或目录不存在;上传文件或目录时上级目录不存在'
'406 Not Acceptable(path)': '目录错误(创建目录时已存在同名文件;或上传文件时存在同名目录)'
'503 System Error': '系统错误'
@_upyun_api = (opt, cb)=>
opt.headers?= {}
opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD']
date = new Date().toUTCString()
if @password.match /^MD5_/
md5_password = @password.replace /^MD5_/, ''
else
md5_password = @PI:PASSWORD:<PASSWORD>END_PI5 @password
signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}&#{opt.length || opt.data?.length ||0}&#{md5_password}"
signature = @MD5 signature
opt.headers["Authorization"] = "UpYun #{@username}:#{signature}"
opt.headers["Date"] = date
@_upyun_api_req = req = @request
method: opt.method
url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}"
headers: opt.headers
body: opt.data
, (e, res, data)=>
return cb e if e
if res.statusCode == 200
cb null, data
else
status = String res.statusCode
if res.body
statusMatch = res.body.match(/\<h\d\>\d+\s(.+)\<\/\s*h\d\>/)
if status = statusMatch?[1]
status = "#{res.statusCode} #{status}"
else
status = res.body
status = @upyun_messages[status]||status
cb new Error status
opt.source?.pipe req
req.pipe opt.pipe if opt.pipe
req.on 'data', opt.onData if opt.onData
return =>
req.abort()
cb new Error '操作已取消'
@upyun_api = (opt, cb)=>
start = Date.now()
@_upyun_api opt, (e, data)=>
console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)"
cb e, data
Messenger.options =
extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right'
theme: 'future'
messageDefaults:
showCloseButton: true
hideAfter: 10
retry:
label: '重试'
phrase: 'TIME秒钟后重试'
auto: true
delay: 5
@createIcon = (icon)=>
$ document.createElement 'i'
.addClass "fa fa-#{icon}"
@shortOperation = (title, operation)=>
@shortOperationBusy = true
$ '#loadingText'
.text title||''
.append '<br />'
$ 'body'
.addClass 'loading'
$ btnCancel = document.createElement 'button'
.appendTo '#loadingText'
.addClass 'btn btn-default btn-xs btn-inline'
.text '取消'
.hide()
operationDone = (e)=>
@shortOperationBusy = false
$ 'body'
.removeClass 'loading'
if e
msg = Messenger().post
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@shortOperation title, operation
operation operationDone, $ btnCancel
@taskOperation = (title, operation)=>
msg = Messenger(
instance: @messengerTasks
extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom'
).post
hideAfter: 0
message: title
actions:
cancel:
label: '取消'
action: =>
$progresslabel1 = $ document.createElement 'span'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'pull-right'
$progressbar = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
.addClass 'progress progress-striped active'
.css margin: 0
.append $(document.createElement 'div').addClass('progress-bar').width '100%'
.append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%'
$progresslabel2 = $ document.createElement 'div'
.appendTo msg.$message.find('.messenger-message-inner')
operationProgress = (progress, progresstext)=>
$progresslabel2.text progresstext if progresstext
$progresslabel1.text "#{progress}%" if progress?
$progressbar
.toggleClass 'active', !progress?
$progressbar.children ':not(.progress-bar-success)'
.toggle !progress?
$progressbar.children '.progress-bar-success'
.toggle progress?
.width "#{progress}%"
operationDone = (e)=>
return unless msg
if e
msg.update
type: 'error'
message: e.message
showCloseButton: true
actions:
ok:
label: '确定'
action: =>
msg.hide()
retry:
label: '重试'
action: =>
msg.hide()
@taskOperation title, operation
else
msg.hide()
operationProgress null
operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a')
@upyun_readdir = (url, cb)=>
@upyun_api
method: "GET"
url: url
, (e, data)=>
return cb e if e
files = data.split('\n').map (line)->
line = line.split '\t'
return null unless line.length == 4
return (
filename: line[0]
url: url + encodeURIComponent line[0]
isDirectory: line[1]=='F'
length: Number line[2]
mtime: 1000 * Number line[3]
)
cb null, files.filter (file)-> file?
@upyun_find_abort = ->
@upyun_find = (url, cb)=>
results = []
@upyun_find_abort = @upyun_readdir url, (e, files)=>
return cb e if e
@async.eachSeries files, (file, doneEach)=>
if file.isDirectory
@upyun_find file.url + '/', (e, tmp)=>
return doneEach e if e
results.push item for item in tmp
results.push file
doneEach null
else
results.push file
_.defer => doneEach null
, (e)=>
@upyun_find_abort = ->
cb e, results
@uypun_upload = (url, files, onProgress, cb)=>
aborted = false
api_aborting = null
aborting = =>
aborted = true
api_aborting?()
status =
total_files: files.length
total_bytes: files.reduce ((a, b)-> a + b.length), 0
current_files: 0
current_bytes: 0
@async.eachSeries files, (file, doneEach)=>
fs.stat file.path, (e, stats)=>
return doneEach (new Error '操作已取消') if aborted
return doneEach e if e
file_length = stats.size
file_stream = fs.createReadStream file.path
api_aborting = @upyun_api
method: "PUT"
headers:
'mkdir': 'true'
url: url + file.url
length: file_length
, (e)=>
status.current_files+= 1
onProgress status
doneEach e
req = @_upyun_api_req
file_stream.pipe req
file_stream.on 'data', (data)=>
status.current_bytes+= data.length
onProgress status
, cb
return aborting
@action_downloadFolder = (filename, url)=>
unless filename || filename = url.match(/([^\/]+)\/$/)?[1]
filename = @bucket
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
@nw_directory (savepath)=>
@taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
total_files = files.length
total_bytes = files.reduce ((a, b)-> a + b.length), 0
current_files = 0
current_bytes = 0
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
@async.eachSeries files, ((file, doneEach)=>
return (_.defer => doneEach null) if file.isDirectory
segs = file.url.substring(url.length).split '/'
segs = segs.map decodeURIComponent
destpath = @path.join savepath, filename, @path.join.apply @path, segs
@mkdirp @path.dirname(destpath), (e)=>
return doneEach e if e
stream = @fs.createWriteStream destpath
stream.on 'error', doneEach
stream.on 'open', =>
current_files+= 1
aborting = @upyun_api
method: 'GET'
url: file.url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * (current_bytes + stream.bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + stream.bytesWritten} / #{@humanFileSize total_bytes})"
, (e)=>
current_bytes+= file.length unless e
doneEach e
), (e)=>
aborting = null
doneTransfer e
unless e
msg = Messenger().post
message: "目录 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
@action_uploadFile = (filepath, filename, destpath)=>
@taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
files = []
loadfileSync = (file)=>
stat = @fs.statSync(file.path)
if stat.isFile()
file.length = stat.size
files.push file
if stat.isDirectory()
for filename in @fs.readdirSync file.path
loadfileSync
path: @path.join(file.path, filename)
url: file.url + '/' + encodeURIComponent filename
try
loadfileSync path: filepath, url: ''
catch e
return doneTransfer e if e
$btnCancelTransfer.show().click @uypun_upload destpath, files, (status)=>
progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})"
, (e)=>
doneTransfer e
unless e
@m_changed_path = destpath.replace /[^\/]+$/, ''
msg = Messenger().post
message: "文件 #{filename} 上传完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
@action_show_url = (title, url)=>
msg = Messenger().post
message: "#{title}<pre>#{url}</pre>"
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@action_share = (url)=>
url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}"
msg = Messenger().post
message: """
您可以通过以下地址向其他人分享该目录:
<pre>#{url}</pre>
注意:<ol>
<li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li>
<li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li>
</ol>
"""
actions:
ok:
label: '确定'
action: =>
msg.hide()
copy:
label: '将该地址复制到剪切版'
action: (ev)=>
$(ev.currentTarget).text '已复制到剪切版'
@gui.Clipboard.get().set url, 'text'
@nw_saveas = (filename, cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwsaveas: filename
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_directory = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', nwdirectory: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val
.trigger 'click'
@nw_selectfiles = (cb)=>
$ dlg = document.createElement 'input'
.appendTo 'body'
.css position: 'absolute', top: - 50
.attr type: 'file', multiple: true
.on 'change', =>
val = $(dlg).val()
$(dlg).remove()
cb val.split ';'
.trigger 'click'
@jump_login = =>
@m_path = '/'
@m_active = false
@refresh_favs()
$ '#filelist, #editor'
.hide()
$ '#login'
.fadeIn()
@jump_filelist = =>
@jump_path '/'
@jump_path = (path)=>
@m_path = path
@m_changed_path = path
@m_active = true
@m_files = null
$ '#filelist .preloader'
.css
opacity: 1
$ '#inputFilter'
.val ''
$ '#login, #editor'
.hide()
$ '#filelist'
.fadeIn()
segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, ''
segs = segs.map decodeURIComponent
$ '#path'
.empty()
$ li = document.createElement 'li'
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @username
.prepend @createIcon 'user'
.attr 'href', '#'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ li = document.createElement 'li'
.toggleClass 'active', !segs.length
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text @bucket
.prepend @createIcon 'cloud'
.attr 'href', "http://#{bucket}.b0.upaiyun.com/"
.data 'url', '/'
for seg, i in segs
url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/'
$ li = document.createElement 'li'
.toggleClass 'active', i == segs.length - 1
.appendTo '#path'
$ document.createElement 'a'
.appendTo li
.text seg
.prepend @createIcon 'folder'
.attr 'href', "http://#{bucket}.b0.upaiyun.com#{url}"
.data 'url', url
$ '#path li:not(:first-child)>a'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data 'url'
@refresh_filelist = (cb)=>
cur_path = @m_path
@upyun_readdir cur_path, (e, files)=>
return cb e if e
if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files)
$('#filelist tbody').empty()
$('#filelist .preloader').css
opacity: 0
for file in @m_files = files
$ tr = document.createElement 'tr'
.appendTo '#filelist tbody'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ a = document.createElement 'a'
.appendTo td
.text file.filename
.prepend @createIcon 'folder'
.attr 'href', "#"
.data 'url', file.url + '/'
.click (ev)=>
ev.preventDefault()
@jump_path $(ev.currentTarget).data('url')
else
$ td
.text file.filename
.prepend @createIcon 'file'
$ document.createElement 'td'
.appendTo tr
.text if file.isDirectory then '' else @humanFileSize file.length
$ document.createElement 'td'
.appendTo tr
.text @moment(file.mtime).format 'LLL'
$ td = document.createElement 'td'
.appendTo tr
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '删除该目录'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url + '/'
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=>
$btnCancelFind.show().click => @upyun_find_abort()
@upyun_find url, (e, files)=>
doneFind e
unless e
files_deleting = 0
async.eachSeries files, (file, doneEach)=>
files_deleting+= 1
@shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: file.url
, (e)=>
operationDone e
doneEach e
, (e)=>
unless e
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /[^\/]+\/$/, ''
operationDone e
else
$ document.createElement 'button'
.appendTo td
.attr title: '删除该文件'
.addClass 'btn btn-danger btn-xs'
.data 'url', file.url
.data 'filename', file.filename
.prepend @createIcon 'trash-o'
.click (ev)=>
url = $(ev.currentTarget).data('url')
filename = $(ev.currentTarget).data('filename')
@shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=>
$btnCancelDel.show().click @upyun_api
method: "DELETE"
url: url
, (e)=>
@m_changed_path = url.replace /\/[^\/]+$/, '/'
operationDone e
if file.isDirectory
$ document.createElement 'button'
.appendTo td
.attr title: '下载该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url + '/'
.data 'filename', file.filename
.click (ev)=>
@action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url')
$ document.createElement 'button'
.appendTo td
.attr title: '向其他人分享该目录'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'share'
.data 'url', file.url + '/'
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@action_share url
else
$ document.createElement 'button'
.appendTo td
.attr title: '下载该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'download'
.data 'url', file.url
.data 'filename', file.filename
.data 'length', file.length
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
length = $(ev.currentTarget).data 'length'
@nw_saveas filename, (savepath)=>
@taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=>
aborting = null
$btnCancelTransfer.click =>
aborting() if aborting?
stream = @fs.createWriteStream savepath
stream.on 'error', doneTransfer
stream.on 'open', =>
aborting = @upyun_api
method: "GET"
url: url
pipe: stream
onData: =>
progressTransfer (Math.floor 100 * stream.bytesWritten / length), "#{@humanFileSize stream.bytesWritten} / #{@humanFileSize length}"
, (e, data)=>
doneTransfer e
unless e
msg = Messenger().post
message: "文件 #{filename} 下载完毕"
actions:
ok:
label: '确定'
action: =>
msg.hide()
open:
label: "打开"
action: =>
msg.hide()
@gui.Shell.openItem savepath
showItemInFolder:
label: "打开目录"
action: =>
msg.hide()
@gui.Shell.showItemInFolder savepath
$ document.createElement 'button'
.appendTo td
.attr title: '在浏览器中访问该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'globe'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.click (ev)=>
url = $(ev.currentTarget).data 'url'
@gui.Shell.openExternal url
$ document.createElement 'button'
.appendTo td
.attr title: '公共地址'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'code'
.data 'url', "http://#{@bucket}.b0.upaiyun.com#{file.url}"
.data 'filename', file.filename
.click (ev)=>
filename = $(ev.currentTarget).data 'filename'
url = $(ev.currentTarget).data 'url'
@action_show_url "文件 #{filename} 的公共地址(URL)", url
$ document.createElement 'button'
.appendTo td
.attr title: '用文本编辑器打开该文件'
.addClass 'btn btn-info btn-xs'
.prepend @createIcon 'edit'
.data 'url', file.url
.data 'filename', file.filename
.click (ev)=>
@open '?' + $.param
username: @username
password: PI:PASSWORD:<PASSWORD>END_PI
bucket: @bucket
default_action: 'editor'
editor_url: $(ev.currentTarget).data 'url'
editor_filename: $(ev.currentTarget).data 'filename'
$('#filelist tbody [title]')
.tooltip
placement: 'bottom'
trigger: 'hover'
cb null
@jump_editor = =>
$ '#login, #filelist'
.hide()
$ '#editor'
.show()
@document.title = @editor_filename
@editor = @ace.edit $('#editor .editor')[0]
$('#btnReloadEditor').click()
window.ondragover = window.ondrop = (ev)->
ev.preventDefault()
return false
$ =>
@messengerTasks = $ document.createElement 'ul'
.appendTo 'body'
.messenger()
forverCounter = 0
@async.forever (doneForever)=>
if @m_active && !@shortOperationBusy
forverCounter += 1
if forverCounter == 20 || @m_changed_path == @m_path
forverCounter = 0
@m_changed_path = null
return @refresh_filelist (e)=>
if e
msg = Messenger().post
message: e.message
type: 'error'
actions:
ok:
label: '确定'
action: =>
msg.hide()
@jump_login()
setTimeout (=>doneForever null), 100
setTimeout (=>doneForever null), 100
, (e)=>
throw e
$ '#btnAddFav'
.click =>
fav = $('#formLogin').serializeObject()
fav.password = "PI:PASSWORD:<PASSWORD>END_PI" + @PI:PASSWORD:<PASSWORD>END_PI5 fav.password unless fav.password.match /^PI:PASSWORD:<PASSWORD>END_PI_/
@m_favs["#{fav.username}@#{fav.bucket}"] = fav
localStorage.favs = JSON.stringify @m_favs
@refresh_favs()
$ '#formLogin'
.submit (ev)=>
ev.preventDefault()
@[k] = v for k, v of $(ev.currentTarget).serializeObject()
@password = "PI:PASSWORD:<PASSWORD>END_PI" + @MD5 @password unless @password.match /^PI:PASSWORD:<PASSWORD>END_PI_/
$ '#filelist tbody'
.empty()
@jump_filelist()
$ window
.on 'dragover', -> $('body').addClass 'drag_hover'
.on 'dragleave', -> $('body').removeClass 'drag_hover'
.on 'dragend', -> $('body').removeClass 'drag_hover'
.on 'drop', (ev)=>
$('body').removeClass 'drag_hover'
ev.preventDefault()
for file in ev.originalEvent.dataTransfer.files
@action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}"
$ '#inputFilter'
.keydown =>
_.defer =>
val = String $('#inputFilter').val()
$ "#filelist tbody tr:contains(#{JSON.stringify val})"
.removeClass 'filtered'
$ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))"
.addClass 'filtered'
$ '#btnDownloadFolder'
.click (ev)=>
ev.preventDefault()
@action_downloadFolder null, @m_path
$ '#btnUploadFiles'
.click (ev)=>
ev.preventDefault()
@nw_selectfiles (files)=>
for filepath in files
filename = @path.basename filepath
@action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}"
$ '#btnUploadFolder'
.click (ev)=>
ev.preventDefault()
@nw_directory (dirpath)=>
@action_uploadFile dirpath, @path.basename(dirpath), @m_path
$ '#btnCreateFolder'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新目录的名称"
@shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=>
cur_path = @m_path
$btnCancelCreateing.click @upyun_api
url: "#{cur_path}#{filename}"
method: "POST"
headers:
'Folder': 'true'
, (e, data)=>
doneCreating e
@m_changed_path = cur_path
$ '#btnCreateFile'
.click (ev)=>
ev.preventDefault()
if filename = prompt "请输入新文件的文件名"
@open '?' + $.param
username: @username
password: PI:PASSWORD:<PASSWORD>END_PI
bucket: @bucket
default_action: 'editor'
editor_url: "#{@m_path}#{filename}"
editor_filename: filename
$ '#btnReloadEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在加载文件 #{editor_filename} ...", (doneReloading, $btnCancelReloading)=>
$btnCancelReloading.click @upyun_api
url: @editor_url
method: 'GET'
, (e, data)=>
if e
data = ''
else
data = data.toString 'utf8'
doneReloading null
unless e
@editor.setValue data
$ '#btnShareFolder'
.click (ev)=>
@action_share @m_path
$ '#btnSaveEditor'
.click (ev)=>
ev.preventDefault()
@shortOperation "正在保存文件 #{editor_filename} ...", (doneSaving, $btnCancelSaving)=>
$btnCancelSaving.click @upyun_api
url: @editor_url
method: 'PUT'
data: new Buffer @editor.getValue(), 'utf8'
, (e)=>
doneSaving e
unless e
msg = Messenger().post
message: "成功保存文件 #{editor_filename}"
actions:
ok:
label: '确定'
action: =>
msg.hide()
$ '#btnLogout'
.click (ev)=>
ev.preventDefault()
@jump_login()
$ '#btnIssues'
.click (ev)=>
ev.preventDefault()
@gui.Shell.openExternal "https://gitcafe.com/layerssss/manager-for-upyun/tickets"
$ '[title]'
.tooltip
placement: 'bottom'
trigger: 'hover'
if (url = @gui.App.argv.pop()) && (url = @url.parse url).protocol.toLowerCase() == 'upyun:' && (auth = url.auth?.split ':')?.length == 2
newSearch = "?username=#{encodeURIComponent auth[0]}&password=#{encodeURIComponent auth[1]}&bucket=#{url.hostname}&m_path=#{encodeURIComponent url.pathname}&default_action=#{encodeURIComponent (url.hash?.replace /^\#/, '')||'filelist'}"
return location.search = newSearch unless location.search == newSearch
for m in location.search.match(/([^\&?]+)\=([^\&]+)/g)||[]
m = m.split '='
@[decodeURIComponent m[0]] = decodeURIComponent m[1]
(@["jump_#{@default_action}"]||@jump_login)()
|
[
{
"context": "ef}\"\n [\n DOM.a\n key: \"a-#{@props.text}-#{@props.href}\"\n href: '",
"end": 669,
"score": 0.6360454559326172,
"start": 669,
"tag": "KEY",
"value": ""
},
{
"context": "\n DOM.a\n key: \"a-#{@props.text}-#{@pro... | src/components/main.coffee | brianshaler/kerplunk-admin | 0 | _ = require 'lodash'
React = require 'react'
{DOM} = React
Item = React.createFactory React.createClass
getInitialState: ->
expanded: false
toggle: (e) ->
e.preventDefault()
@setState
expanded: !@state.expanded
render: ->
classes = ['admin-link']
if @props.children.length > 0
classes.push ''
if @state.expanded
classes.push 'expanded'
else
classes.push 'collapsed'
if @state.active
classes.push 'active'
DOM.li
className: classes.join ' '
,
if @props.children.length > 0
#console.log "ul-#{@props.text}-#{@props.href}"
[
DOM.a
key: "a-#{@props.text}-#{@props.href}"
href: '#'
onClick: @toggle
,
@props.text
DOM.ul
key: "ul-#{@props.text}-#{@props.href}"
className: 'admin-links'
style:
display: ('block' if @state.expanded)
,
_.map @props.children, (kid, index) =>
Item _.extend {key: index}, @props, kid
]
else
DOM.a
href: @props.href
onClick: (e) =>
@props.pushState e, true
, @props.text
processItem = (item, text) ->
href = if typeof item is 'string'
item
else
'#'
children = if typeof item is 'object'
_.map item, processItem
else
null
text: text
href: href
children: children ? []
module.exports = React.createFactory React.createClass
getInitialState: ->
items: @getItems @props
getItems: (props = @props) ->
_.map props.globals.public.nav, processItem
componentWillReceiveProps: (newProps) ->
@setState
items: @getItems newProps
render: ->
DOM.section
className: 'content'
,
_.map @state.items, (item, index) =>
DOM.section
className: 'col-lg-4 col-md-6 admin-block'
key: index
,
DOM.div
className: 'box box-info admin-panel'
,
DOM.div
className: 'box-header'
,
DOM.em className: 'fa fa-gear'
DOM.div
className: 'box-title'
,
item.text ? item.segment
DOM.div
className: 'box-body admin-panel-content'
,
DOM.ul
className: 'admin-links'
,
_.map item.children, (item, index) =>
Item _.extend {key: index}, @props, item
| 60917 | _ = require 'lodash'
React = require 'react'
{DOM} = React
Item = React.createFactory React.createClass
getInitialState: ->
expanded: false
toggle: (e) ->
e.preventDefault()
@setState
expanded: !@state.expanded
render: ->
classes = ['admin-link']
if @props.children.length > 0
classes.push ''
if @state.expanded
classes.push 'expanded'
else
classes.push 'collapsed'
if @state.active
classes.push 'active'
DOM.li
className: classes.join ' '
,
if @props.children.length > 0
#console.log "ul-#{@props.text}-#{@props.href}"
[
DOM.a
key: "a<KEY>-#{@props.text<KEY>}-#{@props.href}"
href: '#'
onClick: @toggle
,
@props.text
DOM.ul
key: "ul-#{@props.text}-#{@props.href}"
className: 'admin-links'
style:
display: ('block' if @state.expanded)
,
_.map @props.children, (kid, index) =>
Item _.extend {key: index}, @props, kid
]
else
DOM.a
href: @props.href
onClick: (e) =>
@props.pushState e, true
, @props.text
processItem = (item, text) ->
href = if typeof item is 'string'
item
else
'#'
children = if typeof item is 'object'
_.map item, processItem
else
null
text: text
href: href
children: children ? []
module.exports = React.createFactory React.createClass
getInitialState: ->
items: @getItems @props
getItems: (props = @props) ->
_.map props.globals.public.nav, processItem
componentWillReceiveProps: (newProps) ->
@setState
items: @getItems newProps
render: ->
DOM.section
className: 'content'
,
_.map @state.items, (item, index) =>
DOM.section
className: 'col-lg-4 col-md-6 admin-block'
key: index
,
DOM.div
className: 'box box-info admin-panel'
,
DOM.div
className: 'box-header'
,
DOM.em className: 'fa fa-gear'
DOM.div
className: 'box-title'
,
item.text ? item.segment
DOM.div
className: 'box-body admin-panel-content'
,
DOM.ul
className: 'admin-links'
,
_.map item.children, (item, index) =>
Item _.extend {key: index}, @props, item
| true | _ = require 'lodash'
React = require 'react'
{DOM} = React
Item = React.createFactory React.createClass
getInitialState: ->
expanded: false
toggle: (e) ->
e.preventDefault()
@setState
expanded: !@state.expanded
render: ->
classes = ['admin-link']
if @props.children.length > 0
classes.push ''
if @state.expanded
classes.push 'expanded'
else
classes.push 'collapsed'
if @state.active
classes.push 'active'
DOM.li
className: classes.join ' '
,
if @props.children.length > 0
#console.log "ul-#{@props.text}-#{@props.href}"
[
DOM.a
key: "aPI:KEY:<KEY>END_PI-#{@props.textPI:KEY:<KEY>END_PI}-#{@props.href}"
href: '#'
onClick: @toggle
,
@props.text
DOM.ul
key: "ul-#{@props.text}-#{@props.href}"
className: 'admin-links'
style:
display: ('block' if @state.expanded)
,
_.map @props.children, (kid, index) =>
Item _.extend {key: index}, @props, kid
]
else
DOM.a
href: @props.href
onClick: (e) =>
@props.pushState e, true
, @props.text
processItem = (item, text) ->
href = if typeof item is 'string'
item
else
'#'
children = if typeof item is 'object'
_.map item, processItem
else
null
text: text
href: href
children: children ? []
module.exports = React.createFactory React.createClass
getInitialState: ->
items: @getItems @props
getItems: (props = @props) ->
_.map props.globals.public.nav, processItem
componentWillReceiveProps: (newProps) ->
@setState
items: @getItems newProps
render: ->
DOM.section
className: 'content'
,
_.map @state.items, (item, index) =>
DOM.section
className: 'col-lg-4 col-md-6 admin-block'
key: index
,
DOM.div
className: 'box box-info admin-panel'
,
DOM.div
className: 'box-header'
,
DOM.em className: 'fa fa-gear'
DOM.div
className: 'box-title'
,
item.text ? item.segment
DOM.div
className: 'box-body admin-panel-content'
,
DOM.ul
className: 'admin-links'
,
_.map item.children, (item, index) =>
Item _.extend {key: index}, @props, item
|
[
{
"context": "ach ->\n homePage.get()\n homePage.login(\"John\", \"WRONG\")\n\n it 'should not go to dashboard', ",
"end": 199,
"score": 0.9977817535400391,
"start": 195,
"tag": "NAME",
"value": "John"
},
{
"context": "ach ->\n homePage.get()\n homePage.login(\... | app/specs/e2e/login_spec.coffee | asartalo/axya | 0 | 'use strict'
describe "E2E: Logging in", ->
homePage = new (require('./pages/home'))
describe 'with incorrect credentials', ->
beforeEach ->
homePage.get()
homePage.login("John", "WRONG")
it 'should not go to dashboard', ->
expect(browser.getCurrentUrl()).toNotContain('#/dashboard')
describe 'with correct credentials', ->
beforeEach ->
homePage.get()
homePage.login("Jane", "secret")
it 'should go to dashboard', ->
expect(browser.getCurrentUrl()).toContain('#/dashboard')
it 'should remember user\'s name', ->
expect(homePage.textContent()).toContain("Jane")
| 198068 | 'use strict'
describe "E2E: Logging in", ->
homePage = new (require('./pages/home'))
describe 'with incorrect credentials', ->
beforeEach ->
homePage.get()
homePage.login("<NAME>", "WRONG")
it 'should not go to dashboard', ->
expect(browser.getCurrentUrl()).toNotContain('#/dashboard')
describe 'with correct credentials', ->
beforeEach ->
homePage.get()
homePage.login("<NAME>", "secret")
it 'should go to dashboard', ->
expect(browser.getCurrentUrl()).toContain('#/dashboard')
it 'should remember user\'s name', ->
expect(homePage.textContent()).toContain("<NAME>")
| true | 'use strict'
describe "E2E: Logging in", ->
homePage = new (require('./pages/home'))
describe 'with incorrect credentials', ->
beforeEach ->
homePage.get()
homePage.login("PI:NAME:<NAME>END_PI", "WRONG")
it 'should not go to dashboard', ->
expect(browser.getCurrentUrl()).toNotContain('#/dashboard')
describe 'with correct credentials', ->
beforeEach ->
homePage.get()
homePage.login("PI:NAME:<NAME>END_PI", "secret")
it 'should go to dashboard', ->
expect(browser.getCurrentUrl()).toContain('#/dashboard')
it 'should remember user\'s name', ->
expect(homePage.textContent()).toContain("PI:NAME:<NAME>END_PI")
|
[
{
"context": " to librato',\n extra : 'see https://github.com/sdesbure/netatmo_librato'\n})\n\nparser.addArgument('secret' ",
"end": 344,
"score": 0.9995230436325073,
"start": 336,
"tag": "USERNAME",
"value": "sdesbure"
},
{
"context": "\"username\": secret.netatmo.username,\n \"... | netatmo_librato_daemon.coffee | sdesbure/netatmo_librato | 0 | #!/usr/bin/env coffee
require 'require-yaml'
require 'unorm'
xregexp = require('xregexp').XRegExp
netatmo = require('netatmo')
Parser = require('commandline-parser').Parser
parser = new Parser({
name : "netatmo_librato_daemon",
desc : 'a daemon which send data from netatmo to librato',
extra : 'see https://github.com/sdesbure/netatmo_librato'
})
parser.addArgument('secret' ,{
flags : ['s','secret'],
desc : "path to the secret file (defaulting to ./secret.yml)",
})
parser.addArgument('config' ,{
flags : ['c','config'],
desc : "path to the config file (defaulting to ./config.yml)",
})
secret_file = parser.get('secret')
if (!secret_file)
secret_file = './secret.yml'
config_file = parser.get('config')
if (!config_file)
config_file = './config.yml'
console.log("secret file used: " + secret_file)
console.log("config file used: " + config_file)
secret = require secret_file
config = require config_file
console.log config
root = exports ? this
ten_min_sec = 600
one_hour_sec = 3600
i = 0
norm = (string) ->
string.normalize("NFKD").replace(xregexp("\\p{M}", "g"), "").replace(new RegExp(" ", 'g'),"-")
auth = {
"client_id": secret.netatmo.client_id,
"client_secret": secret.netatmo.client_secret,
"username": secret.netatmo.username,
"password": secret.netatmo.password,
}
librato = require('librato-metrics').createClient({
email: secret.librato.email,
token: secret.librato.token,
})
data = {gauges: []}
api = new netatmo(auth);
all_calbacks_done = 0
getDevicelist = (err, devices, modules) ->
# console.log devices
# console.log modules
device_name = {}
device_thermostat = {}
device_end_time = {}
if devices.length > 0
console.log '####################### DEVICES #######################'
for device in devices
console.log '----------------------- Device '+device.station_name+'('+device._id+') -----------------------'
device_name[device._id]=norm(device.station_name)
device_end_time[device._id]=device.last_status_store
end_time = device.last_status_store
time_to_retrieve = 2*ten_min_sec
if device.type == 'NAMain'
console.log "Weather Station detected"
device_thermostat[device._id] = false
else
console.log "Thermostat detected"
time_to_retrieve = 2*one_hour_sec
device_thermostat[device._id] = true
device.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
if device.data_type != []
options = {
device_id: device._id,
scale: 'max',
type: device.data_type,
optimize: false,
date_begin: end_time - time_to_retrieve,
date_end: end_time
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
if typeof device.module_name == "undefined"
device.module_name = device.station_name
api.getMeasure options, getMeasure_maker(device_name[device._id],norm(device.module_name), device.data_type)
console.log '----------------------- End Device '+device.station_name+' -----------------------'
console.log '####################### END DEVICES #######################'
if modules.length > 0
console.log '####################### MODULES #######################'
for module in modules
console.log('----------------------- Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------')
time_to_retrieve = 2*ten_min_sec
if device_thermostat[module.main_device]
console.log "Thermostat module detected"
module.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
time_to_retrieve = 2*one_hour_sec
else
console.log "Weather module Station detected"
if module.data_type != []
options = {
device_id: module.main_device,
module_id: module._id
scale: 'max',
type: module.data_type,
optimize: false,
date_begin: device_end_time[module.main_device] - time_to_retrieve,
date_end: device_end_time[module.main_device]
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
api.getMeasure options, getMeasure_maker(device_name[module.main_device],norm(module.module_name), module.data_type)
console.log '----------------------- End Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------'
console.log '####################### END MODULES #######################'
getMeasure_maker = (device_name, module_name, data_type) ->
getMeasure = (err, measure) ->
all_calbacks_done -= 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
console.log '----------------------- Measure result for '+device_name+'.'+module_name+'['+data_type+'] -----------------------'
#console.log(measure)
if measure != []
for own epoch, measures of measure
#console.log epoch
for measurement, i in measures
data.gauges.push { name:'netatmo.'+device_name+'.'+module_name+'.'+data_type[i] , value: measurement, measure_time: epoch }
#console.log data
console.log '----------------------- End Measure result for '+device_name+'.'+module_name+' -----------------------'
if all_calbacks_done == 0
console.log '!!!!!!!!!!!!!!!!!!!!!!! All Callbacks done, processing datas !!!!!!!!!!!!!!!!!!!!!!!'
process_datas()
process_datas = () ->
console.log '####################### Processing datas #######################'
console.log data
librato.post('/metrics', data, (err, response) ->
if err
console.error "error detected"
console.error err
if err.errors != undefined
if err.errors.params != undefined
console.error err.errors.params
if err.errors.params.measure_time != undefined
console.error err.errors.params.measure_time
if response != undefined
console.log(response)
else
console.log "post to librato OK"
)
console.log '####################### End Processing datas #######################'
create_and_send = () ->
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// Starting process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
data = {gauges: []}
options = { app_type: 'app_station'}
api.getDevicelist(options, getDevicelist)
if i == 0
console.log 'processing thermostat'
options = { app_type: 'app_thermostat' }
api.getDevicelist(options, getDevicelist)
i += 1
if i == config.netatmo.thermostat_interval
i = 0 # Next time we retrieve datas from thermostat
console.log 'i: '+i
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// End process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
create_and_send()
setInterval () ->
create_and_send()
, config.netatmo.interval
| 125739 | #!/usr/bin/env coffee
require 'require-yaml'
require 'unorm'
xregexp = require('xregexp').XRegExp
netatmo = require('netatmo')
Parser = require('commandline-parser').Parser
parser = new Parser({
name : "netatmo_librato_daemon",
desc : 'a daemon which send data from netatmo to librato',
extra : 'see https://github.com/sdesbure/netatmo_librato'
})
parser.addArgument('secret' ,{
flags : ['s','secret'],
desc : "path to the secret file (defaulting to ./secret.yml)",
})
parser.addArgument('config' ,{
flags : ['c','config'],
desc : "path to the config file (defaulting to ./config.yml)",
})
secret_file = parser.get('secret')
if (!secret_file)
secret_file = './secret.yml'
config_file = parser.get('config')
if (!config_file)
config_file = './config.yml'
console.log("secret file used: " + secret_file)
console.log("config file used: " + config_file)
secret = require secret_file
config = require config_file
console.log config
root = exports ? this
ten_min_sec = 600
one_hour_sec = 3600
i = 0
norm = (string) ->
string.normalize("NFKD").replace(xregexp("\\p{M}", "g"), "").replace(new RegExp(" ", 'g'),"-")
auth = {
"client_id": secret.netatmo.client_id,
"client_secret": secret.netatmo.client_secret,
"username": secret.netatmo.username,
"password": <PASSWORD>,
}
librato = require('librato-metrics').createClient({
email: secret.librato.email,
token: secret.librato.token,
})
data = {gauges: []}
api = new netatmo(auth);
all_calbacks_done = 0
getDevicelist = (err, devices, modules) ->
# console.log devices
# console.log modules
device_name = {}
device_thermostat = {}
device_end_time = {}
if devices.length > 0
console.log '####################### DEVICES #######################'
for device in devices
console.log '----------------------- Device '+device.station_name+'('+device._id+') -----------------------'
device_name[device._id]=norm(device.station_name)
device_end_time[device._id]=device.last_status_store
end_time = device.last_status_store
time_to_retrieve = 2*ten_min_sec
if device.type == 'NAMain'
console.log "Weather Station detected"
device_thermostat[device._id] = false
else
console.log "Thermostat detected"
time_to_retrieve = 2*one_hour_sec
device_thermostat[device._id] = true
device.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
if device.data_type != []
options = {
device_id: device._id,
scale: 'max',
type: device.data_type,
optimize: false,
date_begin: end_time - time_to_retrieve,
date_end: end_time
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
if typeof device.module_name == "undefined"
device.module_name = device.station_name
api.getMeasure options, getMeasure_maker(device_name[device._id],norm(device.module_name), device.data_type)
console.log '----------------------- End Device '+device.station_name+' -----------------------'
console.log '####################### END DEVICES #######################'
if modules.length > 0
console.log '####################### MODULES #######################'
for module in modules
console.log('----------------------- Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------')
time_to_retrieve = 2*ten_min_sec
if device_thermostat[module.main_device]
console.log "Thermostat module detected"
module.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
time_to_retrieve = 2*one_hour_sec
else
console.log "Weather module Station detected"
if module.data_type != []
options = {
device_id: module.main_device,
module_id: module._id
scale: 'max',
type: module.data_type,
optimize: false,
date_begin: device_end_time[module.main_device] - time_to_retrieve,
date_end: device_end_time[module.main_device]
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
api.getMeasure options, getMeasure_maker(device_name[module.main_device],norm(module.module_name), module.data_type)
console.log '----------------------- End Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------'
console.log '####################### END MODULES #######################'
getMeasure_maker = (device_name, module_name, data_type) ->
getMeasure = (err, measure) ->
all_calbacks_done -= 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
console.log '----------------------- Measure result for '+device_name+'.'+module_name+'['+data_type+'] -----------------------'
#console.log(measure)
if measure != []
for own epoch, measures of measure
#console.log epoch
for measurement, i in measures
data.gauges.push { name:'netatmo.'+device_name+'.'+module_name+'.'+data_type[i] , value: measurement, measure_time: epoch }
#console.log data
console.log '----------------------- End Measure result for '+device_name+'.'+module_name+' -----------------------'
if all_calbacks_done == 0
console.log '!!!!!!!!!!!!!!!!!!!!!!! All Callbacks done, processing datas !!!!!!!!!!!!!!!!!!!!!!!'
process_datas()
process_datas = () ->
console.log '####################### Processing datas #######################'
console.log data
librato.post('/metrics', data, (err, response) ->
if err
console.error "error detected"
console.error err
if err.errors != undefined
if err.errors.params != undefined
console.error err.errors.params
if err.errors.params.measure_time != undefined
console.error err.errors.params.measure_time
if response != undefined
console.log(response)
else
console.log "post to librato OK"
)
console.log '####################### End Processing datas #######################'
create_and_send = () ->
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// Starting process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
data = {gauges: []}
options = { app_type: 'app_station'}
api.getDevicelist(options, getDevicelist)
if i == 0
console.log 'processing thermostat'
options = { app_type: 'app_thermostat' }
api.getDevicelist(options, getDevicelist)
i += 1
if i == config.netatmo.thermostat_interval
i = 0 # Next time we retrieve datas from thermostat
console.log 'i: '+i
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// End process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
create_and_send()
setInterval () ->
create_and_send()
, config.netatmo.interval
| true | #!/usr/bin/env coffee
require 'require-yaml'
require 'unorm'
xregexp = require('xregexp').XRegExp
netatmo = require('netatmo')
Parser = require('commandline-parser').Parser
parser = new Parser({
name : "netatmo_librato_daemon",
desc : 'a daemon which send data from netatmo to librato',
extra : 'see https://github.com/sdesbure/netatmo_librato'
})
parser.addArgument('secret' ,{
flags : ['s','secret'],
desc : "path to the secret file (defaulting to ./secret.yml)",
})
parser.addArgument('config' ,{
flags : ['c','config'],
desc : "path to the config file (defaulting to ./config.yml)",
})
secret_file = parser.get('secret')
if (!secret_file)
secret_file = './secret.yml'
config_file = parser.get('config')
if (!config_file)
config_file = './config.yml'
console.log("secret file used: " + secret_file)
console.log("config file used: " + config_file)
secret = require secret_file
config = require config_file
console.log config
root = exports ? this
ten_min_sec = 600
one_hour_sec = 3600
i = 0
norm = (string) ->
string.normalize("NFKD").replace(xregexp("\\p{M}", "g"), "").replace(new RegExp(" ", 'g'),"-")
auth = {
"client_id": secret.netatmo.client_id,
"client_secret": secret.netatmo.client_secret,
"username": secret.netatmo.username,
"password": PI:PASSWORD:<PASSWORD>END_PI,
}
librato = require('librato-metrics').createClient({
email: secret.librato.email,
token: secret.librato.token,
})
data = {gauges: []}
api = new netatmo(auth);
all_calbacks_done = 0
getDevicelist = (err, devices, modules) ->
# console.log devices
# console.log modules
device_name = {}
device_thermostat = {}
device_end_time = {}
if devices.length > 0
console.log '####################### DEVICES #######################'
for device in devices
console.log '----------------------- Device '+device.station_name+'('+device._id+') -----------------------'
device_name[device._id]=norm(device.station_name)
device_end_time[device._id]=device.last_status_store
end_time = device.last_status_store
time_to_retrieve = 2*ten_min_sec
if device.type == 'NAMain'
console.log "Weather Station detected"
device_thermostat[device._id] = false
else
console.log "Thermostat detected"
time_to_retrieve = 2*one_hour_sec
device_thermostat[device._id] = true
device.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
if device.data_type != []
options = {
device_id: device._id,
scale: 'max',
type: device.data_type,
optimize: false,
date_begin: end_time - time_to_retrieve,
date_end: end_time
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
if typeof device.module_name == "undefined"
device.module_name = device.station_name
api.getMeasure options, getMeasure_maker(device_name[device._id],norm(device.module_name), device.data_type)
console.log '----------------------- End Device '+device.station_name+' -----------------------'
console.log '####################### END DEVICES #######################'
if modules.length > 0
console.log '####################### MODULES #######################'
for module in modules
console.log('----------------------- Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------')
time_to_retrieve = 2*ten_min_sec
if device_thermostat[module.main_device]
console.log "Thermostat module detected"
module.data_type = ['Temperature', 'Sp_Temperature', 'BoilerOn', 'BoilerOff']
time_to_retrieve = 2*one_hour_sec
else
console.log "Weather module Station detected"
if module.data_type != []
options = {
device_id: module.main_device,
module_id: module._id
scale: 'max',
type: module.data_type,
optimize: false,
date_begin: device_end_time[module.main_device] - time_to_retrieve,
date_end: device_end_time[module.main_device]
}
#console.log options
console.log '####################### Measure #######################'
all_calbacks_done += 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
api.getMeasure options, getMeasure_maker(device_name[module.main_device],norm(module.module_name), module.data_type)
console.log '----------------------- End Module '+module.module_name+'(from device '+device_name[module.main_device]+') -----------------------'
console.log '####################### END MODULES #######################'
getMeasure_maker = (device_name, module_name, data_type) ->
getMeasure = (err, measure) ->
all_calbacks_done -= 1
console.log '!!!!!!!!!!!!!!!!!!!!!!! Nb of callbacks: '+all_calbacks_done
console.log '----------------------- Measure result for '+device_name+'.'+module_name+'['+data_type+'] -----------------------'
#console.log(measure)
if measure != []
for own epoch, measures of measure
#console.log epoch
for measurement, i in measures
data.gauges.push { name:'netatmo.'+device_name+'.'+module_name+'.'+data_type[i] , value: measurement, measure_time: epoch }
#console.log data
console.log '----------------------- End Measure result for '+device_name+'.'+module_name+' -----------------------'
if all_calbacks_done == 0
console.log '!!!!!!!!!!!!!!!!!!!!!!! All Callbacks done, processing datas !!!!!!!!!!!!!!!!!!!!!!!'
process_datas()
process_datas = () ->
console.log '####################### Processing datas #######################'
console.log data
librato.post('/metrics', data, (err, response) ->
if err
console.error "error detected"
console.error err
if err.errors != undefined
if err.errors.params != undefined
console.error err.errors.params
if err.errors.params.measure_time != undefined
console.error err.errors.params.measure_time
if response != undefined
console.log(response)
else
console.log "post to librato OK"
)
console.log '####################### End Processing datas #######################'
create_and_send = () ->
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// Starting process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
data = {gauges: []}
options = { app_type: 'app_station'}
api.getDevicelist(options, getDevicelist)
if i == 0
console.log 'processing thermostat'
options = { app_type: 'app_thermostat' }
api.getDevicelist(options, getDevicelist)
i += 1
if i == config.netatmo.thermostat_interval
i = 0 # Next time we retrieve datas from thermostat
console.log 'i: '+i
date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log '/////////////////////// End process at '+date+'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
create_and_send()
setInterval () ->
create_and_send()
, config.netatmo.interval
|
[
{
"context": " #\n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) #\n# ",
"end": 914,
"score": 0.9998069405555725,
"start": 904,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/views/_base/Layout.coffee | wrml/wrml | 47 | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
class Views.Layout extends Marionette.Layout | 206949 | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
class Views.Layout extends Marionette.Layout | true | ###############################################################################
# #
# WRML - Web Resource Modeling Language #
# __ __ ______ __ __ __ #
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ #
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ #
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ #
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ #
# #
# http://www.wrml.org #
# #
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org) #
# #
# 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. #
# #
###############################################################################
# CoffeeScript
@Wrmldoc.module "Views", (Views, App, Backbone, Marionette, $, _) ->
class Views.Layout extends Marionette.Layout |
[
{
"context": "cribe 'password', ->\n user.password = 'a'\n \n it 'has 64 bytes', ->\n ",
"end": 377,
"score": 0.9939361214637756,
"start": 376,
"tag": "PASSWORD",
"value": "a"
}
] | test/models/user.coffee | cncolder/vcvs | 0 | { assert, cwd } = require '../helper'
{ User } = require "#{cwd}/models"
describe User.modelName, ->
after (callback) ->
User.remove {}, callback
it 'has locals', ->
assert typeof User.locals is 'object'
describe 'new', ->
user = new User
name: 'foo'
describe 'password', ->
user.password = 'a'
it 'has 64 bytes', ->
assert.equal user.password.length, 64
describe 'email test@test', ->
user.email = 'test@test'
it 'is valid', (callback) ->
user.validate callback
describe 'login', ->
before (callback) ->
user.login
ip: '0.0.0.0'
callback
it 'has one activity', ->
assert.equal user.activities.length, 1
describe 'Save an user without name', ->
it 'raise validation error', (callback) ->
new User().save ({ name, errors }) ->
assert name is 'ValidationError'
assert errors.name
assert errors.email
callback()
| 138553 | { assert, cwd } = require '../helper'
{ User } = require "#{cwd}/models"
describe User.modelName, ->
after (callback) ->
User.remove {}, callback
it 'has locals', ->
assert typeof User.locals is 'object'
describe 'new', ->
user = new User
name: 'foo'
describe 'password', ->
user.password = '<PASSWORD>'
it 'has 64 bytes', ->
assert.equal user.password.length, 64
describe 'email test@test', ->
user.email = 'test@test'
it 'is valid', (callback) ->
user.validate callback
describe 'login', ->
before (callback) ->
user.login
ip: '0.0.0.0'
callback
it 'has one activity', ->
assert.equal user.activities.length, 1
describe 'Save an user without name', ->
it 'raise validation error', (callback) ->
new User().save ({ name, errors }) ->
assert name is 'ValidationError'
assert errors.name
assert errors.email
callback()
| true | { assert, cwd } = require '../helper'
{ User } = require "#{cwd}/models"
describe User.modelName, ->
after (callback) ->
User.remove {}, callback
it 'has locals', ->
assert typeof User.locals is 'object'
describe 'new', ->
user = new User
name: 'foo'
describe 'password', ->
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
it 'has 64 bytes', ->
assert.equal user.password.length, 64
describe 'email test@test', ->
user.email = 'test@test'
it 'is valid', (callback) ->
user.validate callback
describe 'login', ->
before (callback) ->
user.login
ip: '0.0.0.0'
callback
it 'has one activity', ->
assert.equal user.activities.length, 1
describe 'Save an user without name', ->
it 'raise validation error', (callback) ->
new User().save ({ name, errors }) ->
assert name is 'ValidationError'
assert errors.name
assert errors.email
callback()
|
[
{
"context": "###\nPDFImage - embeds images in PDF documents\nBy Devon Govett\n###\n\nfs = require 'fs'\nData = require './data'\nJP",
"end": 61,
"score": 0.9998637437820435,
"start": 49,
"tag": "NAME",
"value": "Devon Govett"
}
] | lib/image.coffee | iplabs/pdfkit | 0 | ###
PDFImage - embeds images in PDF documents
By Devon Govett
###
fs = require 'fs'
Data = require './data'
JPEG = require './image/jpeg'
PNG = require './image/png'
toBuffer = (src) ->
if Buffer.isBuffer(src)
src
else if src instanceof ArrayBuffer
new Buffer(new Uint8Array(src))
else if match = /^data:.+;base64,(.*)$/.exec(src)
new Buffer(match[1], 'base64')
else
fs.readFileSync src
class PDFImage
@open: (src, label, alphaSrc) ->
data = toBuffer src
if alphaSrc
alphaData = toBuffer alphaSrc
if not JPEG.is alphaData
throw Error 'Alpha mask must be a gray JPEG image'
alpha = new JPEG alphaData
if alpha.colorSpace != 'DeviceGray'
throw Error 'Alpha mask must be a gray JPEG image'
if data
if JPEG.is(data)
return new JPEG(data, label, alpha)
else if PNG.is(data)
return new PNG(data, label, alpha)
else
throw new Error 'Unknown image format.'
module.exports = PDFImage
| 220456 | ###
PDFImage - embeds images in PDF documents
By <NAME>
###
fs = require 'fs'
Data = require './data'
JPEG = require './image/jpeg'
PNG = require './image/png'
toBuffer = (src) ->
if Buffer.isBuffer(src)
src
else if src instanceof ArrayBuffer
new Buffer(new Uint8Array(src))
else if match = /^data:.+;base64,(.*)$/.exec(src)
new Buffer(match[1], 'base64')
else
fs.readFileSync src
class PDFImage
@open: (src, label, alphaSrc) ->
data = toBuffer src
if alphaSrc
alphaData = toBuffer alphaSrc
if not JPEG.is alphaData
throw Error 'Alpha mask must be a gray JPEG image'
alpha = new JPEG alphaData
if alpha.colorSpace != 'DeviceGray'
throw Error 'Alpha mask must be a gray JPEG image'
if data
if JPEG.is(data)
return new JPEG(data, label, alpha)
else if PNG.is(data)
return new PNG(data, label, alpha)
else
throw new Error 'Unknown image format.'
module.exports = PDFImage
| true | ###
PDFImage - embeds images in PDF documents
By PI:NAME:<NAME>END_PI
###
fs = require 'fs'
Data = require './data'
JPEG = require './image/jpeg'
PNG = require './image/png'
toBuffer = (src) ->
if Buffer.isBuffer(src)
src
else if src instanceof ArrayBuffer
new Buffer(new Uint8Array(src))
else if match = /^data:.+;base64,(.*)$/.exec(src)
new Buffer(match[1], 'base64')
else
fs.readFileSync src
class PDFImage
@open: (src, label, alphaSrc) ->
data = toBuffer src
if alphaSrc
alphaData = toBuffer alphaSrc
if not JPEG.is alphaData
throw Error 'Alpha mask must be a gray JPEG image'
alpha = new JPEG alphaData
if alpha.colorSpace != 'DeviceGray'
throw Error 'Alpha mask must be a gray JPEG image'
if data
if JPEG.is(data)
return new JPEG(data, label, alpha)
else if PNG.is(data)
return new PNG(data, label, alpha)
else
throw new Error 'Unknown image format.'
module.exports = PDFImage
|
[
{
"context": "tehFiajdgTsyF5JN8',\n # producerName: 'Mike Shaw',\n # producerNumber: 2,\n # ",
"end": 1112,
"score": 0.9997290968894958,
"start": 1103,
"tag": "NAME",
"value": "Mike Shaw"
},
{
"context": "KBDvra4z9F3iWea4Q',\n # customerN... | server/emails/confirmOrder.coffee | redhead-web/meteor-foodcoop | 11 | import moment from 'moment'
Meteor.methods
confirmOrder: (items, order)->
user = Meteor.users.findOne(order.user)
invoiceNumber = Random.id(6)
dataObject =
order: order
customerNumber: user.profile.customerNumber
items: items
recipient: user.profile.name
number: invoiceNumber
date: moment().format('dddd, MMMM Do YYYY')
# if order.deliveryDay #must have been from POS
# Mailer.send
# to: "#{user.profile.name} <#{user.emails[0].address}>"
# subject: "Receipt: Whangarei Food Co-op #{invoiceNumber}"
# template: "orderReceiptPOS"
# data: dataObject
# else
dataObject.items = _.map (_.groupBy items, 'deliveryDay'), (sales, deliveryDay) ->
deliveryDay: deliveryDay,
sales: sales
console.log dataObject.items
# [ [ 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)', [ [Object] ] ] ]
# { 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)':
# [ { productId: 'sWxb8n8rQaGXXkmEp',
# qty: 1,
# producerId: 'tehFiajdgTsyF5JN8',
# producerName: 'Mike Shaw',
# producerNumber: 2,
# price: 4.55,
# productName: 'A grade Carrots',
# packagingDescription: null,
# packagingRefund: 0,
# unitOfMeasure: '250g',
# orderId: 'BxAkdhWgKeH9uWMNd',
# deliveryDay: Tue Aug 09 2016 00:00:00 GMT+1200 (NZST),
# customerId: 'KBDvra4z9F3iWea4Q',
# customerName: 'Sean and Rowan Stanley',
# customerNumber: 1,
# extraMarkup: null,
# daysNotice: 7,
# dateCreated: Wed Jul 27 2016 10:18:58 GMT+1200 (NZST),
# status: 'undelivered' } ] }
#[{deliveryDay: Date, sales: [array]}]
Mailer.send
to: "#{user.profile.name} <#{user.emails[0].address}>"
subject: "Whangarei Food Co-op Order Confirmation #{invoiceNumber}"
template: "confirmOrderEmail"
data: dataObject
| 163021 | import moment from 'moment'
Meteor.methods
confirmOrder: (items, order)->
user = Meteor.users.findOne(order.user)
invoiceNumber = Random.id(6)
dataObject =
order: order
customerNumber: user.profile.customerNumber
items: items
recipient: user.profile.name
number: invoiceNumber
date: moment().format('dddd, MMMM Do YYYY')
# if order.deliveryDay #must have been from POS
# Mailer.send
# to: "#{user.profile.name} <#{user.emails[0].address}>"
# subject: "Receipt: Whangarei Food Co-op #{invoiceNumber}"
# template: "orderReceiptPOS"
# data: dataObject
# else
dataObject.items = _.map (_.groupBy items, 'deliveryDay'), (sales, deliveryDay) ->
deliveryDay: deliveryDay,
sales: sales
console.log dataObject.items
# [ [ 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)', [ [Object] ] ] ]
# { 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)':
# [ { productId: 'sWxb8n8rQaGXXkmEp',
# qty: 1,
# producerId: 'tehFiajdgTsyF5JN8',
# producerName: '<NAME>',
# producerNumber: 2,
# price: 4.55,
# productName: 'A grade Carrots',
# packagingDescription: null,
# packagingRefund: 0,
# unitOfMeasure: '250g',
# orderId: 'BxAkdhWgKeH9uWMNd',
# deliveryDay: Tue Aug 09 2016 00:00:00 GMT+1200 (NZST),
# customerId: 'KBDvra4z9F3iWea4Q',
# customerName: '<NAME> <NAME>',
# customerNumber: 1,
# extraMarkup: null,
# daysNotice: 7,
# dateCreated: Wed Jul 27 2016 10:18:58 GMT+1200 (NZST),
# status: 'undelivered' } ] }
#[{deliveryDay: Date, sales: [array]}]
Mailer.send
to: "#{user.profile.name} <#{user.emails[0].address}>"
subject: "Whangarei Food Co-op Order Confirmation #{invoiceNumber}"
template: "confirmOrderEmail"
data: dataObject
| true | import moment from 'moment'
Meteor.methods
confirmOrder: (items, order)->
user = Meteor.users.findOne(order.user)
invoiceNumber = Random.id(6)
dataObject =
order: order
customerNumber: user.profile.customerNumber
items: items
recipient: user.profile.name
number: invoiceNumber
date: moment().format('dddd, MMMM Do YYYY')
# if order.deliveryDay #must have been from POS
# Mailer.send
# to: "#{user.profile.name} <#{user.emails[0].address}>"
# subject: "Receipt: Whangarei Food Co-op #{invoiceNumber}"
# template: "orderReceiptPOS"
# data: dataObject
# else
dataObject.items = _.map (_.groupBy items, 'deliveryDay'), (sales, deliveryDay) ->
deliveryDay: deliveryDay,
sales: sales
console.log dataObject.items
# [ [ 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)', [ [Object] ] ] ]
# { 'Tue Aug 09 2016 00:00:00 GMT+1200 (NZST)':
# [ { productId: 'sWxb8n8rQaGXXkmEp',
# qty: 1,
# producerId: 'tehFiajdgTsyF5JN8',
# producerName: 'PI:NAME:<NAME>END_PI',
# producerNumber: 2,
# price: 4.55,
# productName: 'A grade Carrots',
# packagingDescription: null,
# packagingRefund: 0,
# unitOfMeasure: '250g',
# orderId: 'BxAkdhWgKeH9uWMNd',
# deliveryDay: Tue Aug 09 2016 00:00:00 GMT+1200 (NZST),
# customerId: 'KBDvra4z9F3iWea4Q',
# customerName: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI',
# customerNumber: 1,
# extraMarkup: null,
# daysNotice: 7,
# dateCreated: Wed Jul 27 2016 10:18:58 GMT+1200 (NZST),
# status: 'undelivered' } ] }
#[{deliveryDay: Date, sales: [array]}]
Mailer.send
to: "#{user.profile.name} <#{user.emails[0].address}>"
subject: "Whangarei Food Co-op Order Confirmation #{invoiceNumber}"
template: "confirmOrderEmail"
data: dataObject
|
[
{
"context": "\n ###\n connect: ->\n ws = new WebSocket 'ws://64.19.78.244:443/'\n ws.on 'message', (message) ->\n\n if",
"end": 348,
"score": 0.9995786547660828,
"start": 336,
"tag": "IP_ADDRESS",
"value": "64.19.78.244"
}
] | GOTHAM/Backend/src/Objects/World/Components/IPViking.coffee | perara/gotham | 0 | WebSocket = require 'ws'
###*
# IPViking is a attackmap with good traffic flow. FrOM TO location with Port and service information
# @class IPViking
# @module Backend
# @submodule Backend.World
###
class IPViking
constructor: ->
###*
# connect to the stream
# @method connect
###
connect: ->
ws = new WebSocket 'ws://64.19.78.244:443/'
ws.on 'message', (message) ->
if parseInt(message.latitude) == 0 or parseInt(message.longitude) == 0 or parseInt(message.latitude2) == 0 or parseInt(message.longitude2) == 0
return
for key, client of Gotham.SocketServer.getClients()
# Relays IPViking to all clients
client.Socket.emit 'IPViking_Attack', message
module.exports = IPViking | 190117 | WebSocket = require 'ws'
###*
# IPViking is a attackmap with good traffic flow. FrOM TO location with Port and service information
# @class IPViking
# @module Backend
# @submodule Backend.World
###
class IPViking
constructor: ->
###*
# connect to the stream
# @method connect
###
connect: ->
ws = new WebSocket 'ws://192.168.3.11:443/'
ws.on 'message', (message) ->
if parseInt(message.latitude) == 0 or parseInt(message.longitude) == 0 or parseInt(message.latitude2) == 0 or parseInt(message.longitude2) == 0
return
for key, client of Gotham.SocketServer.getClients()
# Relays IPViking to all clients
client.Socket.emit 'IPViking_Attack', message
module.exports = IPViking | true | WebSocket = require 'ws'
###*
# IPViking is a attackmap with good traffic flow. FrOM TO location with Port and service information
# @class IPViking
# @module Backend
# @submodule Backend.World
###
class IPViking
constructor: ->
###*
# connect to the stream
# @method connect
###
connect: ->
ws = new WebSocket 'ws://PI:IP_ADDRESS:192.168.3.11END_PI:443/'
ws.on 'message', (message) ->
if parseInt(message.latitude) == 0 or parseInt(message.longitude) == 0 or parseInt(message.latitude2) == 0 or parseInt(message.longitude2) == 0
return
for key, client of Gotham.SocketServer.getClients()
# Relays IPViking to all clients
client.Socket.emit 'IPViking_Attack', message
module.exports = IPViking |
[
{
"context": "o' />, ' 花式晒人']\n description: '晒人用插件'\n author: 'Jennings Wu.'\n link: 'https://github.com/JenningsWu'\n versi",
"end": 1032,
"score": 0.9998831748962402,
"start": 1021,
"tag": "NAME",
"value": "Jennings Wu"
},
{
"context": "uthor: 'Jennings Wu.'\n link: 'https://... | index.cjsx | yudachi/plugin-sunshine | 0 | remote = require 'remote'
windowManager = remote.require './lib/window'
path = require 'path-extra'
# i18n configure
i18n = new (require 'i18n-2')
locales: ['en-US', 'ja-JP', 'zh-CN', 'zh-TW'],
defaultLocale: 'zh-CN',
directory: path.join(__dirname, 'asset', 'i18n'),
updateFiles: false,
indent: '\t',
extension: '.json',
devMode: false
i18n.setLocale(window.language)
__ = i18n.__.bind(i18n)
window.sunshineWindow = null
initialSunshineWindow = ->
window.sunshineWindow = windowManager.createWindow
x: config.get 'poi.window.x', 0
y: config.get 'poi.window.y', 0
width: 820
height: 650
realClose: true
window.sunshineWindow.loadUrl "file://#{__dirname}/index.html"
# if process.env.DEBUG?
# window.sunshineWindow.openDevTools
# detach: true
# if config.get('plugin.Sunshine.enable', true)
# initialSunshineWindow()
module.exports =
name: 'Sunshine'
priority: 100
displayName: [<FontAwesome key={0} name='sun-o' />, ' 花式晒人']
description: '晒人用插件'
author: 'Jennings Wu.'
link: 'https://github.com/JenningsWu'
version: '0.0.1'
handleClick: ->
# window.sunshineWindow.show()
initialSunshineWindow()
window.sunshineWindow.openDevTools
detach: true
window.sunshineWindow.show()
| 52463 | remote = require 'remote'
windowManager = remote.require './lib/window'
path = require 'path-extra'
# i18n configure
i18n = new (require 'i18n-2')
locales: ['en-US', 'ja-JP', 'zh-CN', 'zh-TW'],
defaultLocale: 'zh-CN',
directory: path.join(__dirname, 'asset', 'i18n'),
updateFiles: false,
indent: '\t',
extension: '.json',
devMode: false
i18n.setLocale(window.language)
__ = i18n.__.bind(i18n)
window.sunshineWindow = null
initialSunshineWindow = ->
window.sunshineWindow = windowManager.createWindow
x: config.get 'poi.window.x', 0
y: config.get 'poi.window.y', 0
width: 820
height: 650
realClose: true
window.sunshineWindow.loadUrl "file://#{__dirname}/index.html"
# if process.env.DEBUG?
# window.sunshineWindow.openDevTools
# detach: true
# if config.get('plugin.Sunshine.enable', true)
# initialSunshineWindow()
module.exports =
name: 'Sunshine'
priority: 100
displayName: [<FontAwesome key={0} name='sun-o' />, ' 花式晒人']
description: '晒人用插件'
author: '<NAME>.'
link: 'https://github.com/JenningsWu'
version: '0.0.1'
handleClick: ->
# window.sunshineWindow.show()
initialSunshineWindow()
window.sunshineWindow.openDevTools
detach: true
window.sunshineWindow.show()
| true | remote = require 'remote'
windowManager = remote.require './lib/window'
path = require 'path-extra'
# i18n configure
i18n = new (require 'i18n-2')
locales: ['en-US', 'ja-JP', 'zh-CN', 'zh-TW'],
defaultLocale: 'zh-CN',
directory: path.join(__dirname, 'asset', 'i18n'),
updateFiles: false,
indent: '\t',
extension: '.json',
devMode: false
i18n.setLocale(window.language)
__ = i18n.__.bind(i18n)
window.sunshineWindow = null
initialSunshineWindow = ->
window.sunshineWindow = windowManager.createWindow
x: config.get 'poi.window.x', 0
y: config.get 'poi.window.y', 0
width: 820
height: 650
realClose: true
window.sunshineWindow.loadUrl "file://#{__dirname}/index.html"
# if process.env.DEBUG?
# window.sunshineWindow.openDevTools
# detach: true
# if config.get('plugin.Sunshine.enable', true)
# initialSunshineWindow()
module.exports =
name: 'Sunshine'
priority: 100
displayName: [<FontAwesome key={0} name='sun-o' />, ' 花式晒人']
description: '晒人用插件'
author: 'PI:NAME:<NAME>END_PI.'
link: 'https://github.com/JenningsWu'
version: '0.0.1'
handleClick: ->
# window.sunshineWindow.show()
initialSunshineWindow()
window.sunshineWindow.openDevTools
detach: true
window.sunshineWindow.show()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9995579123497009,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-writedouble.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.
#
# * Tests to verify we're writing doubles correctly
#
test = (clazz) ->
buffer = new clazz(16)
buffer.writeDoubleBE 2.225073858507201e-308, 0
buffer.writeDoubleLE 2.225073858507201e-308, 8
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x0f, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0x0f, buffer[14]
ASSERT.equal 0x00, buffer[15]
buffer.writeDoubleBE 1.0000000000000004, 0
buffer.writeDoubleLE 1.0000000000000004, 8
ASSERT.equal 0x3f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x02, buffer[7]
ASSERT.equal 0x02, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x3f, buffer[15]
buffer.writeDoubleBE -2, 0
buffer.writeDoubleLE -2, 8
ASSERT.equal 0xc0, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0xc0, buffer[15]
buffer.writeDoubleBE 1.7976931348623157e+308, 0
buffer.writeDoubleLE 1.7976931348623157e+308, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xef, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0xef, buffer[14]
ASSERT.equal 0x7f, buffer[15]
buffer.writeDoubleBE 0 * -1, 0
buffer.writeDoubleLE 0 * -1, 8
ASSERT.equal 0x80, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0x80, buffer[15]
buffer.writeDoubleBE Infinity, 0
buffer.writeDoubleLE Infinity, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x7f, buffer[15]
ASSERT.equal Infinity, buffer.readDoubleBE(0)
ASSERT.equal Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE -Infinity, 0
buffer.writeDoubleLE -Infinity, 8
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0xff, buffer[15]
ASSERT.equal -Infinity, buffer.readDoubleBE(0)
ASSERT.equal -Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE NaN, 0
buffer.writeDoubleLE NaN, 8
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[0] or 0xff is buffer[0]
# mips processors use a slightly different NaN
ASSERT 0xf8 is buffer[1] or 0xf7 is buffer[1]
ASSERT 0x00 is buffer[2] or 0xff is buffer[2]
ASSERT 0x00 is buffer[3] or 0xff is buffer[3]
ASSERT 0x00 is buffer[4] or 0xff is buffer[4]
ASSERT 0x00 is buffer[5] or 0xff is buffer[5]
ASSERT 0x00 is buffer[6] or 0xff is buffer[6]
ASSERT 0x00 is buffer[7] or 0xff is buffer[7]
ASSERT 0x00 is buffer[8] or 0xff is buffer[8]
ASSERT 0x00 is buffer[9] or 0xff is buffer[9]
ASSERT 0x00 is buffer[10] or 0xff is buffer[10]
ASSERT 0x00 is buffer[11] or 0xff is buffer[11]
ASSERT 0x00 is buffer[12] or 0xff is buffer[12]
ASSERT 0x00 is buffer[13] or 0xff is buffer[13]
ASSERT 0xf8 is buffer[14] or 0xf7 is buffer[14]
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[15] or 0xff is buffer[15]
ASSERT.ok isNaN(buffer.readDoubleBE(0))
ASSERT.ok isNaN(buffer.readDoubleLE(8))
return
common = require("../common")
ASSERT = require("assert")
test Buffer
| 150828 | # 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.
#
# * Tests to verify we're writing doubles correctly
#
test = (clazz) ->
buffer = new clazz(16)
buffer.writeDoubleBE 2.225073858507201e-308, 0
buffer.writeDoubleLE 2.225073858507201e-308, 8
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x0f, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0x0f, buffer[14]
ASSERT.equal 0x00, buffer[15]
buffer.writeDoubleBE 1.0000000000000004, 0
buffer.writeDoubleLE 1.0000000000000004, 8
ASSERT.equal 0x3f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x02, buffer[7]
ASSERT.equal 0x02, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x3f, buffer[15]
buffer.writeDoubleBE -2, 0
buffer.writeDoubleLE -2, 8
ASSERT.equal 0xc0, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0xc0, buffer[15]
buffer.writeDoubleBE 1.7976931348623157e+308, 0
buffer.writeDoubleLE 1.7976931348623157e+308, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xef, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0xef, buffer[14]
ASSERT.equal 0x7f, buffer[15]
buffer.writeDoubleBE 0 * -1, 0
buffer.writeDoubleLE 0 * -1, 8
ASSERT.equal 0x80, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0x80, buffer[15]
buffer.writeDoubleBE Infinity, 0
buffer.writeDoubleLE Infinity, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x7f, buffer[15]
ASSERT.equal Infinity, buffer.readDoubleBE(0)
ASSERT.equal Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE -Infinity, 0
buffer.writeDoubleLE -Infinity, 8
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0xff, buffer[15]
ASSERT.equal -Infinity, buffer.readDoubleBE(0)
ASSERT.equal -Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE NaN, 0
buffer.writeDoubleLE NaN, 8
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[0] or 0xff is buffer[0]
# mips processors use a slightly different NaN
ASSERT 0xf8 is buffer[1] or 0xf7 is buffer[1]
ASSERT 0x00 is buffer[2] or 0xff is buffer[2]
ASSERT 0x00 is buffer[3] or 0xff is buffer[3]
ASSERT 0x00 is buffer[4] or 0xff is buffer[4]
ASSERT 0x00 is buffer[5] or 0xff is buffer[5]
ASSERT 0x00 is buffer[6] or 0xff is buffer[6]
ASSERT 0x00 is buffer[7] or 0xff is buffer[7]
ASSERT 0x00 is buffer[8] or 0xff is buffer[8]
ASSERT 0x00 is buffer[9] or 0xff is buffer[9]
ASSERT 0x00 is buffer[10] or 0xff is buffer[10]
ASSERT 0x00 is buffer[11] or 0xff is buffer[11]
ASSERT 0x00 is buffer[12] or 0xff is buffer[12]
ASSERT 0x00 is buffer[13] or 0xff is buffer[13]
ASSERT 0xf8 is buffer[14] or 0xf7 is buffer[14]
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[15] or 0xff is buffer[15]
ASSERT.ok isNaN(buffer.readDoubleBE(0))
ASSERT.ok isNaN(buffer.readDoubleLE(8))
return
common = require("../common")
ASSERT = require("assert")
test Buffer
| 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.
#
# * Tests to verify we're writing doubles correctly
#
test = (clazz) ->
buffer = new clazz(16)
buffer.writeDoubleBE 2.225073858507201e-308, 0
buffer.writeDoubleLE 2.225073858507201e-308, 8
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x0f, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0x0f, buffer[14]
ASSERT.equal 0x00, buffer[15]
buffer.writeDoubleBE 1.0000000000000004, 0
buffer.writeDoubleLE 1.0000000000000004, 8
ASSERT.equal 0x3f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x02, buffer[7]
ASSERT.equal 0x02, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x3f, buffer[15]
buffer.writeDoubleBE -2, 0
buffer.writeDoubleLE -2, 8
ASSERT.equal 0xc0, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0xc0, buffer[15]
buffer.writeDoubleBE 1.7976931348623157e+308, 0
buffer.writeDoubleLE 1.7976931348623157e+308, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xef, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0xff, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
ASSERT.equal 0xff, buffer[8]
ASSERT.equal 0xff, buffer[9]
ASSERT.equal 0xff, buffer[10]
ASSERT.equal 0xff, buffer[11]
ASSERT.equal 0xff, buffer[12]
ASSERT.equal 0xff, buffer[13]
ASSERT.equal 0xef, buffer[14]
ASSERT.equal 0x7f, buffer[15]
buffer.writeDoubleBE 0 * -1, 0
buffer.writeDoubleLE 0 * -1, 8
ASSERT.equal 0x80, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0x00, buffer[14]
ASSERT.equal 0x80, buffer[15]
buffer.writeDoubleBE Infinity, 0
buffer.writeDoubleLE Infinity, 8
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0x7f, buffer[15]
ASSERT.equal Infinity, buffer.readDoubleBE(0)
ASSERT.equal Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE -Infinity, 0
buffer.writeDoubleLE -Infinity, 8
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xf0, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.equal 0x00, buffer[8]
ASSERT.equal 0x00, buffer[9]
ASSERT.equal 0x00, buffer[10]
ASSERT.equal 0x00, buffer[11]
ASSERT.equal 0x00, buffer[12]
ASSERT.equal 0x00, buffer[13]
ASSERT.equal 0xf0, buffer[14]
ASSERT.equal 0xff, buffer[15]
ASSERT.equal -Infinity, buffer.readDoubleBE(0)
ASSERT.equal -Infinity, buffer.readDoubleLE(8)
buffer.writeDoubleBE NaN, 0
buffer.writeDoubleLE NaN, 8
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[0] or 0xff is buffer[0]
# mips processors use a slightly different NaN
ASSERT 0xf8 is buffer[1] or 0xf7 is buffer[1]
ASSERT 0x00 is buffer[2] or 0xff is buffer[2]
ASSERT 0x00 is buffer[3] or 0xff is buffer[3]
ASSERT 0x00 is buffer[4] or 0xff is buffer[4]
ASSERT 0x00 is buffer[5] or 0xff is buffer[5]
ASSERT 0x00 is buffer[6] or 0xff is buffer[6]
ASSERT 0x00 is buffer[7] or 0xff is buffer[7]
ASSERT 0x00 is buffer[8] or 0xff is buffer[8]
ASSERT 0x00 is buffer[9] or 0xff is buffer[9]
ASSERT 0x00 is buffer[10] or 0xff is buffer[10]
ASSERT 0x00 is buffer[11] or 0xff is buffer[11]
ASSERT 0x00 is buffer[12] or 0xff is buffer[12]
ASSERT 0x00 is buffer[13] or 0xff is buffer[13]
ASSERT 0xf8 is buffer[14] or 0xf7 is buffer[14]
# Darwin ia32 does the other kind of NaN.
# Compiler bug. No one really cares.
ASSERT 0x7f is buffer[15] or 0xff is buffer[15]
ASSERT.ok isNaN(buffer.readDoubleBE(0))
ASSERT.ok isNaN(buffer.readDoubleLE(8))
return
common = require("../common")
ASSERT = require("assert")
test Buffer
|
[
{
"context": "ccount secure)\n#\n# developed by http://github.com/vquaiato - Crafters Software Studio\n\nrequire('date-utils')",
"end": 490,
"score": 0.9697181582450867,
"start": 482,
"tag": "USERNAME",
"value": "vquaiato"
},
{
"context": " msg.send \"[#{d} -> #{c.commit.com... | src/scripts/github-activity.coffee | skanev/hubot-scripts | 1 | # it was based on github-issues.coffee script
#
# add "date-utils":">=1.2.5" in the hubot-scripts.json file
#
# add HUBOT_GITHUB_USER to your heroku env
# the HUBOT_GITHUB_USER should map to your account, not the bot account
# the HUBOT_BOT_GITHUB_USER should map to the bot github username
# the HUBOT_BOT_GITHUB_PASS should map to the bot github password
# (you do not need to create a bot github account, but doing keeps your account secure)
#
# developed by http://github.com/vquaiato - Crafters Software Studio
require('date-utils')
module.exports = (robot) ->
robot.hear /^repo show (.*)$/i, (msg) ->
repo = msg.match[1].toLowerCase()
repo = "#{process.env.HUBOT_GITHUB_USER}/#{repo}" unless repo.indexOf("/") > -1
bot_github_user = process.env.HUBOT_BOT_GITHUB_USER
bot_github_pass = process.env.HUBOT_BOT_GITHUB_PASS
auth = new Buffer("#{bot_github_user}:#{bot_github_pass}").toString('base64')
url = "https://api.github.com/repos/#{repo}/commits"
msg.http(url)
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "GitHub says: #{err}"
return
commits = JSON.parse(body)
if commits.message
msg.send "Achievement unlocked: [NEEDLE IN A HAYSTACK] repository #{commits.message}!"
else if commits.length == 0
msg.send "Achievement unlocked: [LIKE A BOSS] no commits found!"
else
msg.send "http://github.com/#{repo}"
send = 5
for c in commits
if send
d = new Date(Date.parse(c.commit.committer.date)).toFormat("DD/MM HH24:MI")
msg.send "[#{d} -> #{c.commit.committer.name}] #{c.commit.message}"
send -= 1 | 113241 | # it was based on github-issues.coffee script
#
# add "date-utils":">=1.2.5" in the hubot-scripts.json file
#
# add HUBOT_GITHUB_USER to your heroku env
# the HUBOT_GITHUB_USER should map to your account, not the bot account
# the HUBOT_BOT_GITHUB_USER should map to the bot github username
# the HUBOT_BOT_GITHUB_PASS should map to the bot github password
# (you do not need to create a bot github account, but doing keeps your account secure)
#
# developed by http://github.com/vquaiato - Crafters Software Studio
require('date-utils')
module.exports = (robot) ->
robot.hear /^repo show (.*)$/i, (msg) ->
repo = msg.match[1].toLowerCase()
repo = "#{process.env.HUBOT_GITHUB_USER}/#{repo}" unless repo.indexOf("/") > -1
bot_github_user = process.env.HUBOT_BOT_GITHUB_USER
bot_github_pass = process.env.HUBOT_BOT_GITHUB_PASS
auth = new Buffer("#{bot_github_user}:#{bot_github_pass}").toString('base64')
url = "https://api.github.com/repos/#{repo}/commits"
msg.http(url)
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "GitHub says: #{err}"
return
commits = JSON.parse(body)
if commits.message
msg.send "Achievement unlocked: [NEEDLE IN A HAYSTACK] repository #{commits.message}!"
else if commits.length == 0
msg.send "Achievement unlocked: [LIKE A BOSS] no commits found!"
else
msg.send "http://github.com/#{repo}"
send = 5
for c in commits
if send
d = new Date(Date.parse(c.commit.committer.date)).toFormat("DD/MM HH24:MI")
msg.send "[#{d} -> #{c.commit.committer.<NAME>}] #{c.commit.message}"
send -= 1 | true | # it was based on github-issues.coffee script
#
# add "date-utils":">=1.2.5" in the hubot-scripts.json file
#
# add HUBOT_GITHUB_USER to your heroku env
# the HUBOT_GITHUB_USER should map to your account, not the bot account
# the HUBOT_BOT_GITHUB_USER should map to the bot github username
# the HUBOT_BOT_GITHUB_PASS should map to the bot github password
# (you do not need to create a bot github account, but doing keeps your account secure)
#
# developed by http://github.com/vquaiato - Crafters Software Studio
require('date-utils')
module.exports = (robot) ->
robot.hear /^repo show (.*)$/i, (msg) ->
repo = msg.match[1].toLowerCase()
repo = "#{process.env.HUBOT_GITHUB_USER}/#{repo}" unless repo.indexOf("/") > -1
bot_github_user = process.env.HUBOT_BOT_GITHUB_USER
bot_github_pass = process.env.HUBOT_BOT_GITHUB_PASS
auth = new Buffer("#{bot_github_user}:#{bot_github_pass}").toString('base64')
url = "https://api.github.com/repos/#{repo}/commits"
msg.http(url)
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "GitHub says: #{err}"
return
commits = JSON.parse(body)
if commits.message
msg.send "Achievement unlocked: [NEEDLE IN A HAYSTACK] repository #{commits.message}!"
else if commits.length == 0
msg.send "Achievement unlocked: [LIKE A BOSS] no commits found!"
else
msg.send "http://github.com/#{repo}"
send = 5
for c in commits
if send
d = new Date(Date.parse(c.commit.committer.date)).toFormat("DD/MM HH24:MI")
msg.send "[#{d} -> #{c.commit.committer.PI:NAME:<NAME>END_PI}] #{c.commit.message}"
send -= 1 |
[
{
"context": "url: \"https://docs.google.com/spreadsheet/ccc?key=0Au4e-jj1-69ZdEloMW03UExKLXI3cGRlbkJteGZFSUE#gid=0\"\n",
"end": 894,
"score": 0.9997430443763733,
"start": 850,
"tag": "KEY",
"value": "0Au4e-jj1-69ZdEloMW03UExKLXI3cGRlbkJteGZFSUE"
}
] | examples/quiz.js.coffee | ulitiy/WidLib | 1 | widget=new Widlib.Widget template: "pizza"
widget.setRemoteScript
pages:
question:
body: ->
@currentQuestion().body
inputs: ->
@currentQuestion().inputs
currentQuestion: ->
@cq||=@data("questions", @session("qNumber"))
onSubmit: (input)->
if input.answer!=@currentQuestion().correct
return false #ignore failures
# @mistake++ #количество попыток внутри задания
# @widget.mistake++ #количество ошибок внутри викторины
# if @mistake==2
# return "fail"
@cq=null
@session("qNumber", @session("qNumber")+1)
return false if @currentQuestion()? # return this
"win" #or true
win:
body: "You won!"
data:
questions:
type: "spreadsheet"
url: "https://docs.google.com/spreadsheet/ccc?key=0Au4e-jj1-69ZdEloMW03UExKLXI3cGRlbkJteGZFSUE#gid=0"
| 5394 | widget=new Widlib.Widget template: "pizza"
widget.setRemoteScript
pages:
question:
body: ->
@currentQuestion().body
inputs: ->
@currentQuestion().inputs
currentQuestion: ->
@cq||=@data("questions", @session("qNumber"))
onSubmit: (input)->
if input.answer!=@currentQuestion().correct
return false #ignore failures
# @mistake++ #количество попыток внутри задания
# @widget.mistake++ #количество ошибок внутри викторины
# if @mistake==2
# return "fail"
@cq=null
@session("qNumber", @session("qNumber")+1)
return false if @currentQuestion()? # return this
"win" #or true
win:
body: "You won!"
data:
questions:
type: "spreadsheet"
url: "https://docs.google.com/spreadsheet/ccc?key=<KEY>#gid=0"
| true | widget=new Widlib.Widget template: "pizza"
widget.setRemoteScript
pages:
question:
body: ->
@currentQuestion().body
inputs: ->
@currentQuestion().inputs
currentQuestion: ->
@cq||=@data("questions", @session("qNumber"))
onSubmit: (input)->
if input.answer!=@currentQuestion().correct
return false #ignore failures
# @mistake++ #количество попыток внутри задания
# @widget.mistake++ #количество ошибок внутри викторины
# if @mistake==2
# return "fail"
@cq=null
@session("qNumber", @session("qNumber")+1)
return false if @currentQuestion()? # return this
"win" #or true
win:
body: "You won!"
data:
questions:
type: "spreadsheet"
url: "https://docs.google.com/spreadsheet/ccc?key=PI:KEY:<KEY>END_PI#gid=0"
|
[
{
"context": "yles!) smooth change effect\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nclass Fx.Attr extends Fx\n\n# protected\n\n prepar",
"end": 96,
"score": 0.9998930096626282,
"start": 79,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/fx/src/fx/attr.coffee | lovely-io/lovely.io-stl | 2 | #
# Basic attributes (not styles!) smooth change effect
#
# Copyright (C) 2011 Nikolay Nemshilov
#
class Fx.Attr extends Fx
# protected
prepare: (attrs)->
@before = {}
@after = attrs
element = @element._
for key of attrs
@before[key] = element[key]
return ;
render: (delta)->
element = @element._
before = @before
after = @after
for key of before
element[key] = before[key] + (after[key] - before[key]) * delta
return; | 80080 | #
# Basic attributes (not styles!) smooth change effect
#
# Copyright (C) 2011 <NAME>
#
class Fx.Attr extends Fx
# protected
prepare: (attrs)->
@before = {}
@after = attrs
element = @element._
for key of attrs
@before[key] = element[key]
return ;
render: (delta)->
element = @element._
before = @before
after = @after
for key of before
element[key] = before[key] + (after[key] - before[key]) * delta
return; | true | #
# Basic attributes (not styles!) smooth change effect
#
# Copyright (C) 2011 PI:NAME:<NAME>END_PI
#
class Fx.Attr extends Fx
# protected
prepare: (attrs)->
@before = {}
@after = attrs
element = @element._
for key of attrs
@before[key] = element[key]
return ;
render: (delta)->
element = @element._
before = @before
after = @after
for key of before
element[key] = before[key] + (after[key] - before[key]) * delta
return; |
[
{
"context": "ize: (key, count) ->\n if count is 0\n key = \"#{key}.zero\"\n else if count is 1\n key = \"#{key}.one\"\n",
"end": 483,
"score": 0.7987183332443237,
"start": 471,
"tag": "KEY",
"value": "\"#{key}.zero"
},
{
"context": "= \"#{key}.zero\"\n else if cou... | src/i18n/index.coffee | mateusmaso/hipbone | 0 | _ = require "underscore"
Module = require "./../module"
module.exports = class I18n extends Module
constructor: (locale, locales={}, splitter) ->
@locale = locale
@locales = locales
@splitter = splitter || /{{\w+}}/g
interpolate: (text, values={}) ->
for match in text.match(@splitter) || []
value = values[match.replace(/\W/g, "")]
text = text.replace(match, value)
text
pluralize: (key, count) ->
if count is 0
key = "#{key}.zero"
else if count is 1
key = "#{key}.one"
else
key = "#{key}.other"
_.path(@locales[@locale], key)
inflector: (key, gender) ->
if gender is 'm'
key = "#{key}.male"
else if gender is 'f'
key = "#{key}.female"
else
key = "#{key}.neutral"
_.path(@locales[@locale], key)
translate: (key, options={}) ->
if _.has(options, 'count')
text = @pluralize(key, options.count)
else if _.has(options, 'gender')
text = @inflector(key, options.gender)
else
text = _.path(@locales[@locale], key)
@interpolate(text, options)
t: @::translate
@register "I18n"
| 156660 | _ = require "underscore"
Module = require "./../module"
module.exports = class I18n extends Module
constructor: (locale, locales={}, splitter) ->
@locale = locale
@locales = locales
@splitter = splitter || /{{\w+}}/g
interpolate: (text, values={}) ->
for match in text.match(@splitter) || []
value = values[match.replace(/\W/g, "")]
text = text.replace(match, value)
text
pluralize: (key, count) ->
if count is 0
key = <KEY>"
else if count is 1
key = <KEY>"
else
key = "#{key}.other"
_.path(@locales[@locale], key)
inflector: (key, gender) ->
if gender is 'm'
key = "#{key}.male"
else if gender is 'f'
key = <KEY>}.female"
else
key = "#{key}.neutral"
_.path(@locales[@locale], key)
translate: (key, options={}) ->
if _.has(options, 'count')
text = @pluralize(key, options.count)
else if _.has(options, 'gender')
text = @inflector(key, options.gender)
else
text = _.path(@locales[@locale], key)
@interpolate(text, options)
t: @::translate
@register "I18n"
| true | _ = require "underscore"
Module = require "./../module"
module.exports = class I18n extends Module
constructor: (locale, locales={}, splitter) ->
@locale = locale
@locales = locales
@splitter = splitter || /{{\w+}}/g
interpolate: (text, values={}) ->
for match in text.match(@splitter) || []
value = values[match.replace(/\W/g, "")]
text = text.replace(match, value)
text
pluralize: (key, count) ->
if count is 0
key = PI:KEY:<KEY>END_PI"
else if count is 1
key = PI:KEY:<KEY>END_PI"
else
key = "#{key}.other"
_.path(@locales[@locale], key)
inflector: (key, gender) ->
if gender is 'm'
key = "#{key}.male"
else if gender is 'f'
key = PI:KEY:<KEY>END_PI}.female"
else
key = "#{key}.neutral"
_.path(@locales[@locale], key)
translate: (key, options={}) ->
if _.has(options, 'count')
text = @pluralize(key, options.count)
else if _.has(options, 'gender')
text = @inflector(key, options.gender)
else
text = _.path(@locales[@locale], key)
@interpolate(text, options)
t: @::translate
@register "I18n"
|
[
{
"context": "local\"\n tld: \"nl\"\n })\n\n it \"parses 192.168.1.1:8080\", ->\n @isEq(\"http://192.168.1.1:8080\", ",
"end": 1626,
"score": 0.9996785521507263,
"start": 1615,
"tag": "IP_ADDRESS",
"value": "192.168.1.1"
},
{
"context": "\"parses 192.168.1.1:8080\... | packages/server/test/unit/cors_spec.coffee | Everworks/cypress | 3 | require("../spec_helper")
cors = require("#{root}lib/util/cors")
describe "lib/util/cors", ->
context ".parseUrlIntoDomainTldPort", ->
beforeEach ->
@isEq = (url, obj) ->
expect(cors.parseUrlIntoDomainTldPort(url)).to.deep.eq(obj)
it "parses https://www.google.com", ->
@isEq("https://www.google.com", {
port: "443"
domain: "google"
tld: "com"
})
it "parses http://localhost:8080", ->
@isEq("http://localhost:8080", {
port: "8080"
domain: ""
tld: "localhost"
})
it "parses http://app.localhost:8080", ->
@isEq("http://app.localhost:8080", {
port: "8080"
domain: "app"
tld: "localhost"
})
it "parses http://app.localhost.dev:8080", ->
@isEq("http://app.localhost.dev:8080", {
port: "8080"
domain: "localhost"
tld: "dev"
})
it "parses http://app.local:8080", ->
@isEq("http://app.local:8080", {
port: "8080"
domain: "app"
tld: "local"
})
## public suffix example of a private tld
it "parses https://example.herokuapp.com", ->
@isEq("https://example.herokuapp.com", {
port: "443"
domain: "example"
tld: "herokuapp.com"
})
it "parses http://www.local.nl", ->
@isEq("http://www.local.nl", {
port: "80"
domain: "local"
tld: "nl"
})
it "parses http://www.local.nl:8080", ->
@isEq("http://www.local.nl:8080", {
port: "8080"
domain: "local"
tld: "nl"
})
it "parses 192.168.1.1:8080", ->
@isEq("http://192.168.1.1:8080", {
port: "8080"
domain: ""
tld: "192.168.1.1"
})
context ".urlMatchesOriginPolicyProps", ->
beforeEach ->
@isFalse = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.false
@isTrue = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.true
describe "domain + subdomain", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://staging.google.com")
it "does not match", ->
@isFalse("https://foo.bar:443", @props)
@isFalse("http://foo.bar:80", @props)
@isFalse("http://foo.bar", @props)
@isFalse("http://staging.google.com", @props)
@isFalse("http://staging.google.com:80", @props)
@isFalse("https://staging.google2.com:443", @props)
@isFalse("https://staging.google.net:443", @props)
@isFalse("https://google.net:443", @props)
@isFalse("http://google.com", @props)
it "matches", ->
@isTrue("https://staging.google.com:443", @props)
@isTrue("https://google.com:443", @props)
@isTrue("https://foo.google.com:443", @props)
@isTrue("https://foo.bar.google.com:443", @props)
describe "public suffix", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://example.gitlab.io")
it "does not match", ->
@isFalse("http://example.gitlab.io", @props)
@isFalse("https://foo.gitlab.io:443", @props)
it "matches", ->
@isTrue("https://example.gitlab.io:443", @props)
@isTrue("https://foo.example.gitlab.io:443", @props)
describe "localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://localhost:4200")
it "does not match", ->
@isFalse("http://localhost:4201", @props)
@isFalse("http://localhoss:4200", @props)
it "matches", ->
@isTrue("http://localhost:4200", @props)
describe "app.localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://app.localhost:4200")
it "does not match", ->
@isFalse("http://app.localhost:4201", @props)
@isFalse("http://app.localhoss:4200", @props)
it "matches", ->
@isTrue("http://app.localhost:4200", @props)
@isTrue("http://name.app.localhost:4200", @props)
describe "local", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://brian.dev.local")
it "does not match", ->
@isFalse("https://brian.dev.local:443", @props)
@isFalse("https://brian.dev.local", @props)
@isFalse("http://brian.dev2.local:81", @props)
it "matches", ->
@isTrue("http://jennifer.dev.local:80", @props)
@isTrue("http://jennifer.dev.local", @props)
describe "ip address", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://192.168.5.10")
it "does not match", ->
@isFalse("http://192.168.5.10:443", @props)
@isFalse("https://192.168.5.10", @props)
@isFalse("http://193.168.5.10", @props)
@isFalse("http://193.168.5.10:80", @props)
it "matches", ->
@isTrue("http://192.168.5.10", @props)
@isTrue("http://192.168.5.10:80", @props)
| 149157 | require("../spec_helper")
cors = require("#{root}lib/util/cors")
describe "lib/util/cors", ->
context ".parseUrlIntoDomainTldPort", ->
beforeEach ->
@isEq = (url, obj) ->
expect(cors.parseUrlIntoDomainTldPort(url)).to.deep.eq(obj)
it "parses https://www.google.com", ->
@isEq("https://www.google.com", {
port: "443"
domain: "google"
tld: "com"
})
it "parses http://localhost:8080", ->
@isEq("http://localhost:8080", {
port: "8080"
domain: ""
tld: "localhost"
})
it "parses http://app.localhost:8080", ->
@isEq("http://app.localhost:8080", {
port: "8080"
domain: "app"
tld: "localhost"
})
it "parses http://app.localhost.dev:8080", ->
@isEq("http://app.localhost.dev:8080", {
port: "8080"
domain: "localhost"
tld: "dev"
})
it "parses http://app.local:8080", ->
@isEq("http://app.local:8080", {
port: "8080"
domain: "app"
tld: "local"
})
## public suffix example of a private tld
it "parses https://example.herokuapp.com", ->
@isEq("https://example.herokuapp.com", {
port: "443"
domain: "example"
tld: "herokuapp.com"
})
it "parses http://www.local.nl", ->
@isEq("http://www.local.nl", {
port: "80"
domain: "local"
tld: "nl"
})
it "parses http://www.local.nl:8080", ->
@isEq("http://www.local.nl:8080", {
port: "8080"
domain: "local"
tld: "nl"
})
it "parses 192.168.1.1:8080", ->
@isEq("http://192.168.1.1:8080", {
port: "8080"
domain: ""
tld: "192.168.1.1"
})
context ".urlMatchesOriginPolicyProps", ->
beforeEach ->
@isFalse = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.false
@isTrue = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.true
describe "domain + subdomain", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://staging.google.com")
it "does not match", ->
@isFalse("https://foo.bar:443", @props)
@isFalse("http://foo.bar:80", @props)
@isFalse("http://foo.bar", @props)
@isFalse("http://staging.google.com", @props)
@isFalse("http://staging.google.com:80", @props)
@isFalse("https://staging.google2.com:443", @props)
@isFalse("https://staging.google.net:443", @props)
@isFalse("https://google.net:443", @props)
@isFalse("http://google.com", @props)
it "matches", ->
@isTrue("https://staging.google.com:443", @props)
@isTrue("https://google.com:443", @props)
@isTrue("https://foo.google.com:443", @props)
@isTrue("https://foo.bar.google.com:443", @props)
describe "public suffix", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://example.gitlab.io")
it "does not match", ->
@isFalse("http://example.gitlab.io", @props)
@isFalse("https://foo.gitlab.io:443", @props)
it "matches", ->
@isTrue("https://example.gitlab.io:443", @props)
@isTrue("https://foo.example.gitlab.io:443", @props)
describe "localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://localhost:4200")
it "does not match", ->
@isFalse("http://localhost:4201", @props)
@isFalse("http://localhoss:4200", @props)
it "matches", ->
@isTrue("http://localhost:4200", @props)
describe "app.localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://app.localhost:4200")
it "does not match", ->
@isFalse("http://app.localhost:4201", @props)
@isFalse("http://app.localhoss:4200", @props)
it "matches", ->
@isTrue("http://app.localhost:4200", @props)
@isTrue("http://name.app.localhost:4200", @props)
describe "local", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://brian.dev.local")
it "does not match", ->
@isFalse("https://brian.dev.local:443", @props)
@isFalse("https://brian.dev.local", @props)
@isFalse("http://brian.dev2.local:81", @props)
it "matches", ->
@isTrue("http://jennifer.dev.local:80", @props)
@isTrue("http://jennifer.dev.local", @props)
describe "ip address", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://192.168.5.10")
it "does not match", ->
@isFalse("http://192.168.5.10:443", @props)
@isFalse("https://192.168.5.10", @props)
@isFalse("http://192.168.127.12", @props)
@isFalse("http://192.168.127.12:80", @props)
it "matches", ->
@isTrue("http://192.168.5.10", @props)
@isTrue("http://192.168.5.10:80", @props)
| true | require("../spec_helper")
cors = require("#{root}lib/util/cors")
describe "lib/util/cors", ->
context ".parseUrlIntoDomainTldPort", ->
beforeEach ->
@isEq = (url, obj) ->
expect(cors.parseUrlIntoDomainTldPort(url)).to.deep.eq(obj)
it "parses https://www.google.com", ->
@isEq("https://www.google.com", {
port: "443"
domain: "google"
tld: "com"
})
it "parses http://localhost:8080", ->
@isEq("http://localhost:8080", {
port: "8080"
domain: ""
tld: "localhost"
})
it "parses http://app.localhost:8080", ->
@isEq("http://app.localhost:8080", {
port: "8080"
domain: "app"
tld: "localhost"
})
it "parses http://app.localhost.dev:8080", ->
@isEq("http://app.localhost.dev:8080", {
port: "8080"
domain: "localhost"
tld: "dev"
})
it "parses http://app.local:8080", ->
@isEq("http://app.local:8080", {
port: "8080"
domain: "app"
tld: "local"
})
## public suffix example of a private tld
it "parses https://example.herokuapp.com", ->
@isEq("https://example.herokuapp.com", {
port: "443"
domain: "example"
tld: "herokuapp.com"
})
it "parses http://www.local.nl", ->
@isEq("http://www.local.nl", {
port: "80"
domain: "local"
tld: "nl"
})
it "parses http://www.local.nl:8080", ->
@isEq("http://www.local.nl:8080", {
port: "8080"
domain: "local"
tld: "nl"
})
it "parses 192.168.1.1:8080", ->
@isEq("http://192.168.1.1:8080", {
port: "8080"
domain: ""
tld: "192.168.1.1"
})
context ".urlMatchesOriginPolicyProps", ->
beforeEach ->
@isFalse = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.false
@isTrue = (url, props) =>
expect(cors.urlMatchesOriginPolicyProps(url, props)).to.be.true
describe "domain + subdomain", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://staging.google.com")
it "does not match", ->
@isFalse("https://foo.bar:443", @props)
@isFalse("http://foo.bar:80", @props)
@isFalse("http://foo.bar", @props)
@isFalse("http://staging.google.com", @props)
@isFalse("http://staging.google.com:80", @props)
@isFalse("https://staging.google2.com:443", @props)
@isFalse("https://staging.google.net:443", @props)
@isFalse("https://google.net:443", @props)
@isFalse("http://google.com", @props)
it "matches", ->
@isTrue("https://staging.google.com:443", @props)
@isTrue("https://google.com:443", @props)
@isTrue("https://foo.google.com:443", @props)
@isTrue("https://foo.bar.google.com:443", @props)
describe "public suffix", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("https://example.gitlab.io")
it "does not match", ->
@isFalse("http://example.gitlab.io", @props)
@isFalse("https://foo.gitlab.io:443", @props)
it "matches", ->
@isTrue("https://example.gitlab.io:443", @props)
@isTrue("https://foo.example.gitlab.io:443", @props)
describe "localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://localhost:4200")
it "does not match", ->
@isFalse("http://localhost:4201", @props)
@isFalse("http://localhoss:4200", @props)
it "matches", ->
@isTrue("http://localhost:4200", @props)
describe "app.localhost", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://app.localhost:4200")
it "does not match", ->
@isFalse("http://app.localhost:4201", @props)
@isFalse("http://app.localhoss:4200", @props)
it "matches", ->
@isTrue("http://app.localhost:4200", @props)
@isTrue("http://name.app.localhost:4200", @props)
describe "local", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://brian.dev.local")
it "does not match", ->
@isFalse("https://brian.dev.local:443", @props)
@isFalse("https://brian.dev.local", @props)
@isFalse("http://brian.dev2.local:81", @props)
it "matches", ->
@isTrue("http://jennifer.dev.local:80", @props)
@isTrue("http://jennifer.dev.local", @props)
describe "ip address", ->
beforeEach ->
@props = cors.parseUrlIntoDomainTldPort("http://192.168.5.10")
it "does not match", ->
@isFalse("http://192.168.5.10:443", @props)
@isFalse("https://192.168.5.10", @props)
@isFalse("http://PI:IP_ADDRESS:192.168.127.12END_PI", @props)
@isFalse("http://PI:IP_ADDRESS:192.168.127.12END_PI:80", @props)
it "matches", ->
@isTrue("http://192.168.5.10", @props)
@isTrue("http://192.168.5.10:80", @props)
|
[
{
"context": "tner_id\":10000000,\n \"account_id\":\"15056805\",\n \"tenant_name\":\"Go Green\",\n ",
"end": 471,
"score": 0.9595853090286255,
"start": 463,
"tag": "KEY",
"value": "15056805"
},
{
"context": "t_id\":\"15056805\",\n \"... | models/directory/fixture/get_company_directory.coffee | signonsridhar/sridhar_hbs | 0 | define([ 'can_fixture'], (can)->
can.fixture('GET /bss/tenant?action=getcompanydirectory', (req, res)->
return `{
"response":{
"service":"getcompanydirectory",
"response_code":100,
"execution_time":78,
"timestamp":"2014-02-05T23:10:15+0000",
"response_data":{
"tenant_id":88880005,
"partner_id":10000000,
"account_id":"15056805",
"tenant_name":"Go Green",
"status":"active",
"credit_card_status": "pending_expiration",
"primary_address_street1":"1800 stokes street",
"primary_address_city":"san jose",
"primary_address_state":"CA",
"primary_address_country":"US",
"primary_address_zip":"95132",
"language":"EN",
"timezone":"AMERICA_LOS_ANGELES",
"conference_enabled":false,
"number_porting_enabled":true,
"fax_enabled":false,
"main_number":"14082000118",
"has_default_main_number":false,
"bundles":[
{
"bundle_id":88880030,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"sapn",
"last_name":"jkjk",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"sapna013100@choochee.com",
"image_present":false
},
"extensions":[
{
"extensionid":88880040,
"tenantid":88880005,
"extension_number":201,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880030,
"is_assigned":false,
"extension":201,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880045,
"partner_code":"tmus",
"phonenumber":14082000119,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880045,
"user_id":88880007,
"extension_id":88880040
}
}
],
"group_members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880032,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"sapn",
"last_name":"jkjk",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"sapna013100@choochee.com",
"image_present":false
},
"extensions":[
{
"extensionid":88880044,
"tenantid":88880005,
"extension_number":203,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880032,
"is_assigned":false,
"extension":203,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880047,
"partner_code":"tmus",
"phonenumber":14082000121,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880047,
"user_id":88880007,
"extension_id":88880044
}
}
],
"group_members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
},
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880031,
"tenant_id":88880005,
"status":"UNPROVISIONED",
"is_assigned":false,
"extensions":[
{
"extensionid":88880041,
"tenantid":88880005,
"extension_number":202,
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880031,
"is_assigned":false,
"extension":202,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880046,
"partner_code":"tmus",
"phonenumber":14082000120,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line"
}
],
"group_members":[
]
}
]
}
],
"groups":[
{
"groupid":88880019,
"tenantid":88880005,
"group_name":"Smart",
"group_extension":"233",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880060,
"tenantid":88880005,
"extension_number":233,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880022,
"tenantid":88880005,
"group_name":"Geometry",
"group_extension":"238",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880063,
"tenantid":88880005,
"extension_number":238,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880020,
"tenantid":88880005,
"group_name":"hhhh",
"group_extension":"231",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880061,
"tenantid":88880005,
"extension_number":231,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880017,
"tenantid":88880005,
"group_name":"cute",
"group_extension":"232",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":6,
"extensions":[
{
"extensionid":88880058,
"tenantid":88880005,
"extension_number":232,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880010,
"tenantid":88880005,
"group_name":"Main",
"group_extension":"200",
"group_call_type":"ivr",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_group_ring":false,
"enable_custom_greeting":false,
"enable_auto_attendant":true,
"enable_group_menu":true,
"enable_company_directory":true,
"enable_company_extensions":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880042,
"tenantid":88880005,
"extension_number":200,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880044,
"partner_code":"tmus",
"phonenumber":14082000118,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"main_line",
"phone_number_address":{
"did_id":88880044,
"user_id":88880007,
"extension_id":88880042,
"address_street1":"1800 stokes street",
"address_street2":"1800 stokes street",
"address_city":"san jose",
"address_state":"CA",
"address_country":"US",
"address_zip":"95132"
}
}
]
}
],
"members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
}
]
},
{
"groupid":88880021,
"tenantid":88880005,
"group_name":"luxuary",
"group_extension":"236",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880062,
"tenantid":88880005,
"extension_number":236,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880018,
"tenantid":88880005,
"group_name":"Genius",
"group_extension":"243",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880059,
"tenantid":88880005,
"extension_number":243,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880011,
"tenantid":88880005,
"group_name":"Conference",
"group_extension":"888",
"group_call_type":"conference",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":false,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_custom_greeting":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880043,
"tenantid":88880005,
"extension_number":888,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880087,
"partner_code":"tmus",
"phonenumber":14088000100,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880093,
"partner_code":"tmus",
"phonenumber":14088000106,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880009,
"partner_code":"tmus",
"phonenumber":14085000774,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880097,
"partner_code":"tmus",
"phonenumber":14088000110,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880094,
"partner_code":"tmus",
"phonenumber":14088000107,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880089,
"partner_code":"tmus",
"phonenumber":14088000102,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880092,
"partner_code":"tmus",
"phonenumber":14088000105,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880008,
"partner_code":"tmus",
"phonenumber":14085000773,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880099,
"partner_code":"tmus",
"phonenumber":18554458764,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880095,
"partner_code":"tmus",
"phonenumber":14088000108,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880088,
"partner_code":"tmus",
"phonenumber":14088000101,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880096,
"partner_code":"tmus",
"phonenumber":14088000109,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880098,
"partner_code":"tmus",
"phonenumber":18554458763,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880091,
"partner_code":"tmus",
"phonenumber":14088000104,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880090,
"partner_code":"tmus",
"phonenumber":14088000103,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
}
]
}
],
"members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
}
]
},
{
"groupid":88880023,
"tenantid":88880005,
"group_name":"magic",
"group_extension":"239",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880064,
"tenantid":88880005,
"extension_number":239,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880012,
"tenantid":88880005,
"group_name":"Marketting",
"group_extension":"765",
"group_call_type":"sequential",
"voicemail_forward_email":"sapna013100@choochee.com",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":3,
"extensions":[
{
"extensionid":88880045,
"tenantid":88880005,
"extension_number":765,
"vm_forwarding_email":"sapna013100@choochee.com",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"sapna013100@choochee.com",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"sapn",
"member_last_name":"jkjk",
"enable_phone_ring":true
}
]
}
]
},
"version":"1.0"
}
}`
)
) | 126545 | define([ 'can_fixture'], (can)->
can.fixture('GET /bss/tenant?action=getcompanydirectory', (req, res)->
return `{
"response":{
"service":"getcompanydirectory",
"response_code":100,
"execution_time":78,
"timestamp":"2014-02-05T23:10:15+0000",
"response_data":{
"tenant_id":88880005,
"partner_id":10000000,
"account_id":"<KEY>",
"tenant_name":"<NAME>",
"status":"active",
"credit_card_status": "pending_expiration",
"primary_address_street1":"1800 stokes street",
"primary_address_city":"san jose",
"primary_address_state":"CA",
"primary_address_country":"US",
"primary_address_zip":"95132",
"language":"EN",
"timezone":"AMERICA_LOS_ANGELES",
"conference_enabled":false,
"number_porting_enabled":true,
"fax_enabled":false,
"main_number":"14082000118",
"has_default_main_number":false,
"bundles":[
{
"bundle_id":88880030,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"<NAME>",
"last_name":"<NAME>",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"<EMAIL>",
"image_present":false
},
"extensions":[
{
"extensionid":88880040,
"tenantid":88880005,
"extension_number":201,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880030,
"is_assigned":false,
"extension":201,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880045,
"partner_code":"tmus",
"phonenumber":14082000119,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880045,
"user_id":88880007,
"extension_id":88880040
}
}
],
"group_members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880032,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"<NAME>",
"last_name":"<NAME>",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"<EMAIL>",
"image_present":false
},
"extensions":[
{
"extensionid":88880044,
"tenantid":88880005,
"extension_number":203,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880032,
"is_assigned":false,
"extension":203,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880047,
"partner_code":"tmus",
"phonenumber":14082000121,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880047,
"user_id":88880007,
"extension_id":88880044
}
}
],
"group_members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
},
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880031,
"tenant_id":88880005,
"status":"UNPROVISIONED",
"is_assigned":false,
"extensions":[
{
"extensionid":88880041,
"tenantid":88880005,
"extension_number":202,
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880031,
"is_assigned":false,
"extension":202,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880046,
"partner_code":"tmus",
"phonenumber":14082000120,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line"
}
],
"group_members":[
]
}
]
}
],
"groups":[
{
"groupid":88880019,
"tenantid":88880005,
"group_name":"Smart",
"group_extension":"233",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880060,
"tenantid":88880005,
"extension_number":233,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880022,
"tenantid":88880005,
"group_name":"Geometry",
"group_extension":"238",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880063,
"tenantid":88880005,
"extension_number":238,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880020,
"tenantid":88880005,
"group_name":"hhhh",
"group_extension":"231",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880061,
"tenantid":88880005,
"extension_number":231,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880017,
"tenantid":88880005,
"group_name":"cute",
"group_extension":"232",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":6,
"extensions":[
{
"extensionid":88880058,
"tenantid":88880005,
"extension_number":232,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880010,
"tenantid":88880005,
"group_name":"Main",
"group_extension":"200",
"group_call_type":"ivr",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_group_ring":false,
"enable_custom_greeting":false,
"enable_auto_attendant":true,
"enable_group_menu":true,
"enable_company_directory":true,
"enable_company_extensions":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880042,
"tenantid":88880005,
"extension_number":200,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880044,
"partner_code":"tmus",
"phonenumber":14082000118,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"main_line",
"phone_number_address":{
"did_id":88880044,
"user_id":88880007,
"extension_id":88880042,
"address_street1":"1800 stokes street",
"address_street2":"1800 stokes street",
"address_city":"san jose",
"address_state":"CA",
"address_country":"US",
"address_zip":"95132"
}
}
]
}
],
"members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
}
]
},
{
"groupid":88880021,
"tenantid":88880005,
"group_name":"<NAME>",
"group_extension":"236",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880062,
"tenantid":88880005,
"extension_number":236,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880018,
"tenantid":88880005,
"group_name":"<NAME>",
"group_extension":"243",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880059,
"tenantid":88880005,
"extension_number":243,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880011,
"tenantid":88880005,
"group_name":"Conference",
"group_extension":"888",
"group_call_type":"conference",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":false,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_custom_greeting":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880043,
"tenantid":88880005,
"extension_number":888,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880087,
"partner_code":"tmus",
"phonenumber":14088000100,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880093,
"partner_code":"tmus",
"phonenumber":14088000106,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880009,
"partner_code":"tmus",
"phonenumber":14085000774,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880097,
"partner_code":"tmus",
"phonenumber":14088000110,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880094,
"partner_code":"tmus",
"phonenumber":14088000107,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880089,
"partner_code":"tmus",
"phonenumber":14088000102,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880092,
"partner_code":"tmus",
"phonenumber":14088000105,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880008,
"partner_code":"<NAME>us",
"phonenumber":14085000773,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880099,
"partner_code":"<NAME>us",
"phonenumber":18554458764,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880095,
"partner_code":"tmus",
"phonenumber":14088000108,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880088,
"partner_code":"tmus",
"phonenumber":14088000101,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880096,
"partner_code":"tmus",
"phonenumber":14088000109,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880098,
"partner_code":"tmus",
"phonenumber":18554458763,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880091,
"partner_code":"tmus",
"phonenumber":14088000104,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880090,
"partner_code":"tmus",
"phonenumber":14088000103,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
}
]
}
],
"members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
}
]
},
{
"groupid":88880023,
"tenantid":88880005,
"group_name":"magic",
"group_extension":"239",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880064,
"tenantid":88880005,
"extension_number":239,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880012,
"tenantid":88880005,
"group_name":"Marketting",
"group_extension":"765",
"group_call_type":"sequential",
"voicemail_forward_email":"<EMAIL>",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":3,
"extensions":[
{
"extensionid":88880045,
"tenantid":88880005,
"extension_number":765,
"vm_forwarding_email":"<EMAIL>",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"<EMAIL>",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"<NAME>",
"member_last_name":"<NAME>",
"enable_phone_ring":true
}
]
}
]
},
"version":"1.0"
}
}`
)
) | true | define([ 'can_fixture'], (can)->
can.fixture('GET /bss/tenant?action=getcompanydirectory', (req, res)->
return `{
"response":{
"service":"getcompanydirectory",
"response_code":100,
"execution_time":78,
"timestamp":"2014-02-05T23:10:15+0000",
"response_data":{
"tenant_id":88880005,
"partner_id":10000000,
"account_id":"PI:KEY:<KEY>END_PI",
"tenant_name":"PI:NAME:<NAME>END_PI",
"status":"active",
"credit_card_status": "pending_expiration",
"primary_address_street1":"1800 stokes street",
"primary_address_city":"san jose",
"primary_address_state":"CA",
"primary_address_country":"US",
"primary_address_zip":"95132",
"language":"EN",
"timezone":"AMERICA_LOS_ANGELES",
"conference_enabled":false,
"number_porting_enabled":true,
"fax_enabled":false,
"main_number":"14082000118",
"has_default_main_number":false,
"bundles":[
{
"bundle_id":88880030,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"PI:NAME:<NAME>END_PI",
"last_name":"PI:NAME:<NAME>END_PI",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"PI:EMAIL:<EMAIL>END_PI",
"image_present":false
},
"extensions":[
{
"extensionid":88880040,
"tenantid":88880005,
"extension_number":201,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880030,
"is_assigned":false,
"extension":201,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880045,
"partner_code":"tmus",
"phonenumber":14082000119,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880045,
"user_id":88880007,
"extension_id":88880040
}
}
],
"group_members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880032,
"tenant_id":88880005,
"status":"OSSPROVISIONED",
"is_assigned":true,
"user":{
"tenantid":88880005,
"userid":88880007,
"first_name":"PI:NAME:<NAME>END_PI",
"last_name":"PI:NAME:<NAME>END_PI",
"timezone":"AMERICA_LOS_ANGELES",
"language":"EN",
"conferenceBridge":8835484,
"conference_bridge_pin":5829,
"conference_enabled":true,
"is_administrator":true,
"email":"PI:EMAIL:<EMAIL>END_PI",
"image_present":false
},
"extensions":[
{
"extensionid":88880044,
"tenantid":88880005,
"extension_number":203,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880032,
"is_assigned":false,
"extension":203,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880047,
"partner_code":"tmus",
"phonenumber":14082000121,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line",
"phone_number_address":{
"did_id":88880047,
"user_id":88880007,
"extension_id":88880044
}
}
],
"group_members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
},
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
}
]
}
]
},
{
"bundle_id":88880031,
"tenant_id":88880005,
"status":"UNPROVISIONED",
"is_assigned":false,
"extensions":[
{
"extensionid":88880041,
"tenantid":88880005,
"extension_number":202,
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
{
"deviceid":88880031,
"is_assigned":false,
"extension":202,
"productid":"10261667",
"product_sku":"SKU-CSO-IP303-001",
"status":"order_initiated",
"device_name":"Cisco IP303 Default Device",
"registration_date":"2014-01-31 10:27:08.0",
"rebooted_date":"2014-01-31 10:27:08.0",
"creation_date":"2014-01-31 10:27:08.0",
"order_id":"5728830",
"needs_provisoining":false
}
],
"phone_numbers":[
{
"didid":88880046,
"partner_code":"tmus",
"phonenumber":14082000120,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"user_line"
}
],
"group_members":[
]
}
]
}
],
"groups":[
{
"groupid":88880019,
"tenantid":88880005,
"group_name":"Smart",
"group_extension":"233",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880060,
"tenantid":88880005,
"extension_number":233,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880022,
"tenantid":88880005,
"group_name":"Geometry",
"group_extension":"238",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880063,
"tenantid":88880005,
"extension_number":238,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880020,
"tenantid":88880005,
"group_name":"hhhh",
"group_extension":"231",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880061,
"tenantid":88880005,
"extension_number":231,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880017,
"tenantid":88880005,
"group_name":"cute",
"group_extension":"232",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":6,
"extensions":[
{
"extensionid":88880058,
"tenantid":88880005,
"extension_number":232,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880010,
"tenantid":88880005,
"group_name":"Main",
"group_extension":"200",
"group_call_type":"ivr",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_group_ring":false,
"enable_custom_greeting":false,
"enable_auto_attendant":true,
"enable_group_menu":true,
"enable_company_directory":true,
"enable_company_extensions":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880042,
"tenantid":88880005,
"extension_number":200,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880044,
"partner_code":"tmus",
"phonenumber":14082000118,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":false,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"main_line",
"phone_number_address":{
"did_id":88880044,
"user_id":88880007,
"extension_id":88880042,
"address_street1":"1800 stokes street",
"address_street2":"1800 stokes street",
"address_city":"san jose",
"address_state":"CA",
"address_country":"US",
"address_zip":"95132"
}
}
]
}
],
"members":[
{
"groupid":88880010,
"group_name":"Main",
"group_extension":200,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
}
]
},
{
"groupid":88880021,
"tenantid":88880005,
"group_name":"PI:NAME:<NAME>END_PI",
"group_extension":"236",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880062,
"tenantid":88880005,
"extension_number":236,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880018,
"tenantid":88880005,
"group_name":"PI:NAME:<NAME>END_PI",
"group_extension":"243",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880059,
"tenantid":88880005,
"extension_number":243,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880011,
"tenantid":88880005,
"group_name":"Conference",
"group_extension":"888",
"group_call_type":"conference",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":false,
"enable_voicemail":true,
"allow_member_forward":false,
"enable_custom_greeting":false,
"enable_dnd":false,
"extensions":[
{
"extensionid":88880043,
"tenantid":88880005,
"extension_number":888,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":false,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
{
"didid":88880087,
"partner_code":"tmus",
"phonenumber":14088000100,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880093,
"partner_code":"tmus",
"phonenumber":14088000106,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880009,
"partner_code":"tmus",
"phonenumber":14085000774,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880097,
"partner_code":"tmus",
"phonenumber":14088000110,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880094,
"partner_code":"tmus",
"phonenumber":14088000107,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880089,
"partner_code":"tmus",
"phonenumber":14088000102,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880092,
"partner_code":"tmus",
"phonenumber":14088000105,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880008,
"partner_code":"PI:NAME:<NAME>END_PIus",
"phonenumber":14085000773,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880099,
"partner_code":"PI:NAME:<NAME>END_PIus",
"phonenumber":18554458764,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880095,
"partner_code":"tmus",
"phonenumber":14088000108,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880088,
"partner_code":"tmus",
"phonenumber":14088000101,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880096,
"partner_code":"tmus",
"phonenumber":14088000109,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880098,
"partner_code":"tmus",
"phonenumber":18554458763,
"caller_id":0,
"area_code":"855",
"country_code":"1",
"city":"",
"state":"CA",
"is_conference":true,
"is_toll_free":true,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880091,
"partner_code":"tmus",
"phonenumber":14088000104,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
},
{
"didid":88880090,
"partner_code":"tmus",
"phonenumber":14088000103,
"caller_id":0,
"area_code":"408",
"country_code":"1",
"city":"MORGAN HILL",
"state":"CA",
"is_conference":true,
"is_toll_free":false,
"is_ported":false,
"is_assigned":true,
"extension":0,
"type":"group_line"
}
]
}
],
"members":[
{
"groupid":88880011,
"group_name":"Conference",
"group_extension":888,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880040,
"member_extension_number":201,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
}
]
},
{
"groupid":88880023,
"tenantid":88880005,
"group_name":"magic",
"group_extension":"239",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":0,
"extensions":[
{
"extensionid":88880064,
"tenantid":88880005,
"extension_number":239,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
]
},
{
"groupid":88880012,
"tenantid":88880005,
"group_name":"Marketting",
"group_extension":"765",
"group_call_type":"sequential",
"voicemail_forward_email":"PI:EMAIL:<EMAIL>END_PI",
"enable_voicemail_forward_email":true,
"enable_voicemail":true,
"allow_member_forward":false,
"use_in_groups_auto_attendant":true,
"enable_custom_greeting":false,
"enable_dnd":false,
"ivr_digit":3,
"extensions":[
{
"extensionid":88880045,
"tenantid":88880005,
"extension_number":765,
"vm_forwarding_email":"PI:EMAIL:<EMAIL>END_PI",
"dnd_enabled":false,
"call_waiting_enabled":false,
"forwarding_enabled":false,
"vm_forwarding_enabled":true,
"international_calls_enabled":false,
"devices":[
],
"phone_numbers":[
]
}
],
"members":[
{
"groupid":88880012,
"group_name":"Marketting",
"group_extension":765,
"memberid":88880007,
"member_email_address":"PI:EMAIL:<EMAIL>END_PI",
"member_extensionid":88880044,
"member_extension_number":203,
"member_first_name":"PI:NAME:<NAME>END_PI",
"member_last_name":"PI:NAME:<NAME>END_PI",
"enable_phone_ring":true
}
]
}
]
},
"version":"1.0"
}
}`
)
) |
[
{
"context": "vent usage of this.state within setState\n# @author Rolf Erik Lekang, Jørgen Aaberg\n###\n'use strict'\n\n# --------------",
"end": 91,
"score": 0.9998765587806702,
"start": 75,
"tag": "NAME",
"value": "Rolf Erik Lekang"
},
{
"context": ".state within setState\n# @autho... | src/tests/rules/no-access-state-in-setstate.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prevent usage of this.state within setState
# @author Rolf Erik Lekang, Jørgen Aaberg
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-access-state-in-setstate'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-access-state-in-setstate', rule,
valid: [
code: '''
Hello = React.createClass
onClick: ->
@setState (state) => {value: state.value + 1}
'''
,
code: '''
Hello = React.createClass({
multiplyValue: (obj) ->
return obj.value*2
onClick: ->
value = this.state.value
this.multiplyValue({ value: value })
})
'''
,
# issue 1559: don't crash
code: '''
SearchForm = createReactClass({
render: ->
return (
<div>
{(->
if (this.state.prompt)
return <div>{this.state.prompt}</div>
).call(this)}
</div>
)
})
'''
,
# issue 1604: allow this.state in callback
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => console.log(this.state))
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => 1 + 1)
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
nextValueNotUsed = this.state.value + 1
nextValue = 2
this.setState({value: nextValue})
})
'''
,
# https://github.com/yannickcr/eslint-plugin-react/pull/1611
code: '''
testFunction = ({a, b}) ->
'''
]
invalid: [
code: '''
Hello = React.createClass
onClick: ->
@setState value: @state.value + 1
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState => {value: this.state.value + 1}
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
nextValue = this.state.value + 1
this.setState({value: nextValue})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
{state, ...rest} = this
this.setState({value: state.value + 1})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
nextState = (state) ->
return {value: state.value + 1}
Hello = React.createClass({
onClick: ->
this.setState(nextState(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => 1 + 1)
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => console.log(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
nextState: ->
return {value: this.state.value + 1}
onClick: ->
this.setState(nextState())
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
]
| 20659 | ###*
# @fileoverview Prevent usage of this.state within setState
# @author <NAME>, <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-access-state-in-setstate'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-access-state-in-setstate', rule,
valid: [
code: '''
Hello = React.createClass
onClick: ->
@setState (state) => {value: state.value + 1}
'''
,
code: '''
Hello = React.createClass({
multiplyValue: (obj) ->
return obj.value*2
onClick: ->
value = this.state.value
this.multiplyValue({ value: value })
})
'''
,
# issue 1559: don't crash
code: '''
SearchForm = createReactClass({
render: ->
return (
<div>
{(->
if (this.state.prompt)
return <div>{this.state.prompt}</div>
).call(this)}
</div>
)
})
'''
,
# issue 1604: allow this.state in callback
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => console.log(this.state))
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => 1 + 1)
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
nextValueNotUsed = this.state.value + 1
nextValue = 2
this.setState({value: nextValue})
})
'''
,
# https://github.com/yannickcr/eslint-plugin-react/pull/1611
code: '''
testFunction = ({a, b}) ->
'''
]
invalid: [
code: '''
Hello = React.createClass
onClick: ->
@setState value: @state.value + 1
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState => {value: this.state.value + 1}
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
nextValue = this.state.value + 1
this.setState({value: nextValue})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
{state, ...rest} = this
this.setState({value: state.value + 1})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
nextState = (state) ->
return {value: state.value + 1}
Hello = React.createClass({
onClick: ->
this.setState(nextState(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => 1 + 1)
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => console.log(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
nextState: ->
return {value: this.state.value + 1}
onClick: ->
this.setState(nextState())
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
]
| true | ###*
# @fileoverview Prevent usage of this.state within setState
# @author PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-access-state-in-setstate'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-access-state-in-setstate', rule,
valid: [
code: '''
Hello = React.createClass
onClick: ->
@setState (state) => {value: state.value + 1}
'''
,
code: '''
Hello = React.createClass({
multiplyValue: (obj) ->
return obj.value*2
onClick: ->
value = this.state.value
this.multiplyValue({ value: value })
})
'''
,
# issue 1559: don't crash
code: '''
SearchForm = createReactClass({
render: ->
return (
<div>
{(->
if (this.state.prompt)
return <div>{this.state.prompt}</div>
).call(this)}
</div>
)
})
'''
,
# issue 1604: allow this.state in callback
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => console.log(this.state))
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState({}, () => 1 + 1)
})
'''
,
code: '''
Hello = React.createClass({
onClick: ->
nextValueNotUsed = this.state.value + 1
nextValue = 2
this.setState({value: nextValue})
})
'''
,
# https://github.com/yannickcr/eslint-plugin-react/pull/1611
code: '''
testFunction = ({a, b}) ->
'''
]
invalid: [
code: '''
Hello = React.createClass
onClick: ->
@setState value: @state.value + 1
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState => {value: this.state.value + 1}
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
nextValue = this.state.value + 1
this.setState({value: nextValue})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
{state, ...rest} = this
this.setState({value: state.value + 1})
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
nextState = (state) ->
return {value: state.value + 1}
Hello = React.createClass({
onClick: ->
this.setState(nextState(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => 1 + 1)
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
onClick: ->
this.setState(this.state, () => console.log(this.state))
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
,
code: '''
Hello = React.createClass({
nextState: ->
return {value: this.state.value + 1}
onClick: ->
this.setState(nextState())
})
'''
errors: [
message: 'Use callback in setState when referencing the previous state.'
]
]
|
[
{
"context": ").count() is 0\n Accounts.createUser(\n email: \"lauren.craig@newspring.cc\"\n password: \"newspring\"\n profile:\n nam",
"end": 96,
"score": 0.9999266862869263,
"start": 71,
"tag": "EMAIL",
"value": "lauren.craig@newspring.cc"
},
{
"context": "email: \"l... | _source/lib/config/accounts.coffee | jbaxleyiii/laurencraig.com | 0 | if Meteor.users.find().count() is 0
Accounts.createUser(
email: "lauren.craig@newspring.cc"
password: "newspring"
profile:
name: "Lauren Craig"
)
| 129053 | if Meteor.users.find().count() is 0
Accounts.createUser(
email: "<EMAIL>"
password: "<PASSWORD>"
profile:
name: "<NAME>"
)
| true | if Meteor.users.find().count() is 0
Accounts.createUser(
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
profile:
name: "PI:NAME:<NAME>END_PI"
)
|
[
{
"context": "\n passwords =\n currentPassword: $scope.password.current\n plainPassword:\n first: $s",
"end": 1647,
"score": 0.6469756960868835,
"start": 1639,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "lainPassword:\n first: $scope.p... | src/Vifeed/FrontendBundle/Resources/assets/js/profile/controllers/profile-ctrl.coffee | bzis/zomba | 0 | angular.module('profile').controller 'ProfileCtrl', [
'$scope', '$location', 'security', 'Companies', 'ProgressBar', 'Utility', 'company',
($scope, $location, security, Companies, ProgressBar, Utility, company) ->
'use strict'
return unless security.isAuthenticated()
$scope.hasCompany = false
$scope.loadingProfile = false
$scope.loadingPasswords = false
$scope.loadingCompany = false
$scope.errorList = []
$scope.passwordErrorList = []
$scope.campaignErrorList = []
$scope.profile = security.currentUser
$scope.taxationSystems = Companies.getTaxationSystems()
$scope.company = company
resetPasswordModels = ->
$scope.password =
current: null
newOne: null
newOneRepeated: null
$scope.updateUserInfo = ->
ProgressBar.start()
$scope.loadingProfile = true
$scope.errorList = []
profile =
first_name: $scope.profile.firstName
surname: $scope.profile.lastName
email: $scope.profile.email
phone: "+7#{$scope.profile.phone}"
notification:
email: $scope.profile.notification.email
sms: $scope.profile.notification.sms
news: $scope.profile.notification.news
security.updateUser(profile).catch (response) ->
$scope.errorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingProfile = false
ProgressBar.stop()
)
$scope.updateUserPasswords = ->
ProgressBar.start()
$scope.loadingPasswords = true
$scope.passwordErrorList = []
passwords =
currentPassword: $scope.password.current
plainPassword:
first: $scope.password.newOne
second: $scope.password.newOneRepeated
security.updateUserPasswords(passwords).then(
( -> resetPasswordModels()),
(response) -> $scope.passwordErrorList = Utility.toErrorList response.data.errors
).finally( ->
$scope.loadingPasswords = false
ProgressBar.stop()
)
$scope.updateCompany = ->
ProgressBar.start()
$scope.loadingCompany = true
$scope.companyErrorList = []
Companies.updateCompany($scope.company).catch (response) ->
$scope.companyErrorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingCompany = false
ProgressBar.stop()
)
]
| 56256 | angular.module('profile').controller 'ProfileCtrl', [
'$scope', '$location', 'security', 'Companies', 'ProgressBar', 'Utility', 'company',
($scope, $location, security, Companies, ProgressBar, Utility, company) ->
'use strict'
return unless security.isAuthenticated()
$scope.hasCompany = false
$scope.loadingProfile = false
$scope.loadingPasswords = false
$scope.loadingCompany = false
$scope.errorList = []
$scope.passwordErrorList = []
$scope.campaignErrorList = []
$scope.profile = security.currentUser
$scope.taxationSystems = Companies.getTaxationSystems()
$scope.company = company
resetPasswordModels = ->
$scope.password =
current: null
newOne: null
newOneRepeated: null
$scope.updateUserInfo = ->
ProgressBar.start()
$scope.loadingProfile = true
$scope.errorList = []
profile =
first_name: $scope.profile.firstName
surname: $scope.profile.lastName
email: $scope.profile.email
phone: "+7#{$scope.profile.phone}"
notification:
email: $scope.profile.notification.email
sms: $scope.profile.notification.sms
news: $scope.profile.notification.news
security.updateUser(profile).catch (response) ->
$scope.errorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingProfile = false
ProgressBar.stop()
)
$scope.updateUserPasswords = ->
ProgressBar.start()
$scope.loadingPasswords = true
$scope.passwordErrorList = []
passwords =
currentPassword: $scope.<PASSWORD>.current
plainPassword:
first: $scope.password.new<PASSWORD>
second: $scope.password.newOneRepeated
security.updateUserPasswords(passwords).then(
( -> resetPasswordModels()),
(response) -> $scope.passwordErrorList = Utility.toErrorList response.data.errors
).finally( ->
$scope.loadingPasswords = false
ProgressBar.stop()
)
$scope.updateCompany = ->
ProgressBar.start()
$scope.loadingCompany = true
$scope.companyErrorList = []
Companies.updateCompany($scope.company).catch (response) ->
$scope.companyErrorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingCompany = false
ProgressBar.stop()
)
]
| true | angular.module('profile').controller 'ProfileCtrl', [
'$scope', '$location', 'security', 'Companies', 'ProgressBar', 'Utility', 'company',
($scope, $location, security, Companies, ProgressBar, Utility, company) ->
'use strict'
return unless security.isAuthenticated()
$scope.hasCompany = false
$scope.loadingProfile = false
$scope.loadingPasswords = false
$scope.loadingCompany = false
$scope.errorList = []
$scope.passwordErrorList = []
$scope.campaignErrorList = []
$scope.profile = security.currentUser
$scope.taxationSystems = Companies.getTaxationSystems()
$scope.company = company
resetPasswordModels = ->
$scope.password =
current: null
newOne: null
newOneRepeated: null
$scope.updateUserInfo = ->
ProgressBar.start()
$scope.loadingProfile = true
$scope.errorList = []
profile =
first_name: $scope.profile.firstName
surname: $scope.profile.lastName
email: $scope.profile.email
phone: "+7#{$scope.profile.phone}"
notification:
email: $scope.profile.notification.email
sms: $scope.profile.notification.sms
news: $scope.profile.notification.news
security.updateUser(profile).catch (response) ->
$scope.errorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingProfile = false
ProgressBar.stop()
)
$scope.updateUserPasswords = ->
ProgressBar.start()
$scope.loadingPasswords = true
$scope.passwordErrorList = []
passwords =
currentPassword: $scope.PI:PASSWORD:<PASSWORD>END_PI.current
plainPassword:
first: $scope.password.newPI:PASSWORD:<PASSWORD>END_PI
second: $scope.password.newOneRepeated
security.updateUserPasswords(passwords).then(
( -> resetPasswordModels()),
(response) -> $scope.passwordErrorList = Utility.toErrorList response.data.errors
).finally( ->
$scope.loadingPasswords = false
ProgressBar.stop()
)
$scope.updateCompany = ->
ProgressBar.start()
$scope.loadingCompany = true
$scope.companyErrorList = []
Companies.updateCompany($scope.company).catch (response) ->
$scope.companyErrorList = Utility.toErrorList response.data.errors
.finally( ->
$scope.loadingCompany = false
ProgressBar.stop()
)
]
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9986402988433838,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/disabled/test-http-head-request.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world"
server = http.createServer((req, res) ->
res.writeHeader 200,
"Content-Length": body.length.toString()
"Content-Type": "text/plain"
console.log "method: " + req.method
res.write body unless req.method is "HEAD"
res.end()
return
)
server.listen common.PORT
gotEnd = false
server.on "listening", ->
request = http.request(
port: common.PORT
method: "HEAD"
path: "/"
, (response) ->
console.log "got response"
response.on "data", ->
process.exit 2
return
response.on "end", ->
process.exit 0
return
return
)
request.end()
return
#give a bit of time for the server to respond before we check it
setTimeout (->
process.exit 1
return
), 2000
| 2282 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world"
server = http.createServer((req, res) ->
res.writeHeader 200,
"Content-Length": body.length.toString()
"Content-Type": "text/plain"
console.log "method: " + req.method
res.write body unless req.method is "HEAD"
res.end()
return
)
server.listen common.PORT
gotEnd = false
server.on "listening", ->
request = http.request(
port: common.PORT
method: "HEAD"
path: "/"
, (response) ->
console.log "got response"
response.on "data", ->
process.exit 2
return
response.on "end", ->
process.exit 0
return
return
)
request.end()
return
#give a bit of time for the server to respond before we check it
setTimeout (->
process.exit 1
return
), 2000
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world"
server = http.createServer((req, res) ->
res.writeHeader 200,
"Content-Length": body.length.toString()
"Content-Type": "text/plain"
console.log "method: " + req.method
res.write body unless req.method is "HEAD"
res.end()
return
)
server.listen common.PORT
gotEnd = false
server.on "listening", ->
request = http.request(
port: common.PORT
method: "HEAD"
path: "/"
, (response) ->
console.log "got response"
response.on "data", ->
process.exit 2
return
response.on "end", ->
process.exit 0
return
return
)
request.end()
return
#give a bit of time for the server to respond before we check it
setTimeout (->
process.exit 1
return
), 2000
|
[
{
"context": "epPath\n\t\t@label = 'Meander'\n\t\t@description = \"\"\"As Karl Kerenyi pointed out, \"the meander is the figure of a laby",
"end": 478,
"score": 0.9993879199028015,
"start": 466,
"tag": "NAME",
"value": "Karl Kerenyi"
}
] | coffee/Items/Paths/PrecisePaths/Meander.coffee | arthursw/comme-un-dessein-client | 0 | define ['paper', 'R', 'Utils/Utils', 'Items/Paths/PrecisePaths/StepPath' ], (P, R, Utils, StepPath) ->
# Meander makes use of both the tangent and the normal of the control path to draw a spiral at each step
# Many different versions can be derived from this one (some inspiration can be found here:
# http://www.dreamstime.com/photos-images/meander-wave-ancient-greek-ornament.html )
class Meander extends StepPath
@label = 'Meander'
@description = """As Karl Kerenyi pointed out, "the meander is the figure of a labyrinth in linear form".
A meander or meandros (Greek: Μαίανδρος) is a decorative border constructed from a continuous line, shaped into a repeated motif.
Such a design is also called the Greek fret or Greek key design, although these are modern designations.
(source: http://en.wikipedia.org/wiki/Meander_(art))"""
@iconURL = "static/images/icons/inverted/squareSpiral.png"
# The thickness path adds 3 parameters in the options bar:
# step: a number which defines the size of the steps along the control path
# (@data.step is already defined in precise path, this will bind it to the options bar)
# thickness: the thickness of the spirals
# rsmooth: whether the path is smoothed or not (not that @data.smooth is already used
# to define if one can edit the control path handles or if they are automatically set)
@initializeParameters: ()->
parameters = super()
parameters['Parameters'] ?= {}
parameters['Parameters'].step =
type: 'slider'
label: 'Step'
min: 10
max: 100
default: 20
simplified: 20
step: 1
parameters['Parameters'].thickness =
type: 'slider'
label: 'Thickness'
min: 1
max: 30
default: 5
step: 1
parameters['Parameters'].rsmooth =
type: 'checkbox'
label: 'Smooth'
default: false
return parameters
@parameters = @initializeParameters()
@createTool(@)
beginDraw: ()->
@initializeDrawing(false)
@line = @addPath()
@spiral = @addPath()
return
updateDraw: (offset, step)->
if not step then return
point = @controlPath.getPointAt(offset)
normal = @controlPath.getNormalAt(offset).normalize()
tangent = normal.rotate(90)
@line.add(point)
@spiral.add(point.add(normal.multiply(@data.thickness)))
# line spiral
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
p1 = point.add(normal.multiply(@data.step))
@spiral.add(p1)
p2 = p1.add(tangent.multiply(@data.step-@data.thickness))
@spiral.add(p2)
p3 = p2.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p3)
p4 = p3.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p4)
p5 = p4.add(normal.multiply( @data.thickness ))
@spiral.add(p5)
p6 = p5.add(tangent.multiply( @data.step-4*@data.thickness ))
@spiral.add(p6)
p7 = p6.add(normal.multiply( @data.step-4*@data.thickness ))
@spiral.add(p7)
p8 = p7.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p8)
p9 = p8.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p9)
return
endDraw: ()->
if @data.rsmooth
@spiral.smooth()
@line.smooth()
return
return Meander
| 108076 | define ['paper', 'R', 'Utils/Utils', 'Items/Paths/PrecisePaths/StepPath' ], (P, R, Utils, StepPath) ->
# Meander makes use of both the tangent and the normal of the control path to draw a spiral at each step
# Many different versions can be derived from this one (some inspiration can be found here:
# http://www.dreamstime.com/photos-images/meander-wave-ancient-greek-ornament.html )
class Meander extends StepPath
@label = 'Meander'
@description = """As <NAME> pointed out, "the meander is the figure of a labyrinth in linear form".
A meander or meandros (Greek: Μαίανδρος) is a decorative border constructed from a continuous line, shaped into a repeated motif.
Such a design is also called the Greek fret or Greek key design, although these are modern designations.
(source: http://en.wikipedia.org/wiki/Meander_(art))"""
@iconURL = "static/images/icons/inverted/squareSpiral.png"
# The thickness path adds 3 parameters in the options bar:
# step: a number which defines the size of the steps along the control path
# (@data.step is already defined in precise path, this will bind it to the options bar)
# thickness: the thickness of the spirals
# rsmooth: whether the path is smoothed or not (not that @data.smooth is already used
# to define if one can edit the control path handles or if they are automatically set)
@initializeParameters: ()->
parameters = super()
parameters['Parameters'] ?= {}
parameters['Parameters'].step =
type: 'slider'
label: 'Step'
min: 10
max: 100
default: 20
simplified: 20
step: 1
parameters['Parameters'].thickness =
type: 'slider'
label: 'Thickness'
min: 1
max: 30
default: 5
step: 1
parameters['Parameters'].rsmooth =
type: 'checkbox'
label: 'Smooth'
default: false
return parameters
@parameters = @initializeParameters()
@createTool(@)
beginDraw: ()->
@initializeDrawing(false)
@line = @addPath()
@spiral = @addPath()
return
updateDraw: (offset, step)->
if not step then return
point = @controlPath.getPointAt(offset)
normal = @controlPath.getNormalAt(offset).normalize()
tangent = normal.rotate(90)
@line.add(point)
@spiral.add(point.add(normal.multiply(@data.thickness)))
# line spiral
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
p1 = point.add(normal.multiply(@data.step))
@spiral.add(p1)
p2 = p1.add(tangent.multiply(@data.step-@data.thickness))
@spiral.add(p2)
p3 = p2.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p3)
p4 = p3.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p4)
p5 = p4.add(normal.multiply( @data.thickness ))
@spiral.add(p5)
p6 = p5.add(tangent.multiply( @data.step-4*@data.thickness ))
@spiral.add(p6)
p7 = p6.add(normal.multiply( @data.step-4*@data.thickness ))
@spiral.add(p7)
p8 = p7.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p8)
p9 = p8.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p9)
return
endDraw: ()->
if @data.rsmooth
@spiral.smooth()
@line.smooth()
return
return Meander
| true | define ['paper', 'R', 'Utils/Utils', 'Items/Paths/PrecisePaths/StepPath' ], (P, R, Utils, StepPath) ->
# Meander makes use of both the tangent and the normal of the control path to draw a spiral at each step
# Many different versions can be derived from this one (some inspiration can be found here:
# http://www.dreamstime.com/photos-images/meander-wave-ancient-greek-ornament.html )
class Meander extends StepPath
@label = 'Meander'
@description = """As PI:NAME:<NAME>END_PI pointed out, "the meander is the figure of a labyrinth in linear form".
A meander or meandros (Greek: Μαίανδρος) is a decorative border constructed from a continuous line, shaped into a repeated motif.
Such a design is also called the Greek fret or Greek key design, although these are modern designations.
(source: http://en.wikipedia.org/wiki/Meander_(art))"""
@iconURL = "static/images/icons/inverted/squareSpiral.png"
# The thickness path adds 3 parameters in the options bar:
# step: a number which defines the size of the steps along the control path
# (@data.step is already defined in precise path, this will bind it to the options bar)
# thickness: the thickness of the spirals
# rsmooth: whether the path is smoothed or not (not that @data.smooth is already used
# to define if one can edit the control path handles or if they are automatically set)
@initializeParameters: ()->
parameters = super()
parameters['Parameters'] ?= {}
parameters['Parameters'].step =
type: 'slider'
label: 'Step'
min: 10
max: 100
default: 20
simplified: 20
step: 1
parameters['Parameters'].thickness =
type: 'slider'
label: 'Thickness'
min: 1
max: 30
default: 5
step: 1
parameters['Parameters'].rsmooth =
type: 'checkbox'
label: 'Smooth'
default: false
return parameters
@parameters = @initializeParameters()
@createTool(@)
beginDraw: ()->
@initializeDrawing(false)
@line = @addPath()
@spiral = @addPath()
return
updateDraw: (offset, step)->
if not step then return
point = @controlPath.getPointAt(offset)
normal = @controlPath.getNormalAt(offset).normalize()
tangent = normal.rotate(90)
@line.add(point)
@spiral.add(point.add(normal.multiply(@data.thickness)))
# line spiral
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
# | 9-----------8 |
# | | | |
# | | 4---5 | |
# | | | | | |
# | | | 6---7 |
# | | | |
# | | 3-----------2
# | |
# 0 0---------------1
# | |
p1 = point.add(normal.multiply(@data.step))
@spiral.add(p1)
p2 = p1.add(tangent.multiply(@data.step-@data.thickness))
@spiral.add(p2)
p3 = p2.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p3)
p4 = p3.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p4)
p5 = p4.add(normal.multiply( @data.thickness ))
@spiral.add(p5)
p6 = p5.add(tangent.multiply( @data.step-4*@data.thickness ))
@spiral.add(p6)
p7 = p6.add(normal.multiply( @data.step-4*@data.thickness ))
@spiral.add(p7)
p8 = p7.add(tangent.multiply( -(@data.step-3*@data.thickness) ))
@spiral.add(p8)
p9 = p8.add(normal.multiply( -(@data.step-2*@data.thickness) ))
@spiral.add(p9)
return
endDraw: ()->
if @data.rsmooth
@spiral.smooth()
@line.smooth()
return
return Meander
|
[
{
"context": " @initReady\n\n Post.callbacks.push\n name: 'Quick Reply'\n cb: @node\n\n initReady: ->\n $.off d, ",
"end": 287,
"score": 0.7379892468452454,
"start": 276,
"tag": "NAME",
"value": "Quick Reply"
},
{
"context": " textOnly\n mode: 'regist'\n ... | src/Posting/QR.coffee | ihavenoface/4chan-x | 4 | QR =
init: ->
return if !Conf['Quick Reply']
@db = new DataBoard 'yourPosts'
@posts = []
if Conf['Hide Original Post Form']
$.addClass doc, 'hide-original-post-form'
$.on d, '4chanXInitFinished', @initReady
Post.callbacks.push
name: 'Quick Reply'
cb: @node
initReady: ->
$.off d, '4chanXInitFinished', QR.initReady
QR.postingIsEnabled = !!$.id 'postForm'
return unless QR.postingIsEnabled
sc = $.el 'a',
className: 'qr-shortcut fa fa-comment-o'
title: 'Quick Reply'
href: 'javascript:;'
$.on sc, 'click', ->
$.event 'CloseMenu'
QR.open()
QR.nodes.com.focus()
Header.addShortcut sc, 2
<% if (type === 'crx') { %>
$.on d, 'paste', QR.paste
<% } %>
$.on d, 'dragover', QR.dragOver
$.on d, 'drop', QR.dropFile
$.on d, 'dragstart dragend', QR.drag
switch g.VIEW
when 'index'
$.on d, 'IndexRefresh', QR.generatePostableThreadsList
when 'thread'
$.on d, 'ThreadUpdate', ->
if g.DEAD
QR.abort()
else
QR.status()
return unless Conf['Persistent QR']
QR.open()
QR.hide() if Conf['Auto-Hide QR'] or g.VIEW is 'catalog' or g.VIEW is 'index' and Conf['Index Mode'] is 'catalog'
node: ->
if QR.db.get {boardID: @board.ID, threadID: @thread.ID, postID: @ID}
$.addClass @nodes.root, 'your-post'
$.on $('a[title="Reply to this post"]', @nodes.info), 'click', QR.quote
persist: ->
QR.open()
QR.hide() if Conf['Auto-Hide QR']
open: ->
if QR.nodes
QR.nodes.el.hidden = false
QR.unhide()
return
try
QR.dialog()
catch err
delete QR.nodes
Main.handleErrors
message: 'Quick Reply dialog creation crashed.'
error: err
close: ->
if QR.req
QR.abort()
return
QR.nodes.el.hidden = true
QR.cleanNotifications()
d.activeElement.blur()
$.rmClass QR.nodes.el, 'dump'
new QR.post true
for post in QR.posts.splice 0, QR.posts.length - 1
post.delete()
QR.cooldown.auto = false
QR.status()
focusin: ->
$.addClass QR.nodes.el, 'has-focus'
focusout: ->
<% if (type === 'crx') { %>
$.rmClass QR.nodes.el, 'has-focus'
<% } else { %>
$.queueTask ->
return if $.x 'ancestor::div[@id="qr"]', d.activeElement
$.rmClass QR.nodes.el, 'has-focus'
<% } %>
hide: ->
d.activeElement.blur()
$.addClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = true
unhide: ->
$.rmClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = false
toggleHide: ->
if @checked
QR.hide()
else
QR.unhide()
toggleSage: ->
{email} = QR.nodes
email.value = !/sage/i.test(email.value) and 'sage' or ''
error: (err) ->
QR.open()
if typeof err is 'string'
el = $.tn err
else
el = err
el.removeAttribute 'style'
if QR.captcha.isEnabled and /captcha|verification/i.test el.textContent
# Focus the captcha input on captcha error.
QR.captcha.nodes.input.focus()
notice = new Notice 'warning', el
QR.notifications.push notice
return unless Header.areNotificationsEnabled
notif = new Notification 'Quick reply warning',
body: el.textContent
icon: Favicon.logo
notif.onclick = -> window.focus()
<% if (type === 'crx') { %>
# Firefox automatically closes notifications
# so we can't control the onclose properly.
notif.onclose = -> notice.close()
notif.onshow = ->
setTimeout ->
notif.onclose = null
notif.close()
, 7 * $.SECOND
<% } %>
notifications: []
cleanNotifications: ->
for notification in QR.notifications
notification.close()
QR.notifications = []
status: ->
return unless QR.nodes
{thread} = QR.posts[0]
if thread isnt 'new' and g.threads["#{g.BOARD}.#{thread}"].isDead
value = 404
disabled = true
QR.cooldown.auto = false
value = if QR.req
QR.req.progress
else
QR.cooldown.seconds or value
{status} = QR.nodes
status.value = unless value
'Submit'
else if QR.cooldown.auto
"Auto #{value}"
else
value
status.disabled = disabled or false
quote: (e) ->
e?.preventDefault()
return unless QR.postingIsEnabled
sel = d.getSelection()
post = Get.postFromNode @
text = ">>#{post}\n"
if sel.toString().trim() and post is Get.postFromNode sel.anchorNode
range = sel.getRangeAt 0
frag = range.cloneContents()
ancestor = range.commonAncestorContainer
if ancestor.nodeName is '#text'
# Quoting the insides of a spoiler/code tag.
if $.x 'ancestor::s', ancestor
$.prepend frag, $.tn '[spoiler]'
$.add frag, $.tn '[/spoiler]'
if $.x 'ancestor::pre[contains(@class,"prettyprint")]', ancestor
$.prepend frag, $.tn '[code]'
$.add frag, $.tn '[/code]'
for node in $$ 'br', frag
$.replace node, $.tn '\n>' unless node is frag.lastChild
for node in $$ 's', frag
$.replace node, [$.tn('[spoiler]'), node.childNodes..., $.tn '[/spoiler]']
for node in $$ '.prettyprint', frag
$.replace node, [$.tn('[code]'), node.childNodes..., $.tn '[/code]']
text += ">#{frag.textContent.trim()}\n"
QR.open()
if QR.selected.isLocked
index = QR.posts.indexOf QR.selected
(QR.posts[index+1] or new QR.post()).select()
$.addClass QR.nodes.el, 'dump'
QR.cooldown.auto = true
{com, thread} = QR.nodes
thread.value = Get.threadFromNode @ unless com.value
caretPos = com.selectionStart
# Replace selection for text.
com.value = com.value[...caretPos] + text + com.value[com.selectionEnd..]
# Move the caret to the end of the new quote.
range = caretPos + text.length
com.setSelectionRange range, range
com.focus()
QR.selected.save com
QR.selected.save thread
characterCount: ->
counter = QR.nodes.charCount
count = QR.nodes.com.textLength
counter.textContent = count
counter.hidden = count < 1000
(if count > 1500 then $.addClass else $.rmClass) counter, 'warning'
drag: (e) ->
# Let it drag anything from the page.
toggle = if e.type is 'dragstart' then $.off else $.on
toggle d, 'dragover', QR.dragOver
toggle d, 'drop', QR.dropFile
dragOver: (e) ->
e.preventDefault()
e.dataTransfer.dropEffect = 'copy' # cursor feedback
dropFile: (e) ->
# Let it only handle files from the desktop.
return unless e.dataTransfer.files.length
e.preventDefault()
QR.open()
QR.handleFiles e.dataTransfer.files
paste: (e) ->
files = []
for item in e.clipboardData.items when item.kind is 'file'
blob = item.getAsFile()
blob.name = 'file'
blob.name += '.' + blob.type.split('/')[1] if blob.type
files.push blob
return unless files.length
QR.open()
QR.handleFiles files
$.addClass QR.nodes.el, 'dump'
handleBlob: (urlBlob, header, url) ->
name = url.substr url.lastIndexOf('/')+1, url.length
start = header.indexOf("Content-Type: ") + 14
endsc = header.substr(start, header.length).indexOf ';'
endnl = header.substr(start, header.length).indexOf('\n') - 1
end = endnl
if endsc isnt -1 and endsc < endnl
end = endsc
mime = header.substr start, end
blob = new Blob [urlBlob], {type: mime}
blob.name = url.substr url.lastIndexOf('/') + 1, url.length
name_start = header.indexOf('name="') + 6
if name_start - 6 isnt -1
name_end = header.substr(name_start, header.length).indexOf '"'
blob.name = header.substr name_start, name_end
return if blob.type is null
QR.error 'Unsupported file type.'
return unless blob.type in ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/x-shockwave-flash', '']
QR.error 'Unsupported file type.'
QR.handleFiles [blob]
handleUrl: ->
url = prompt 'Insert an url:'
return if url is null
<% if (type === 'crx') { %>
xhr = new XMLHttpRequest();
xhr.open 'GET', url, true
xhr.responseType = 'blob'
xhr.onload = (e) ->
if @readyState is @DONE && xhr.status is 200
QR.handleBlob @response, @getResponseHeader('Content-Type'), url
return
else
QR.error 'Can\'t load image.'
return
xhr.onerror = (e) ->
QR.error 'Can\'t load image.'
return
xhr.send()
return
<% } %>
<% if (type === 'userscript') { %>
GM_xmlhttpRequest {
method: "GET",
url: url,
overrideMimeType: 'text/plain; charset=x-user-defined',
onload: (xhr) ->
r = xhr.responseText
data = new Uint8Array r.length
i = 0
while i < r.length
data[i] = r.charCodeAt i
i++
QR.handleBlob data, xhr.responseHeaders, url
return
onerror: (xhr) ->
QR.error "Can't load image."
}
return
<% } %>
handleFiles: (files) ->
if @ isnt QR # file input
files = [@files...]
@value = null
return unless files.length
max = QR.nodes.fileInput.max
isSingle = files.length is 1
QR.cleanNotifications()
for file in files
QR.handleFile file, isSingle, max
$.addClass QR.nodes.el, 'dump' unless isSingle
handleFile: (file, isSingle, max) ->
if file.size > max
QR.error "#{file.name}: File too large (file: #{$.bytesToString file.size}, max: #{$.bytesToString max})."
return
if isSingle
post = QR.selected
else if (post = QR.posts[QR.posts.length - 1]).file
post = new QR.post()
if /^text/.test file.type
post.pasteText file
else
post.setFile file
openFileInput: ->
QR.nodes.fileInput.click()
generatePostableThreadsList: ->
return unless QR.nodes
list = QR.nodes.thread
options = [list.firstChild]
for thread of g.BOARD.threads
options.push $.el 'option',
value: thread
textContent: "Thread No.#{thread}"
val = list.value
$.rmAll list
$.add list, options
list.value = val
return unless list.value
# Fix the value if the option disappeared.
list.value = if g.VIEW is 'thread'
g.THREADID
else
'new'
dialog: ->
dialog = UI.dialog 'qr', 'top:0;right:0;', <%= importHTML('Posting/QR') %>
QR.nodes = nodes =
el: dialog
move: $ '.move', dialog
autohide: $ '#autohide', dialog
thread: $ 'select', dialog
close: $ '.close', dialog
form: $ 'form', dialog
dumpButton: $ '#dump-button', dialog
urlButton: $ '#url-button', dialog
name: $ '[data-name=name]', dialog
email: $ '[data-name=email]', dialog
sub: $ '[data-name=sub]', dialog
com: $ '[data-name=com]', dialog
dumpList: $ '#dump-list', dialog
proceed: $ '[name=qr-proceed]', dialog
addPost: $ '#add-post', dialog
charCount: $ '#char-count', dialog
fileSubmit: $ '#file-n-submit', dialog
fileButton: $ '#qr-file-button', dialog
filename: $ '#qr-filename', dialog
filesize: $ '#qr-filesize', dialog
fileRM: $ '#qr-filerm', dialog
spoiler: $ '#qr-file-spoiler', dialog
status: $ '[type=submit]', dialog
fileInput: $ '[type=file]', dialog
if Conf['Tab to Choose Files First']
$.add nodes.fileSubmit, nodes.status
$.get 'qr-proceed', false, (item) ->
nodes.proceed.checked = item['qr-proceed']
nodes.fileInput.max = $('input[name=MAX_FILE_SIZE]').value
QR.spoiler = !!$ 'input[name=spoiler]'
nodes.spoiler.hidden = !QR.spoiler
if g.BOARD.ID is 'f'
nodes.flashTag = $.el 'select',
name: 'filetag'
innerHTML: """
<option value=0>Hentai</option>
<option value=6>Porn</option>
<option value=1>Japanese</option>
<option value=2>Anime</option>
<option value=3>Game</option>
<option value=5>Loop</option>
<option value=4 selected>Other</option>
"""
nodes.flashTag.dataset.default = '4'
$.add nodes.form, nodes.flashTag
if flagSelector = $ '.flagSelector'
nodes.flag = flagSelector.cloneNode true
nodes.flag.dataset.name = 'flag'
nodes.flag.dataset.default = '0'
$.add nodes.form, nodes.flag
<% if (type === 'userscript') { %>
# XXX Firefox lacks focusin/focusout support.
for elm in $$ '*', QR.nodes.el
$.on elm, 'blur', QR.focusout
$.on elm, 'focus', QR.focusin
<% } %>
$.on dialog, 'focusin', QR.focusin
$.on dialog, 'focusout', QR.focusout
$.on nodes.fileButton, 'click', QR.openFileInput
$.on nodes.autohide, 'change', QR.toggleHide
$.on nodes.close, 'click', QR.close
$.on nodes.dumpButton, 'click', -> nodes.el.classList.toggle 'dump'
$.on nodes.urlButton, 'click', QR.handleUrl
$.on nodes.proceed, 'click', $.cb.checked
$.on nodes.addPost, 'click', -> new QR.post true
$.on nodes.form, 'submit', QR.submit
$.on nodes.fileRM, 'click', -> QR.selected.rmFile()
$.on nodes.spoiler, 'change', -> QR.selected.nodes.spoiler.click()
$.on nodes.fileInput, 'change', QR.handleFiles
# save selected post's data
save = -> QR.selected.save @
for name in ['thread', 'name', 'email', 'sub', 'com', 'filename', 'flag']
continue unless node = nodes[name]
event = if node.nodeName is 'SELECT' then 'change' else 'input'
$.on nodes[name], event, save
<% if (type === 'userscript') { %>
if Conf['Remember QR Size']
$.get 'QR Size', '', (item) ->
nodes.com.style.cssText = item['QR Size']
$.on nodes.com, 'mouseup', (e) ->
return if e.button isnt 0
$.set 'QR Size', @style.cssText
<% } %>
QR.generatePostableThreadsList()
QR.persona.init()
new QR.post true
QR.status()
QR.cooldown.init()
QR.captcha.init()
$.add d.body, dialog
# Create a custom event when the QR dialog is first initialized.
# Use it to extend the QR's functionalities, or for XTRM RICE.
$.event 'QRDialogCreation', null, dialog
submit: (e, dismiss) ->
e?.preventDefault()
if QR.req
QR.abort()
return
if QR.cooldown.seconds
QR.cooldown.auto = !QR.cooldown.auto
QR.status()
return
post = QR.posts[0]
post.forceSave()
if g.BOARD.ID is 'f'
filetag = QR.nodes.flashTag.value
threadID = post.thread
thread = g.BOARD.threads[threadID]
# prevent errors
if threadID is 'new'
threadID = null
if g.BOARD.ID is 'vg' and !post.sub
err = 'New threads require a subject.'
else unless post.file or textOnly = !!$ 'input[name=textonly]', $.id 'postForm'
err = 'No file selected.'
else if g.BOARD.threads[threadID].isClosed
err = 'You can\'t reply to this thread anymore.'
else unless post.com or post.file
err = 'No file selected.'
else if post.file and thread.fileLimit
err = 'Max limit of image replies has been reached.'
else if !dismiss and !post.file and m = post.com.match /pic(ture)? (un)?related/i
err = $.el 'span',
innerHTML: """
No file selected despite '#{m[0]}' in your post. <button>Dismiss</button>
"""
$.on ($ 'button', err), 'click', ->
QR.submit null, true
if QR.captcha.isEnabled and !err
{challenge, response} = QR.captcha.getOne()
err = 'No valid captcha.' unless response
QR.cleanNotifications()
if err
# stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
return
# Enable auto-posting if we have stuff to post, disable it otherwise.
QR.cooldown.auto = QR.posts.length > 1
if Conf['Auto-Hide QR'] and !QR.cooldown.auto
QR.hide()
if !QR.cooldown.auto and $.x 'ancestor::div[@id="qr"]', d.activeElement
# Unfocus the focused element if it is one within the QR and we're not auto-posting.
d.activeElement.blur()
com = if Conf['Markdown'] then Markdown.format post.com else post.com
post.lock()
formData =
resto: threadID
name: post.name
email: post.email
sub: post.sub
com: com
upfile: post.file
filetag: filetag
spoiler: post.spoiler
flag: post.flag
textonly: textOnly
mode: 'regist'
pwd: QR.persona.pwd
recaptcha_challenge_field: challenge
recaptcha_response_field: response
options =
responseType: 'document'
withCredentials: true
onload: QR.response
onerror: ->
# Connection error, or
# www.4chan.org/banned
delete QR.req
if QR.captcha.isEnabled
QR.captcha.destroy()
QR.captcha.setup()
post.unlock()
QR.cooldown.auto = false
QR.status()
QR.error $.el 'span',
innerHTML: """
Connection error. You may have been <a href=//www.4chan.org/banned target=_blank>banned</a>.
[<a href="https://github.com/MayhemYDG/4chan-x/wiki/FAQ#what-does-connection-error-you-may-have-been-banned-mean" target=_blank>FAQ</a>]
"""
extra =
form: $.formData formData
upCallbacks:
onload: ->
# Upload done, waiting for server response.
QR.req.isUploadFinished = true
QR.req.uploadEndTime = Date.now()
QR.req.progress = '...'
QR.status()
onprogress: (e) ->
# Uploading...
QR.req.progress = "#{Math.round e.loaded / e.total * 100}%"
QR.status()
QR.req = $.ajax $.id('postForm').parentNode.action, options, extra
# Starting to upload might take some time.
# Provide some feedback that we're starting to submit.
QR.req.uploadStartTime = Date.now()
QR.req.progress = '...'
QR.status()
response: ->
{req} = QR
delete QR.req
QR.captcha.destroy() if QR.captcha.isEnabled
post = QR.posts[0]
postsCount = QR.posts.length - 1
post.unlock()
resDoc = req.response
if ban = $ '.banType', resDoc # banned/warning
board = $('.board', resDoc).innerHTML
err = $.el 'span', innerHTML:
if ban.textContent.toLowerCase() is 'banned'
"""
You are banned on #{board}! ;_;<br>
Click <a href=//www.4chan.org/banned target=_blank>here</a> to see the reason.
"""
else
"""
You were issued a warning on #{board} as #{$('.nameBlock', resDoc).innerHTML}.<br>
Reason: #{$('.reason', resDoc).innerHTML}
"""
else if err = resDoc.getElementById 'errmsg' # error!
$('a', err)?.target = '_blank' # duplicate image link
else if resDoc.title isnt 'Post successful!'
err = 'Connection error with sys.4chan.org.'
else if req.status isnt 200
err = "Error #{req.statusText} (#{req.status})"
if err
if /captcha|verification/i.test(err.textContent) or err is 'Connection error with sys.4chan.org.'
# Remove the obnoxious 4chan Pass ad.
if /mistyped/i.test err.textContent
err = 'You seem to have mistyped the CAPTCHA.'
QR.cooldown.auto = false
# Too many frequent mistyped captchas will auto-ban you!
# On connection error, the post most likely didn't go through.
QR.cooldown.set delay: 2
else if err.textContent and m = err.textContent.match /wait(?:\s+(\d+)\s+minutes)?\s+(\d+)\s+second/i
QR.cooldown.auto = !QR.captcha.isEnabled
QR.cooldown.set delay: (m[1] or 0) * 60 + Number m[2]
else if err.textContent.match /duplicate\sfile/i
if QR.nodes.proceed.checked and postsCount
post.rm()
QR.cooldown.auto = true
QR.cooldown.set delay: 10
else
QR.cooldown.auto = false
else # stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
QR.captcha.setup() if QR.captcha.isEnabled
return
h1 = $ 'h1', resDoc
QR.cleanNotifications()
QR.notifications.push new Notice 'success', h1.textContent, 5
QR.persona.set post
[_, threadID, postID] = h1.nextSibling.textContent.match /thread:(\d+),no:(\d+)/
postID = +postID
threadID = +threadID or postID
isReply = threadID isnt postID
QR.db.set
boardID: g.BOARD.ID
threadID: threadID
postID: postID
val: true
# Post/upload confirmed as successful.
$.event 'QRPostSuccessful', {
boardID: g.BOARD.ID
threadID
postID
}
$.event 'QRPostSuccessful_', {boardID: g.BOARD.ID, threadID, postID}
# Enable auto-posting if we have stuff left to post, disable it otherwise.
QR.cooldown.auto = postsCount and isReply
QR.captcha.setup() if QR.captcha.isEnabled and QR.cooldown.auto
unless Conf['Persistent QR'] or QR.cooldown.auto
QR.close()
else
post.rm()
QR.cooldown.set {req, post, isReply, threadID}
URL = if threadID is postID # new thread
Build.path g.BOARD.ID, threadID
else if g.VIEW is 'index' and !QR.cooldown.auto and Conf['Open Post in New Tab'] # replying from the index
Build.path g.BOARD.ID, threadID, postID
if URL
if Conf['Open Post in New Tab']
$.open URL
else
window.location = URL
QR.status()
abort: ->
if QR.req and !QR.req.isUploadFinished
QR.req.abort()
delete QR.req
QR.posts[0].unlock()
QR.cooldown.auto = false
QR.notifications.push new Notice 'info', 'QR upload aborted.', 5
QR.status()
| 106382 | QR =
init: ->
return if !Conf['Quick Reply']
@db = new DataBoard 'yourPosts'
@posts = []
if Conf['Hide Original Post Form']
$.addClass doc, 'hide-original-post-form'
$.on d, '4chanXInitFinished', @initReady
Post.callbacks.push
name: '<NAME>'
cb: @node
initReady: ->
$.off d, '4chanXInitFinished', QR.initReady
QR.postingIsEnabled = !!$.id 'postForm'
return unless QR.postingIsEnabled
sc = $.el 'a',
className: 'qr-shortcut fa fa-comment-o'
title: 'Quick Reply'
href: 'javascript:;'
$.on sc, 'click', ->
$.event 'CloseMenu'
QR.open()
QR.nodes.com.focus()
Header.addShortcut sc, 2
<% if (type === 'crx') { %>
$.on d, 'paste', QR.paste
<% } %>
$.on d, 'dragover', QR.dragOver
$.on d, 'drop', QR.dropFile
$.on d, 'dragstart dragend', QR.drag
switch g.VIEW
when 'index'
$.on d, 'IndexRefresh', QR.generatePostableThreadsList
when 'thread'
$.on d, 'ThreadUpdate', ->
if g.DEAD
QR.abort()
else
QR.status()
return unless Conf['Persistent QR']
QR.open()
QR.hide() if Conf['Auto-Hide QR'] or g.VIEW is 'catalog' or g.VIEW is 'index' and Conf['Index Mode'] is 'catalog'
node: ->
if QR.db.get {boardID: @board.ID, threadID: @thread.ID, postID: @ID}
$.addClass @nodes.root, 'your-post'
$.on $('a[title="Reply to this post"]', @nodes.info), 'click', QR.quote
persist: ->
QR.open()
QR.hide() if Conf['Auto-Hide QR']
open: ->
if QR.nodes
QR.nodes.el.hidden = false
QR.unhide()
return
try
QR.dialog()
catch err
delete QR.nodes
Main.handleErrors
message: 'Quick Reply dialog creation crashed.'
error: err
close: ->
if QR.req
QR.abort()
return
QR.nodes.el.hidden = true
QR.cleanNotifications()
d.activeElement.blur()
$.rmClass QR.nodes.el, 'dump'
new QR.post true
for post in QR.posts.splice 0, QR.posts.length - 1
post.delete()
QR.cooldown.auto = false
QR.status()
focusin: ->
$.addClass QR.nodes.el, 'has-focus'
focusout: ->
<% if (type === 'crx') { %>
$.rmClass QR.nodes.el, 'has-focus'
<% } else { %>
$.queueTask ->
return if $.x 'ancestor::div[@id="qr"]', d.activeElement
$.rmClass QR.nodes.el, 'has-focus'
<% } %>
hide: ->
d.activeElement.blur()
$.addClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = true
unhide: ->
$.rmClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = false
toggleHide: ->
if @checked
QR.hide()
else
QR.unhide()
toggleSage: ->
{email} = QR.nodes
email.value = !/sage/i.test(email.value) and 'sage' or ''
error: (err) ->
QR.open()
if typeof err is 'string'
el = $.tn err
else
el = err
el.removeAttribute 'style'
if QR.captcha.isEnabled and /captcha|verification/i.test el.textContent
# Focus the captcha input on captcha error.
QR.captcha.nodes.input.focus()
notice = new Notice 'warning', el
QR.notifications.push notice
return unless Header.areNotificationsEnabled
notif = new Notification 'Quick reply warning',
body: el.textContent
icon: Favicon.logo
notif.onclick = -> window.focus()
<% if (type === 'crx') { %>
# Firefox automatically closes notifications
# so we can't control the onclose properly.
notif.onclose = -> notice.close()
notif.onshow = ->
setTimeout ->
notif.onclose = null
notif.close()
, 7 * $.SECOND
<% } %>
notifications: []
cleanNotifications: ->
for notification in QR.notifications
notification.close()
QR.notifications = []
status: ->
return unless QR.nodes
{thread} = QR.posts[0]
if thread isnt 'new' and g.threads["#{g.BOARD}.#{thread}"].isDead
value = 404
disabled = true
QR.cooldown.auto = false
value = if QR.req
QR.req.progress
else
QR.cooldown.seconds or value
{status} = QR.nodes
status.value = unless value
'Submit'
else if QR.cooldown.auto
"Auto #{value}"
else
value
status.disabled = disabled or false
quote: (e) ->
e?.preventDefault()
return unless QR.postingIsEnabled
sel = d.getSelection()
post = Get.postFromNode @
text = ">>#{post}\n"
if sel.toString().trim() and post is Get.postFromNode sel.anchorNode
range = sel.getRangeAt 0
frag = range.cloneContents()
ancestor = range.commonAncestorContainer
if ancestor.nodeName is '#text'
# Quoting the insides of a spoiler/code tag.
if $.x 'ancestor::s', ancestor
$.prepend frag, $.tn '[spoiler]'
$.add frag, $.tn '[/spoiler]'
if $.x 'ancestor::pre[contains(@class,"prettyprint")]', ancestor
$.prepend frag, $.tn '[code]'
$.add frag, $.tn '[/code]'
for node in $$ 'br', frag
$.replace node, $.tn '\n>' unless node is frag.lastChild
for node in $$ 's', frag
$.replace node, [$.tn('[spoiler]'), node.childNodes..., $.tn '[/spoiler]']
for node in $$ '.prettyprint', frag
$.replace node, [$.tn('[code]'), node.childNodes..., $.tn '[/code]']
text += ">#{frag.textContent.trim()}\n"
QR.open()
if QR.selected.isLocked
index = QR.posts.indexOf QR.selected
(QR.posts[index+1] or new QR.post()).select()
$.addClass QR.nodes.el, 'dump'
QR.cooldown.auto = true
{com, thread} = QR.nodes
thread.value = Get.threadFromNode @ unless com.value
caretPos = com.selectionStart
# Replace selection for text.
com.value = com.value[...caretPos] + text + com.value[com.selectionEnd..]
# Move the caret to the end of the new quote.
range = caretPos + text.length
com.setSelectionRange range, range
com.focus()
QR.selected.save com
QR.selected.save thread
characterCount: ->
counter = QR.nodes.charCount
count = QR.nodes.com.textLength
counter.textContent = count
counter.hidden = count < 1000
(if count > 1500 then $.addClass else $.rmClass) counter, 'warning'
drag: (e) ->
# Let it drag anything from the page.
toggle = if e.type is 'dragstart' then $.off else $.on
toggle d, 'dragover', QR.dragOver
toggle d, 'drop', QR.dropFile
dragOver: (e) ->
e.preventDefault()
e.dataTransfer.dropEffect = 'copy' # cursor feedback
dropFile: (e) ->
# Let it only handle files from the desktop.
return unless e.dataTransfer.files.length
e.preventDefault()
QR.open()
QR.handleFiles e.dataTransfer.files
paste: (e) ->
files = []
for item in e.clipboardData.items when item.kind is 'file'
blob = item.getAsFile()
blob.name = 'file'
blob.name += '.' + blob.type.split('/')[1] if blob.type
files.push blob
return unless files.length
QR.open()
QR.handleFiles files
$.addClass QR.nodes.el, 'dump'
handleBlob: (urlBlob, header, url) ->
name = url.substr url.lastIndexOf('/')+1, url.length
start = header.indexOf("Content-Type: ") + 14
endsc = header.substr(start, header.length).indexOf ';'
endnl = header.substr(start, header.length).indexOf('\n') - 1
end = endnl
if endsc isnt -1 and endsc < endnl
end = endsc
mime = header.substr start, end
blob = new Blob [urlBlob], {type: mime}
blob.name = url.substr url.lastIndexOf('/') + 1, url.length
name_start = header.indexOf('name="') + 6
if name_start - 6 isnt -1
name_end = header.substr(name_start, header.length).indexOf '"'
blob.name = header.substr name_start, name_end
return if blob.type is null
QR.error 'Unsupported file type.'
return unless blob.type in ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/x-shockwave-flash', '']
QR.error 'Unsupported file type.'
QR.handleFiles [blob]
handleUrl: ->
url = prompt 'Insert an url:'
return if url is null
<% if (type === 'crx') { %>
xhr = new XMLHttpRequest();
xhr.open 'GET', url, true
xhr.responseType = 'blob'
xhr.onload = (e) ->
if @readyState is @DONE && xhr.status is 200
QR.handleBlob @response, @getResponseHeader('Content-Type'), url
return
else
QR.error 'Can\'t load image.'
return
xhr.onerror = (e) ->
QR.error 'Can\'t load image.'
return
xhr.send()
return
<% } %>
<% if (type === 'userscript') { %>
GM_xmlhttpRequest {
method: "GET",
url: url,
overrideMimeType: 'text/plain; charset=x-user-defined',
onload: (xhr) ->
r = xhr.responseText
data = new Uint8Array r.length
i = 0
while i < r.length
data[i] = r.charCodeAt i
i++
QR.handleBlob data, xhr.responseHeaders, url
return
onerror: (xhr) ->
QR.error "Can't load image."
}
return
<% } %>
handleFiles: (files) ->
if @ isnt QR # file input
files = [@files...]
@value = null
return unless files.length
max = QR.nodes.fileInput.max
isSingle = files.length is 1
QR.cleanNotifications()
for file in files
QR.handleFile file, isSingle, max
$.addClass QR.nodes.el, 'dump' unless isSingle
handleFile: (file, isSingle, max) ->
if file.size > max
QR.error "#{file.name}: File too large (file: #{$.bytesToString file.size}, max: #{$.bytesToString max})."
return
if isSingle
post = QR.selected
else if (post = QR.posts[QR.posts.length - 1]).file
post = new QR.post()
if /^text/.test file.type
post.pasteText file
else
post.setFile file
openFileInput: ->
QR.nodes.fileInput.click()
generatePostableThreadsList: ->
return unless QR.nodes
list = QR.nodes.thread
options = [list.firstChild]
for thread of g.BOARD.threads
options.push $.el 'option',
value: thread
textContent: "Thread No.#{thread}"
val = list.value
$.rmAll list
$.add list, options
list.value = val
return unless list.value
# Fix the value if the option disappeared.
list.value = if g.VIEW is 'thread'
g.THREADID
else
'new'
dialog: ->
dialog = UI.dialog 'qr', 'top:0;right:0;', <%= importHTML('Posting/QR') %>
QR.nodes = nodes =
el: dialog
move: $ '.move', dialog
autohide: $ '#autohide', dialog
thread: $ 'select', dialog
close: $ '.close', dialog
form: $ 'form', dialog
dumpButton: $ '#dump-button', dialog
urlButton: $ '#url-button', dialog
name: $ '[data-name=name]', dialog
email: $ '[data-name=email]', dialog
sub: $ '[data-name=sub]', dialog
com: $ '[data-name=com]', dialog
dumpList: $ '#dump-list', dialog
proceed: $ '[name=qr-proceed]', dialog
addPost: $ '#add-post', dialog
charCount: $ '#char-count', dialog
fileSubmit: $ '#file-n-submit', dialog
fileButton: $ '#qr-file-button', dialog
filename: $ '#qr-filename', dialog
filesize: $ '#qr-filesize', dialog
fileRM: $ '#qr-filerm', dialog
spoiler: $ '#qr-file-spoiler', dialog
status: $ '[type=submit]', dialog
fileInput: $ '[type=file]', dialog
if Conf['Tab to Choose Files First']
$.add nodes.fileSubmit, nodes.status
$.get 'qr-proceed', false, (item) ->
nodes.proceed.checked = item['qr-proceed']
nodes.fileInput.max = $('input[name=MAX_FILE_SIZE]').value
QR.spoiler = !!$ 'input[name=spoiler]'
nodes.spoiler.hidden = !QR.spoiler
if g.BOARD.ID is 'f'
nodes.flashTag = $.el 'select',
name: 'filetag'
innerHTML: """
<option value=0>Hentai</option>
<option value=6>Porn</option>
<option value=1>Japanese</option>
<option value=2>Anime</option>
<option value=3>Game</option>
<option value=5>Loop</option>
<option value=4 selected>Other</option>
"""
nodes.flashTag.dataset.default = '4'
$.add nodes.form, nodes.flashTag
if flagSelector = $ '.flagSelector'
nodes.flag = flagSelector.cloneNode true
nodes.flag.dataset.name = 'flag'
nodes.flag.dataset.default = '0'
$.add nodes.form, nodes.flag
<% if (type === 'userscript') { %>
# XXX Firefox lacks focusin/focusout support.
for elm in $$ '*', QR.nodes.el
$.on elm, 'blur', QR.focusout
$.on elm, 'focus', QR.focusin
<% } %>
$.on dialog, 'focusin', QR.focusin
$.on dialog, 'focusout', QR.focusout
$.on nodes.fileButton, 'click', QR.openFileInput
$.on nodes.autohide, 'change', QR.toggleHide
$.on nodes.close, 'click', QR.close
$.on nodes.dumpButton, 'click', -> nodes.el.classList.toggle 'dump'
$.on nodes.urlButton, 'click', QR.handleUrl
$.on nodes.proceed, 'click', $.cb.checked
$.on nodes.addPost, 'click', -> new QR.post true
$.on nodes.form, 'submit', QR.submit
$.on nodes.fileRM, 'click', -> QR.selected.rmFile()
$.on nodes.spoiler, 'change', -> QR.selected.nodes.spoiler.click()
$.on nodes.fileInput, 'change', QR.handleFiles
# save selected post's data
save = -> QR.selected.save @
for name in ['thread', 'name', 'email', 'sub', 'com', 'filename', 'flag']
continue unless node = nodes[name]
event = if node.nodeName is 'SELECT' then 'change' else 'input'
$.on nodes[name], event, save
<% if (type === 'userscript') { %>
if Conf['Remember QR Size']
$.get 'QR Size', '', (item) ->
nodes.com.style.cssText = item['QR Size']
$.on nodes.com, 'mouseup', (e) ->
return if e.button isnt 0
$.set 'QR Size', @style.cssText
<% } %>
QR.generatePostableThreadsList()
QR.persona.init()
new QR.post true
QR.status()
QR.cooldown.init()
QR.captcha.init()
$.add d.body, dialog
# Create a custom event when the QR dialog is first initialized.
# Use it to extend the QR's functionalities, or for XTRM RICE.
$.event 'QRDialogCreation', null, dialog
submit: (e, dismiss) ->
e?.preventDefault()
if QR.req
QR.abort()
return
if QR.cooldown.seconds
QR.cooldown.auto = !QR.cooldown.auto
QR.status()
return
post = QR.posts[0]
post.forceSave()
if g.BOARD.ID is 'f'
filetag = QR.nodes.flashTag.value
threadID = post.thread
thread = g.BOARD.threads[threadID]
# prevent errors
if threadID is 'new'
threadID = null
if g.BOARD.ID is 'vg' and !post.sub
err = 'New threads require a subject.'
else unless post.file or textOnly = !!$ 'input[name=textonly]', $.id 'postForm'
err = 'No file selected.'
else if g.BOARD.threads[threadID].isClosed
err = 'You can\'t reply to this thread anymore.'
else unless post.com or post.file
err = 'No file selected.'
else if post.file and thread.fileLimit
err = 'Max limit of image replies has been reached.'
else if !dismiss and !post.file and m = post.com.match /pic(ture)? (un)?related/i
err = $.el 'span',
innerHTML: """
No file selected despite '#{m[0]}' in your post. <button>Dismiss</button>
"""
$.on ($ 'button', err), 'click', ->
QR.submit null, true
if QR.captcha.isEnabled and !err
{challenge, response} = QR.captcha.getOne()
err = 'No valid captcha.' unless response
QR.cleanNotifications()
if err
# stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
return
# Enable auto-posting if we have stuff to post, disable it otherwise.
QR.cooldown.auto = QR.posts.length > 1
if Conf['Auto-Hide QR'] and !QR.cooldown.auto
QR.hide()
if !QR.cooldown.auto and $.x 'ancestor::div[@id="qr"]', d.activeElement
# Unfocus the focused element if it is one within the QR and we're not auto-posting.
d.activeElement.blur()
com = if Conf['Markdown'] then Markdown.format post.com else post.com
post.lock()
formData =
resto: threadID
name: post.name
email: post.email
sub: post.sub
com: com
upfile: post.file
filetag: filetag
spoiler: post.spoiler
flag: post.flag
textonly: textOnly
mode: 'regist'
pwd: <PASSWORD>
recaptcha_challenge_field: challenge
recaptcha_response_field: response
options =
responseType: 'document'
withCredentials: true
onload: QR.response
onerror: ->
# Connection error, or
# www.4chan.org/banned
delete QR.req
if QR.captcha.isEnabled
QR.captcha.destroy()
QR.captcha.setup()
post.unlock()
QR.cooldown.auto = false
QR.status()
QR.error $.el 'span',
innerHTML: """
Connection error. You may have been <a href=//www.4chan.org/banned target=_blank>banned</a>.
[<a href="https://github.com/MayhemYDG/4chan-x/wiki/FAQ#what-does-connection-error-you-may-have-been-banned-mean" target=_blank>FAQ</a>]
"""
extra =
form: $.formData formData
upCallbacks:
onload: ->
# Upload done, waiting for server response.
QR.req.isUploadFinished = true
QR.req.uploadEndTime = Date.now()
QR.req.progress = '...'
QR.status()
onprogress: (e) ->
# Uploading...
QR.req.progress = "#{Math.round e.loaded / e.total * 100}%"
QR.status()
QR.req = $.ajax $.id('postForm').parentNode.action, options, extra
# Starting to upload might take some time.
# Provide some feedback that we're starting to submit.
QR.req.uploadStartTime = Date.now()
QR.req.progress = '...'
QR.status()
response: ->
{req} = QR
delete QR.req
QR.captcha.destroy() if QR.captcha.isEnabled
post = QR.posts[0]
postsCount = QR.posts.length - 1
post.unlock()
resDoc = req.response
if ban = $ '.banType', resDoc # banned/warning
board = $('.board', resDoc).innerHTML
err = $.el 'span', innerHTML:
if ban.textContent.toLowerCase() is 'banned'
"""
You are banned on #{board}! ;_;<br>
Click <a href=//www.4chan.org/banned target=_blank>here</a> to see the reason.
"""
else
"""
You were issued a warning on #{board} as #{$('.nameBlock', resDoc).innerHTML}.<br>
Reason: #{$('.reason', resDoc).innerHTML}
"""
else if err = resDoc.getElementById 'errmsg' # error!
$('a', err)?.target = '_blank' # duplicate image link
else if resDoc.title isnt 'Post successful!'
err = 'Connection error with sys.4chan.org.'
else if req.status isnt 200
err = "Error #{req.statusText} (#{req.status})"
if err
if /captcha|verification/i.test(err.textContent) or err is 'Connection error with sys.4chan.org.'
# Remove the obnoxious 4chan Pass ad.
if /mistyped/i.test err.textContent
err = 'You seem to have mistyped the CAPTCHA.'
QR.cooldown.auto = false
# Too many frequent mistyped captchas will auto-ban you!
# On connection error, the post most likely didn't go through.
QR.cooldown.set delay: 2
else if err.textContent and m = err.textContent.match /wait(?:\s+(\d+)\s+minutes)?\s+(\d+)\s+second/i
QR.cooldown.auto = !QR.captcha.isEnabled
QR.cooldown.set delay: (m[1] or 0) * 60 + Number m[2]
else if err.textContent.match /duplicate\sfile/i
if QR.nodes.proceed.checked and postsCount
post.rm()
QR.cooldown.auto = true
QR.cooldown.set delay: 10
else
QR.cooldown.auto = false
else # stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
QR.captcha.setup() if QR.captcha.isEnabled
return
h1 = $ 'h1', resDoc
QR.cleanNotifications()
QR.notifications.push new Notice 'success', h1.textContent, 5
QR.persona.set post
[_, threadID, postID] = h1.nextSibling.textContent.match /thread:(\d+),no:(\d+)/
postID = +postID
threadID = +threadID or postID
isReply = threadID isnt postID
QR.db.set
boardID: g.BOARD.ID
threadID: threadID
postID: postID
val: true
# Post/upload confirmed as successful.
$.event 'QRPostSuccessful', {
boardID: g.BOARD.ID
threadID
postID
}
$.event 'QRPostSuccessful_', {boardID: g.BOARD.ID, threadID, postID}
# Enable auto-posting if we have stuff left to post, disable it otherwise.
QR.cooldown.auto = postsCount and isReply
QR.captcha.setup() if QR.captcha.isEnabled and QR.cooldown.auto
unless Conf['Persistent QR'] or QR.cooldown.auto
QR.close()
else
post.rm()
QR.cooldown.set {req, post, isReply, threadID}
URL = if threadID is postID # new thread
Build.path g.BOARD.ID, threadID
else if g.VIEW is 'index' and !QR.cooldown.auto and Conf['Open Post in New Tab'] # replying from the index
Build.path g.BOARD.ID, threadID, postID
if URL
if Conf['Open Post in New Tab']
$.open URL
else
window.location = URL
QR.status()
abort: ->
if QR.req and !QR.req.isUploadFinished
QR.req.abort()
delete QR.req
QR.posts[0].unlock()
QR.cooldown.auto = false
QR.notifications.push new Notice 'info', 'QR upload aborted.', 5
QR.status()
| true | QR =
init: ->
return if !Conf['Quick Reply']
@db = new DataBoard 'yourPosts'
@posts = []
if Conf['Hide Original Post Form']
$.addClass doc, 'hide-original-post-form'
$.on d, '4chanXInitFinished', @initReady
Post.callbacks.push
name: 'PI:NAME:<NAME>END_PI'
cb: @node
initReady: ->
$.off d, '4chanXInitFinished', QR.initReady
QR.postingIsEnabled = !!$.id 'postForm'
return unless QR.postingIsEnabled
sc = $.el 'a',
className: 'qr-shortcut fa fa-comment-o'
title: 'Quick Reply'
href: 'javascript:;'
$.on sc, 'click', ->
$.event 'CloseMenu'
QR.open()
QR.nodes.com.focus()
Header.addShortcut sc, 2
<% if (type === 'crx') { %>
$.on d, 'paste', QR.paste
<% } %>
$.on d, 'dragover', QR.dragOver
$.on d, 'drop', QR.dropFile
$.on d, 'dragstart dragend', QR.drag
switch g.VIEW
when 'index'
$.on d, 'IndexRefresh', QR.generatePostableThreadsList
when 'thread'
$.on d, 'ThreadUpdate', ->
if g.DEAD
QR.abort()
else
QR.status()
return unless Conf['Persistent QR']
QR.open()
QR.hide() if Conf['Auto-Hide QR'] or g.VIEW is 'catalog' or g.VIEW is 'index' and Conf['Index Mode'] is 'catalog'
node: ->
if QR.db.get {boardID: @board.ID, threadID: @thread.ID, postID: @ID}
$.addClass @nodes.root, 'your-post'
$.on $('a[title="Reply to this post"]', @nodes.info), 'click', QR.quote
persist: ->
QR.open()
QR.hide() if Conf['Auto-Hide QR']
open: ->
if QR.nodes
QR.nodes.el.hidden = false
QR.unhide()
return
try
QR.dialog()
catch err
delete QR.nodes
Main.handleErrors
message: 'Quick Reply dialog creation crashed.'
error: err
close: ->
if QR.req
QR.abort()
return
QR.nodes.el.hidden = true
QR.cleanNotifications()
d.activeElement.blur()
$.rmClass QR.nodes.el, 'dump'
new QR.post true
for post in QR.posts.splice 0, QR.posts.length - 1
post.delete()
QR.cooldown.auto = false
QR.status()
focusin: ->
$.addClass QR.nodes.el, 'has-focus'
focusout: ->
<% if (type === 'crx') { %>
$.rmClass QR.nodes.el, 'has-focus'
<% } else { %>
$.queueTask ->
return if $.x 'ancestor::div[@id="qr"]', d.activeElement
$.rmClass QR.nodes.el, 'has-focus'
<% } %>
hide: ->
d.activeElement.blur()
$.addClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = true
unhide: ->
$.rmClass QR.nodes.el, 'autohide'
QR.nodes.autohide.checked = false
toggleHide: ->
if @checked
QR.hide()
else
QR.unhide()
toggleSage: ->
{email} = QR.nodes
email.value = !/sage/i.test(email.value) and 'sage' or ''
error: (err) ->
QR.open()
if typeof err is 'string'
el = $.tn err
else
el = err
el.removeAttribute 'style'
if QR.captcha.isEnabled and /captcha|verification/i.test el.textContent
# Focus the captcha input on captcha error.
QR.captcha.nodes.input.focus()
notice = new Notice 'warning', el
QR.notifications.push notice
return unless Header.areNotificationsEnabled
notif = new Notification 'Quick reply warning',
body: el.textContent
icon: Favicon.logo
notif.onclick = -> window.focus()
<% if (type === 'crx') { %>
# Firefox automatically closes notifications
# so we can't control the onclose properly.
notif.onclose = -> notice.close()
notif.onshow = ->
setTimeout ->
notif.onclose = null
notif.close()
, 7 * $.SECOND
<% } %>
notifications: []
cleanNotifications: ->
for notification in QR.notifications
notification.close()
QR.notifications = []
status: ->
return unless QR.nodes
{thread} = QR.posts[0]
if thread isnt 'new' and g.threads["#{g.BOARD}.#{thread}"].isDead
value = 404
disabled = true
QR.cooldown.auto = false
value = if QR.req
QR.req.progress
else
QR.cooldown.seconds or value
{status} = QR.nodes
status.value = unless value
'Submit'
else if QR.cooldown.auto
"Auto #{value}"
else
value
status.disabled = disabled or false
quote: (e) ->
e?.preventDefault()
return unless QR.postingIsEnabled
sel = d.getSelection()
post = Get.postFromNode @
text = ">>#{post}\n"
if sel.toString().trim() and post is Get.postFromNode sel.anchorNode
range = sel.getRangeAt 0
frag = range.cloneContents()
ancestor = range.commonAncestorContainer
if ancestor.nodeName is '#text'
# Quoting the insides of a spoiler/code tag.
if $.x 'ancestor::s', ancestor
$.prepend frag, $.tn '[spoiler]'
$.add frag, $.tn '[/spoiler]'
if $.x 'ancestor::pre[contains(@class,"prettyprint")]', ancestor
$.prepend frag, $.tn '[code]'
$.add frag, $.tn '[/code]'
for node in $$ 'br', frag
$.replace node, $.tn '\n>' unless node is frag.lastChild
for node in $$ 's', frag
$.replace node, [$.tn('[spoiler]'), node.childNodes..., $.tn '[/spoiler]']
for node in $$ '.prettyprint', frag
$.replace node, [$.tn('[code]'), node.childNodes..., $.tn '[/code]']
text += ">#{frag.textContent.trim()}\n"
QR.open()
if QR.selected.isLocked
index = QR.posts.indexOf QR.selected
(QR.posts[index+1] or new QR.post()).select()
$.addClass QR.nodes.el, 'dump'
QR.cooldown.auto = true
{com, thread} = QR.nodes
thread.value = Get.threadFromNode @ unless com.value
caretPos = com.selectionStart
# Replace selection for text.
com.value = com.value[...caretPos] + text + com.value[com.selectionEnd..]
# Move the caret to the end of the new quote.
range = caretPos + text.length
com.setSelectionRange range, range
com.focus()
QR.selected.save com
QR.selected.save thread
characterCount: ->
counter = QR.nodes.charCount
count = QR.nodes.com.textLength
counter.textContent = count
counter.hidden = count < 1000
(if count > 1500 then $.addClass else $.rmClass) counter, 'warning'
drag: (e) ->
# Let it drag anything from the page.
toggle = if e.type is 'dragstart' then $.off else $.on
toggle d, 'dragover', QR.dragOver
toggle d, 'drop', QR.dropFile
dragOver: (e) ->
e.preventDefault()
e.dataTransfer.dropEffect = 'copy' # cursor feedback
dropFile: (e) ->
# Let it only handle files from the desktop.
return unless e.dataTransfer.files.length
e.preventDefault()
QR.open()
QR.handleFiles e.dataTransfer.files
paste: (e) ->
files = []
for item in e.clipboardData.items when item.kind is 'file'
blob = item.getAsFile()
blob.name = 'file'
blob.name += '.' + blob.type.split('/')[1] if blob.type
files.push blob
return unless files.length
QR.open()
QR.handleFiles files
$.addClass QR.nodes.el, 'dump'
handleBlob: (urlBlob, header, url) ->
name = url.substr url.lastIndexOf('/')+1, url.length
start = header.indexOf("Content-Type: ") + 14
endsc = header.substr(start, header.length).indexOf ';'
endnl = header.substr(start, header.length).indexOf('\n') - 1
end = endnl
if endsc isnt -1 and endsc < endnl
end = endsc
mime = header.substr start, end
blob = new Blob [urlBlob], {type: mime}
blob.name = url.substr url.lastIndexOf('/') + 1, url.length
name_start = header.indexOf('name="') + 6
if name_start - 6 isnt -1
name_end = header.substr(name_start, header.length).indexOf '"'
blob.name = header.substr name_start, name_end
return if blob.type is null
QR.error 'Unsupported file type.'
return unless blob.type in ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/x-shockwave-flash', '']
QR.error 'Unsupported file type.'
QR.handleFiles [blob]
handleUrl: ->
url = prompt 'Insert an url:'
return if url is null
<% if (type === 'crx') { %>
xhr = new XMLHttpRequest();
xhr.open 'GET', url, true
xhr.responseType = 'blob'
xhr.onload = (e) ->
if @readyState is @DONE && xhr.status is 200
QR.handleBlob @response, @getResponseHeader('Content-Type'), url
return
else
QR.error 'Can\'t load image.'
return
xhr.onerror = (e) ->
QR.error 'Can\'t load image.'
return
xhr.send()
return
<% } %>
<% if (type === 'userscript') { %>
GM_xmlhttpRequest {
method: "GET",
url: url,
overrideMimeType: 'text/plain; charset=x-user-defined',
onload: (xhr) ->
r = xhr.responseText
data = new Uint8Array r.length
i = 0
while i < r.length
data[i] = r.charCodeAt i
i++
QR.handleBlob data, xhr.responseHeaders, url
return
onerror: (xhr) ->
QR.error "Can't load image."
}
return
<% } %>
handleFiles: (files) ->
if @ isnt QR # file input
files = [@files...]
@value = null
return unless files.length
max = QR.nodes.fileInput.max
isSingle = files.length is 1
QR.cleanNotifications()
for file in files
QR.handleFile file, isSingle, max
$.addClass QR.nodes.el, 'dump' unless isSingle
handleFile: (file, isSingle, max) ->
if file.size > max
QR.error "#{file.name}: File too large (file: #{$.bytesToString file.size}, max: #{$.bytesToString max})."
return
if isSingle
post = QR.selected
else if (post = QR.posts[QR.posts.length - 1]).file
post = new QR.post()
if /^text/.test file.type
post.pasteText file
else
post.setFile file
openFileInput: ->
QR.nodes.fileInput.click()
generatePostableThreadsList: ->
return unless QR.nodes
list = QR.nodes.thread
options = [list.firstChild]
for thread of g.BOARD.threads
options.push $.el 'option',
value: thread
textContent: "Thread No.#{thread}"
val = list.value
$.rmAll list
$.add list, options
list.value = val
return unless list.value
# Fix the value if the option disappeared.
list.value = if g.VIEW is 'thread'
g.THREADID
else
'new'
dialog: ->
dialog = UI.dialog 'qr', 'top:0;right:0;', <%= importHTML('Posting/QR') %>
QR.nodes = nodes =
el: dialog
move: $ '.move', dialog
autohide: $ '#autohide', dialog
thread: $ 'select', dialog
close: $ '.close', dialog
form: $ 'form', dialog
dumpButton: $ '#dump-button', dialog
urlButton: $ '#url-button', dialog
name: $ '[data-name=name]', dialog
email: $ '[data-name=email]', dialog
sub: $ '[data-name=sub]', dialog
com: $ '[data-name=com]', dialog
dumpList: $ '#dump-list', dialog
proceed: $ '[name=qr-proceed]', dialog
addPost: $ '#add-post', dialog
charCount: $ '#char-count', dialog
fileSubmit: $ '#file-n-submit', dialog
fileButton: $ '#qr-file-button', dialog
filename: $ '#qr-filename', dialog
filesize: $ '#qr-filesize', dialog
fileRM: $ '#qr-filerm', dialog
spoiler: $ '#qr-file-spoiler', dialog
status: $ '[type=submit]', dialog
fileInput: $ '[type=file]', dialog
if Conf['Tab to Choose Files First']
$.add nodes.fileSubmit, nodes.status
$.get 'qr-proceed', false, (item) ->
nodes.proceed.checked = item['qr-proceed']
nodes.fileInput.max = $('input[name=MAX_FILE_SIZE]').value
QR.spoiler = !!$ 'input[name=spoiler]'
nodes.spoiler.hidden = !QR.spoiler
if g.BOARD.ID is 'f'
nodes.flashTag = $.el 'select',
name: 'filetag'
innerHTML: """
<option value=0>Hentai</option>
<option value=6>Porn</option>
<option value=1>Japanese</option>
<option value=2>Anime</option>
<option value=3>Game</option>
<option value=5>Loop</option>
<option value=4 selected>Other</option>
"""
nodes.flashTag.dataset.default = '4'
$.add nodes.form, nodes.flashTag
if flagSelector = $ '.flagSelector'
nodes.flag = flagSelector.cloneNode true
nodes.flag.dataset.name = 'flag'
nodes.flag.dataset.default = '0'
$.add nodes.form, nodes.flag
<% if (type === 'userscript') { %>
# XXX Firefox lacks focusin/focusout support.
for elm in $$ '*', QR.nodes.el
$.on elm, 'blur', QR.focusout
$.on elm, 'focus', QR.focusin
<% } %>
$.on dialog, 'focusin', QR.focusin
$.on dialog, 'focusout', QR.focusout
$.on nodes.fileButton, 'click', QR.openFileInput
$.on nodes.autohide, 'change', QR.toggleHide
$.on nodes.close, 'click', QR.close
$.on nodes.dumpButton, 'click', -> nodes.el.classList.toggle 'dump'
$.on nodes.urlButton, 'click', QR.handleUrl
$.on nodes.proceed, 'click', $.cb.checked
$.on nodes.addPost, 'click', -> new QR.post true
$.on nodes.form, 'submit', QR.submit
$.on nodes.fileRM, 'click', -> QR.selected.rmFile()
$.on nodes.spoiler, 'change', -> QR.selected.nodes.spoiler.click()
$.on nodes.fileInput, 'change', QR.handleFiles
# save selected post's data
save = -> QR.selected.save @
for name in ['thread', 'name', 'email', 'sub', 'com', 'filename', 'flag']
continue unless node = nodes[name]
event = if node.nodeName is 'SELECT' then 'change' else 'input'
$.on nodes[name], event, save
<% if (type === 'userscript') { %>
if Conf['Remember QR Size']
$.get 'QR Size', '', (item) ->
nodes.com.style.cssText = item['QR Size']
$.on nodes.com, 'mouseup', (e) ->
return if e.button isnt 0
$.set 'QR Size', @style.cssText
<% } %>
QR.generatePostableThreadsList()
QR.persona.init()
new QR.post true
QR.status()
QR.cooldown.init()
QR.captcha.init()
$.add d.body, dialog
# Create a custom event when the QR dialog is first initialized.
# Use it to extend the QR's functionalities, or for XTRM RICE.
$.event 'QRDialogCreation', null, dialog
submit: (e, dismiss) ->
e?.preventDefault()
if QR.req
QR.abort()
return
if QR.cooldown.seconds
QR.cooldown.auto = !QR.cooldown.auto
QR.status()
return
post = QR.posts[0]
post.forceSave()
if g.BOARD.ID is 'f'
filetag = QR.nodes.flashTag.value
threadID = post.thread
thread = g.BOARD.threads[threadID]
# prevent errors
if threadID is 'new'
threadID = null
if g.BOARD.ID is 'vg' and !post.sub
err = 'New threads require a subject.'
else unless post.file or textOnly = !!$ 'input[name=textonly]', $.id 'postForm'
err = 'No file selected.'
else if g.BOARD.threads[threadID].isClosed
err = 'You can\'t reply to this thread anymore.'
else unless post.com or post.file
err = 'No file selected.'
else if post.file and thread.fileLimit
err = 'Max limit of image replies has been reached.'
else if !dismiss and !post.file and m = post.com.match /pic(ture)? (un)?related/i
err = $.el 'span',
innerHTML: """
No file selected despite '#{m[0]}' in your post. <button>Dismiss</button>
"""
$.on ($ 'button', err), 'click', ->
QR.submit null, true
if QR.captcha.isEnabled and !err
{challenge, response} = QR.captcha.getOne()
err = 'No valid captcha.' unless response
QR.cleanNotifications()
if err
# stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
return
# Enable auto-posting if we have stuff to post, disable it otherwise.
QR.cooldown.auto = QR.posts.length > 1
if Conf['Auto-Hide QR'] and !QR.cooldown.auto
QR.hide()
if !QR.cooldown.auto and $.x 'ancestor::div[@id="qr"]', d.activeElement
# Unfocus the focused element if it is one within the QR and we're not auto-posting.
d.activeElement.blur()
com = if Conf['Markdown'] then Markdown.format post.com else post.com
post.lock()
formData =
resto: threadID
name: post.name
email: post.email
sub: post.sub
com: com
upfile: post.file
filetag: filetag
spoiler: post.spoiler
flag: post.flag
textonly: textOnly
mode: 'regist'
pwd: PI:PASSWORD:<PASSWORD>END_PI
recaptcha_challenge_field: challenge
recaptcha_response_field: response
options =
responseType: 'document'
withCredentials: true
onload: QR.response
onerror: ->
# Connection error, or
# www.4chan.org/banned
delete QR.req
if QR.captcha.isEnabled
QR.captcha.destroy()
QR.captcha.setup()
post.unlock()
QR.cooldown.auto = false
QR.status()
QR.error $.el 'span',
innerHTML: """
Connection error. You may have been <a href=//www.4chan.org/banned target=_blank>banned</a>.
[<a href="https://github.com/MayhemYDG/4chan-x/wiki/FAQ#what-does-connection-error-you-may-have-been-banned-mean" target=_blank>FAQ</a>]
"""
extra =
form: $.formData formData
upCallbacks:
onload: ->
# Upload done, waiting for server response.
QR.req.isUploadFinished = true
QR.req.uploadEndTime = Date.now()
QR.req.progress = '...'
QR.status()
onprogress: (e) ->
# Uploading...
QR.req.progress = "#{Math.round e.loaded / e.total * 100}%"
QR.status()
QR.req = $.ajax $.id('postForm').parentNode.action, options, extra
# Starting to upload might take some time.
# Provide some feedback that we're starting to submit.
QR.req.uploadStartTime = Date.now()
QR.req.progress = '...'
QR.status()
response: ->
{req} = QR
delete QR.req
QR.captcha.destroy() if QR.captcha.isEnabled
post = QR.posts[0]
postsCount = QR.posts.length - 1
post.unlock()
resDoc = req.response
if ban = $ '.banType', resDoc # banned/warning
board = $('.board', resDoc).innerHTML
err = $.el 'span', innerHTML:
if ban.textContent.toLowerCase() is 'banned'
"""
You are banned on #{board}! ;_;<br>
Click <a href=//www.4chan.org/banned target=_blank>here</a> to see the reason.
"""
else
"""
You were issued a warning on #{board} as #{$('.nameBlock', resDoc).innerHTML}.<br>
Reason: #{$('.reason', resDoc).innerHTML}
"""
else if err = resDoc.getElementById 'errmsg' # error!
$('a', err)?.target = '_blank' # duplicate image link
else if resDoc.title isnt 'Post successful!'
err = 'Connection error with sys.4chan.org.'
else if req.status isnt 200
err = "Error #{req.statusText} (#{req.status})"
if err
if /captcha|verification/i.test(err.textContent) or err is 'Connection error with sys.4chan.org.'
# Remove the obnoxious 4chan Pass ad.
if /mistyped/i.test err.textContent
err = 'You seem to have mistyped the CAPTCHA.'
QR.cooldown.auto = false
# Too many frequent mistyped captchas will auto-ban you!
# On connection error, the post most likely didn't go through.
QR.cooldown.set delay: 2
else if err.textContent and m = err.textContent.match /wait(?:\s+(\d+)\s+minutes)?\s+(\d+)\s+second/i
QR.cooldown.auto = !QR.captcha.isEnabled
QR.cooldown.set delay: (m[1] or 0) * 60 + Number m[2]
else if err.textContent.match /duplicate\sfile/i
if QR.nodes.proceed.checked and postsCount
post.rm()
QR.cooldown.auto = true
QR.cooldown.set delay: 10
else
QR.cooldown.auto = false
else # stop auto-posting
QR.cooldown.auto = false
QR.status()
QR.error err
QR.captcha.setup() if QR.captcha.isEnabled
return
h1 = $ 'h1', resDoc
QR.cleanNotifications()
QR.notifications.push new Notice 'success', h1.textContent, 5
QR.persona.set post
[_, threadID, postID] = h1.nextSibling.textContent.match /thread:(\d+),no:(\d+)/
postID = +postID
threadID = +threadID or postID
isReply = threadID isnt postID
QR.db.set
boardID: g.BOARD.ID
threadID: threadID
postID: postID
val: true
# Post/upload confirmed as successful.
$.event 'QRPostSuccessful', {
boardID: g.BOARD.ID
threadID
postID
}
$.event 'QRPostSuccessful_', {boardID: g.BOARD.ID, threadID, postID}
# Enable auto-posting if we have stuff left to post, disable it otherwise.
QR.cooldown.auto = postsCount and isReply
QR.captcha.setup() if QR.captcha.isEnabled and QR.cooldown.auto
unless Conf['Persistent QR'] or QR.cooldown.auto
QR.close()
else
post.rm()
QR.cooldown.set {req, post, isReply, threadID}
URL = if threadID is postID # new thread
Build.path g.BOARD.ID, threadID
else if g.VIEW is 'index' and !QR.cooldown.auto and Conf['Open Post in New Tab'] # replying from the index
Build.path g.BOARD.ID, threadID, postID
if URL
if Conf['Open Post in New Tab']
$.open URL
else
window.location = URL
QR.status()
abort: ->
if QR.req and !QR.req.isUploadFinished
QR.req.abort()
delete QR.req
QR.posts[0].unlock()
QR.cooldown.auto = false
QR.notifications.push new Notice 'info', 'QR upload aborted.', 5
QR.status()
|
[
{
"context": "###\r\n Copyright (c) 2015 Michio Yokomizo (mrpepper023) \r\n control-structures.js is relea",
"end": 42,
"score": 0.9998766779899597,
"start": 27,
"tag": "NAME",
"value": "Michio Yokomizo"
},
{
"context": "###\r\n Copyright (c) 2015 Michio Yokomizo (mrpepper023) ... | lib/control-structures.coffee | mrpepper023/control-structures | 1 | ###
Copyright (c) 2015 Michio Yokomizo (mrpepper023)
control-structures.js is released under the MIT License,
see https://github.com/mrpepper023/control-structures
you want to use this library in same namespace with node.js as with web-browser,
include this library like 'var cs = require('control-structures');'
###
((root, factory) ->
if FORCE_CLIENTSIDE?
root.cs = factory()
else if (typeof define == 'function' && define.amd)
define([], factory)
else if (typeof exports == 'object')
module.exports = factory()
else
root.cs = factory()
)(this, () ->
a=(g)->[].slice.call(g)
###
y combinator
###
y: (func) ->
return ((p) ->
return ->
return func(p(p)).apply(this,arguments)
)((p) ->
return ->
return func(p(p)).apply(this,arguments)
)
###
simple continuation
(継続のネストが深くなりすぎるのを防ぐため、
または、if,switchの後、容易に合流するために用います)
_(firstargs,func1,func2,...)
引数に取った非同期関数を順次実行します
firstargs
func1に渡す引数を配列に納めたものです
[arg1,arg2]を渡すと、func1(func2,arg1,arg2)が呼ばれます
この配列の要素数は可変です
func1(next,...)
最初に実行する関数です。次へ進むときはこの関数内でnextを呼びます。
next(arg3,arg4) を実行すると、func2(func3,arg3,arg4)が呼ばれます
この引数の要素数は可変です
func2(next,...)
以下、同様に好きな回数だけ続けられます。
###
_: ->
args = a(arguments)
firstargs = args.shift()
(@.y (func) ->
return ->
arg = args.shift()
if arg?
passargs = a(arguments)
passargs.unshift(func)
arg.apply(this,passargs)
).apply this,firstargs
###
Each (simultaneous)
_each(obj, applyargs_array, applyfunc, endfunc)
ArrayまたはObjectの各要素に、並行して同じ関数を適用します
obj
処理するArrayまたはObject
applyargs_array
applyfuncに渡すその他の引数を配列にして指定します。
[arg1,arg2]を指定すると、applyfunc(val,i,next,arg1,arg2)が呼ばれます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがArrayの場合、valは要素、iは序数です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがObjectの場合、keyは要素のキー、valueは要素の値です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
endfunc(...)
結果を受け取る関数です。next('foo','bar')が2要素から呼ばれる場合、
endfunc(['foo','foo'],['bar','bar'])となります。配列内の順序は、各処理の
終了順です。弁別する必要のある場合、iやkeyをnextの引数に加えて下さい。
###
_each: (obj, applyargs_array, applyfunc, endfunc) ->
((nextc) ->
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
num = 0
next = nextc()
if isarr
for val,i in obj
num++
applyfunc.apply this,[val,i,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
else
for key,val of obj
num++
applyfunc.apply this,[key,val,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
)(->
count = 0
result = []
return (num,next) ->
count++
if arguments.length > 0
args = a(arguments)
args.shift()
args.shift()
for arg,i in args
if result.length <= i
result.push([])
result[i].push(arg)
if count == num
next.apply this,result
)
###
for Loop
_for(i, f_judge, f_iter, firstarg_array, loopfunc, endfunc)
初期値・条件・イテレータを用いて、loopfuncを繰り返します。
i
カウンタの初期値です。
f_judge(n) 返値=true,false
カウンタに対する条件です。falseが返るとループが終了します。
※この関数は同期関数でなければなりません。
f_iter(n) 返値=カウンタ値
カウンタのイテレータです。引数がカウンタの現在の値で、返値を返すと、
カウンタに代入されます。
※この関数は同期関数でなければなりません。
firstarg_array
loopfuncへの初回の引数を、配列で示します。
[arg1,arg2]を渡すと、loopfunc(n,break,next,arg1,arg2)が呼ばれます。
loopfunc(n,_break,_next,...)
繰り返し実行する内容です。nはカウンタの現在値です。
続行する場合、_next(...)を呼び出します。_nextの引数は、次回のloopfuncの
呼び出しの際、引き渡されます。たとえば、_next(arg3,arg4)を呼び出せば、
loopfunc(n,next,arg3,arg4)が呼ばれます。
繰り返しを中断する場合、_break(...)を呼び出します。すると、
endfunc(n,...)が呼び出されます。
endfunc(n,...)
繰り返しの終了後に実行される関数です。nは終了時のカウンタの値です。
###
_for: (i, f_judge, f_iter, firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
if f_judge i
loopfunc.apply this,[i,->
#_break
endfunc.apply this,[i].concat(a(arguments))
,->
#_next
i = f_iter i
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,[i].concat(a(arguments))
).apply this,firstarg_array
###
for in Array or Object
_for_in(obj, firstargs, loopfunc, endfunc)
firstargs
初回のloopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(key,val,_break,_next,arg1,arg2)が呼ばれます。
loopfunc(key,val,_break,_next,...)
繰り返し実行する関数です。Objectの場合、key,valが得られます
続行する場合_next(...)、中断する場合_break(...)を呼び出します。
_nextの引数は、次回のloopfuncに渡されます。
_breakの引数は、endfuncに渡されます。
endfunc(...)
繰り返しの終了時に呼ばれます。
###
_for_in: (obj, firstargs, loopfunc, endfunc) ->
i = -1
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
if isarr
indexlimit = obj.length
else
indexlimit = Object.keys(obj).length
(@.y (func) ->
return ->
i += 1
if i < indexlimit
if isarr
loopfunc.apply this,[obj[i],i, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
key = Object.keys(obj)[i]
value = obj[key]
loopfunc.apply this,[key, value, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,arguments
).apply this,firstargs
###
while Loop
_while(firstarg_array, loopfunc, endfunc)
終了条件のみを指定した繰り返しを行います。リトライループなどです。
firstarg_array
初回のf_judge, loopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
loopfunc(_break,_next,...)
繰り返し行う非同期処理です。
繰り返しを中断するときは_break(...)を呼ぶと、endfunc(...)が呼ばれます。
繰り返しを続行するときは_next(...)を呼ぶと、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
endfunc(...)
次の処理です。上記の通り、引数を受け取ることができます。
###
_while: (firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
passargs = a(arguments)
passargs.unshift ->
#_next
func.apply this,arguments
passargs.unshift ->
#_break
endfunc.apply this,arguments
loopfunc.apply this,passargs
).apply this,firstarg_array
###
exception handling
myexc = new exc
例外管理オブジェクトを生成します。ここではmyexcとします。
myexc._try(block_args_array,f_block,e_array,f_catch,f_finally,f_next)
例外スコープを開始します。実処理はblock内、例外処理はf_catch内、
終了処理はf_finally内で行い、f_nextへと進みます。
f_finally内で_throwすると、当該終了処理は完了せずに例外送出します
block_args_array
blockに渡す引数を、配列にして指定します。
[arg1,arg2]を渡すと、f_block(arg1,arg2)が呼ばれます。
f_block(...)
実処理を行うスコープです。このexc例外を発生しうる関数を
呼び出すときはmyexcを渡して下さい。次へ進むときは
myexc._finally(...)を呼べば、f_finally(next,...)が呼ばれます。
e_array
f_catchで処理する例外の種類を列挙した配列です。
可読性のある文字列をお勧めします。
f_catch(_e,...)
_throwに渡された例外の種類と、その他の_throwに渡された引数が
得られます。e_arrayで列挙した例外は全て処理して下さい。
処理を終えたらmyexc._finally(...)を呼んで下さい。f_blockと同様です。
f_finally(next,...)
終了処理を簡潔に行います。処理を終えたら、next(...)を呼んで下さい。
f_next(...)が呼ばれます。基本的にはmyexcを引数に指定して下さい。
f_next(...)
次の処理を行う関数です。
myexc._throw(_e,...)
例外を発生させます。引数はf_catchに渡されます。
myexc._finally(...)
例外スコープのスタックをpopして、ユーザ終了処理を呼び出します。
引数はf_finallyに渡されます。
###
exc: class exc
_stack = []
constructor: ->
_try: (block_args_array,block,e_array,arg_catch,arg_finally,arg_next) ->
_stack.push({e_array:e_array,_catch:arg_catch,_finally:arg_finally,next:arg_next})
block.apply this,block_args_array
fa = ->
if _stack.length > 0
stackpop = _stack.pop()
stackpop._finally.apply this,arguments
else
return
_finally: ->
if _stack.length > 0
stackpop = _stack.pop()
if stackpop.next?
stackpop._finally.apply this,[stackpop.next].concat(a(arguments))
return
else
stackpop._finally.apply this,[->return].concat(a(arguments))
return
else
return
y = (func) ->
return ((p) -> return -> return func(p(p)).apply(this,arguments)
)((p) -> return -> return func(p(p)).apply(this,arguments)
)
_w = (loopfunc, endfunc) -> (y (func) -> return -> loopfunc(endfunc,func))()
_throw: (_e) =>
catchset = {}
uncaught = false
_w (_break,_next)=>
catchset = _stack.pop()
if catchset?
_stack.push catchset
result = catchset.e_array.indexOf _e
if result != -1
catchset._catch.apply this,[_e].concat(a(arguments))
return
else
if arguments.length <= 2
fa.call this,_next
else
passargs = a(arguments)
passargs.shift()
passargs.shift()
passargs.unshift(_next)
fa.apply this,passargs
else
uncaught = true
_break()
,->
if uncaught
console.log 'uncaught exception: '+_e.toString()
process.exit 1
return
)
###
todo:
引数チェック
firstarg_arrayが配列でないor(null)のときの処理など
関数を取る場合のチェック&nullチェック(devのみ?)
返値チェック
イテレータや終了条件など、同期関数の返値チェック
ループ関数に同期関数を入れられたときのstack overflowを避けるか分かりやすく
###
| 82897 | ###
Copyright (c) 2015 <NAME> (mrpepper023)
control-structures.js is released under the MIT License,
see https://github.com/mrpepper023/control-structures
you want to use this library in same namespace with node.js as with web-browser,
include this library like 'var cs = require('control-structures');'
###
((root, factory) ->
if FORCE_CLIENTSIDE?
root.cs = factory()
else if (typeof define == 'function' && define.amd)
define([], factory)
else if (typeof exports == 'object')
module.exports = factory()
else
root.cs = factory()
)(this, () ->
a=(g)->[].slice.call(g)
###
y combinator
###
y: (func) ->
return ((p) ->
return ->
return func(p(p)).apply(this,arguments)
)((p) ->
return ->
return func(p(p)).apply(this,arguments)
)
###
simple continuation
(継続のネストが深くなりすぎるのを防ぐため、
または、if,switchの後、容易に合流するために用います)
_(firstargs,func1,func2,...)
引数に取った非同期関数を順次実行します
firstargs
func1に渡す引数を配列に納めたものです
[arg1,arg2]を渡すと、func1(func2,arg1,arg2)が呼ばれます
この配列の要素数は可変です
func1(next,...)
最初に実行する関数です。次へ進むときはこの関数内でnextを呼びます。
next(arg3,arg4) を実行すると、func2(func3,arg3,arg4)が呼ばれます
この引数の要素数は可変です
func2(next,...)
以下、同様に好きな回数だけ続けられます。
###
_: ->
args = a(arguments)
firstargs = args.shift()
(@.y (func) ->
return ->
arg = args.shift()
if arg?
passargs = a(arguments)
passargs.unshift(func)
arg.apply(this,passargs)
).apply this,firstargs
###
Each (simultaneous)
_each(obj, applyargs_array, applyfunc, endfunc)
ArrayまたはObjectの各要素に、並行して同じ関数を適用します
obj
処理するArrayまたはObject
applyargs_array
applyfuncに渡すその他の引数を配列にして指定します。
[arg1,arg2]を指定すると、applyfunc(val,i,next,arg1,arg2)が呼ばれます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがArrayの場合、valは要素、iは序数です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがObjectの場合、keyは要素のキー、valueは要素の値です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
endfunc(...)
結果を受け取る関数です。next('foo','bar')が2要素から呼ばれる場合、
endfunc(['foo','foo'],['bar','bar'])となります。配列内の順序は、各処理の
終了順です。弁別する必要のある場合、iやkeyをnextの引数に加えて下さい。
###
_each: (obj, applyargs_array, applyfunc, endfunc) ->
((nextc) ->
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
num = 0
next = nextc()
if isarr
for val,i in obj
num++
applyfunc.apply this,[val,i,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
else
for key,val of obj
num++
applyfunc.apply this,[key,val,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
)(->
count = 0
result = []
return (num,next) ->
count++
if arguments.length > 0
args = a(arguments)
args.shift()
args.shift()
for arg,i in args
if result.length <= i
result.push([])
result[i].push(arg)
if count == num
next.apply this,result
)
###
for Loop
_for(i, f_judge, f_iter, firstarg_array, loopfunc, endfunc)
初期値・条件・イテレータを用いて、loopfuncを繰り返します。
i
カウンタの初期値です。
f_judge(n) 返値=true,false
カウンタに対する条件です。falseが返るとループが終了します。
※この関数は同期関数でなければなりません。
f_iter(n) 返値=カウンタ値
カウンタのイテレータです。引数がカウンタの現在の値で、返値を返すと、
カウンタに代入されます。
※この関数は同期関数でなければなりません。
firstarg_array
loopfuncへの初回の引数を、配列で示します。
[arg1,arg2]を渡すと、loopfunc(n,break,next,arg1,arg2)が呼ばれます。
loopfunc(n,_break,_next,...)
繰り返し実行する内容です。nはカウンタの現在値です。
続行する場合、_next(...)を呼び出します。_nextの引数は、次回のloopfuncの
呼び出しの際、引き渡されます。たとえば、_next(arg3,arg4)を呼び出せば、
loopfunc(n,next,arg3,arg4)が呼ばれます。
繰り返しを中断する場合、_break(...)を呼び出します。すると、
endfunc(n,...)が呼び出されます。
endfunc(n,...)
繰り返しの終了後に実行される関数です。nは終了時のカウンタの値です。
###
_for: (i, f_judge, f_iter, firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
if f_judge i
loopfunc.apply this,[i,->
#_break
endfunc.apply this,[i].concat(a(arguments))
,->
#_next
i = f_iter i
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,[i].concat(a(arguments))
).apply this,firstarg_array
###
for in Array or Object
_for_in(obj, firstargs, loopfunc, endfunc)
firstargs
初回のloopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(key,val,_break,_next,arg1,arg2)が呼ばれます。
loopfunc(key,val,_break,_next,...)
繰り返し実行する関数です。Objectの場合、key,valが得られます
続行する場合_next(...)、中断する場合_break(...)を呼び出します。
_nextの引数は、次回のloopfuncに渡されます。
_breakの引数は、endfuncに渡されます。
endfunc(...)
繰り返しの終了時に呼ばれます。
###
_for_in: (obj, firstargs, loopfunc, endfunc) ->
i = -1
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
if isarr
indexlimit = obj.length
else
indexlimit = Object.keys(obj).length
(@.y (func) ->
return ->
i += 1
if i < indexlimit
if isarr
loopfunc.apply this,[obj[i],i, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
key = Object.keys(obj)[i]
value = obj[key]
loopfunc.apply this,[key, value, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,arguments
).apply this,firstargs
###
while Loop
_while(firstarg_array, loopfunc, endfunc)
終了条件のみを指定した繰り返しを行います。リトライループなどです。
firstarg_array
初回のf_judge, loopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
loopfunc(_break,_next,...)
繰り返し行う非同期処理です。
繰り返しを中断するときは_break(...)を呼ぶと、endfunc(...)が呼ばれます。
繰り返しを続行するときは_next(...)を呼ぶと、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
endfunc(...)
次の処理です。上記の通り、引数を受け取ることができます。
###
_while: (firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
passargs = a(arguments)
passargs.unshift ->
#_next
func.apply this,arguments
passargs.unshift ->
#_break
endfunc.apply this,arguments
loopfunc.apply this,passargs
).apply this,firstarg_array
###
exception handling
myexc = new exc
例外管理オブジェクトを生成します。ここではmyexcとします。
myexc._try(block_args_array,f_block,e_array,f_catch,f_finally,f_next)
例外スコープを開始します。実処理はblock内、例外処理はf_catch内、
終了処理はf_finally内で行い、f_nextへと進みます。
f_finally内で_throwすると、当該終了処理は完了せずに例外送出します
block_args_array
blockに渡す引数を、配列にして指定します。
[arg1,arg2]を渡すと、f_block(arg1,arg2)が呼ばれます。
f_block(...)
実処理を行うスコープです。このexc例外を発生しうる関数を
呼び出すときはmyexcを渡して下さい。次へ進むときは
myexc._finally(...)を呼べば、f_finally(next,...)が呼ばれます。
e_array
f_catchで処理する例外の種類を列挙した配列です。
可読性のある文字列をお勧めします。
f_catch(_e,...)
_throwに渡された例外の種類と、その他の_throwに渡された引数が
得られます。e_arrayで列挙した例外は全て処理して下さい。
処理を終えたらmyexc._finally(...)を呼んで下さい。f_blockと同様です。
f_finally(next,...)
終了処理を簡潔に行います。処理を終えたら、next(...)を呼んで下さい。
f_next(...)が呼ばれます。基本的にはmyexcを引数に指定して下さい。
f_next(...)
次の処理を行う関数です。
myexc._throw(_e,...)
例外を発生させます。引数はf_catchに渡されます。
myexc._finally(...)
例外スコープのスタックをpopして、ユーザ終了処理を呼び出します。
引数はf_finallyに渡されます。
###
exc: class exc
_stack = []
constructor: ->
_try: (block_args_array,block,e_array,arg_catch,arg_finally,arg_next) ->
_stack.push({e_array:e_array,_catch:arg_catch,_finally:arg_finally,next:arg_next})
block.apply this,block_args_array
fa = ->
if _stack.length > 0
stackpop = _stack.pop()
stackpop._finally.apply this,arguments
else
return
_finally: ->
if _stack.length > 0
stackpop = _stack.pop()
if stackpop.next?
stackpop._finally.apply this,[stackpop.next].concat(a(arguments))
return
else
stackpop._finally.apply this,[->return].concat(a(arguments))
return
else
return
y = (func) ->
return ((p) -> return -> return func(p(p)).apply(this,arguments)
)((p) -> return -> return func(p(p)).apply(this,arguments)
)
_w = (loopfunc, endfunc) -> (y (func) -> return -> loopfunc(endfunc,func))()
_throw: (_e) =>
catchset = {}
uncaught = false
_w (_break,_next)=>
catchset = _stack.pop()
if catchset?
_stack.push catchset
result = catchset.e_array.indexOf _e
if result != -1
catchset._catch.apply this,[_e].concat(a(arguments))
return
else
if arguments.length <= 2
fa.call this,_next
else
passargs = a(arguments)
passargs.shift()
passargs.shift()
passargs.unshift(_next)
fa.apply this,passargs
else
uncaught = true
_break()
,->
if uncaught
console.log 'uncaught exception: '+_e.toString()
process.exit 1
return
)
###
todo:
引数チェック
firstarg_arrayが配列でないor(null)のときの処理など
関数を取る場合のチェック&nullチェック(devのみ?)
返値チェック
イテレータや終了条件など、同期関数の返値チェック
ループ関数に同期関数を入れられたときのstack overflowを避けるか分かりやすく
###
| true | ###
Copyright (c) 2015 PI:NAME:<NAME>END_PI (mrpepper023)
control-structures.js is released under the MIT License,
see https://github.com/mrpepper023/control-structures
you want to use this library in same namespace with node.js as with web-browser,
include this library like 'var cs = require('control-structures');'
###
((root, factory) ->
if FORCE_CLIENTSIDE?
root.cs = factory()
else if (typeof define == 'function' && define.amd)
define([], factory)
else if (typeof exports == 'object')
module.exports = factory()
else
root.cs = factory()
)(this, () ->
a=(g)->[].slice.call(g)
###
y combinator
###
y: (func) ->
return ((p) ->
return ->
return func(p(p)).apply(this,arguments)
)((p) ->
return ->
return func(p(p)).apply(this,arguments)
)
###
simple continuation
(継続のネストが深くなりすぎるのを防ぐため、
または、if,switchの後、容易に合流するために用います)
_(firstargs,func1,func2,...)
引数に取った非同期関数を順次実行します
firstargs
func1に渡す引数を配列に納めたものです
[arg1,arg2]を渡すと、func1(func2,arg1,arg2)が呼ばれます
この配列の要素数は可変です
func1(next,...)
最初に実行する関数です。次へ進むときはこの関数内でnextを呼びます。
next(arg3,arg4) を実行すると、func2(func3,arg3,arg4)が呼ばれます
この引数の要素数は可変です
func2(next,...)
以下、同様に好きな回数だけ続けられます。
###
_: ->
args = a(arguments)
firstargs = args.shift()
(@.y (func) ->
return ->
arg = args.shift()
if arg?
passargs = a(arguments)
passargs.unshift(func)
arg.apply(this,passargs)
).apply this,firstargs
###
Each (simultaneous)
_each(obj, applyargs_array, applyfunc, endfunc)
ArrayまたはObjectの各要素に、並行して同じ関数を適用します
obj
処理するArrayまたはObject
applyargs_array
applyfuncに渡すその他の引数を配列にして指定します。
[arg1,arg2]を指定すると、applyfunc(val,i,next,arg1,arg2)が呼ばれます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがArrayの場合、valは要素、iは序数です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
applyfunc(val,i,next,...)
各要素に適用する関数です。objがObjectの場合、keyは要素のキー、valueは要素の値です。
処理が終わったらnext(...)を呼び出します。nextの各引数は、配列に代入されて
endfuncに渡されます。
endfunc(...)
結果を受け取る関数です。next('foo','bar')が2要素から呼ばれる場合、
endfunc(['foo','foo'],['bar','bar'])となります。配列内の順序は、各処理の
終了順です。弁別する必要のある場合、iやkeyをnextの引数に加えて下さい。
###
_each: (obj, applyargs_array, applyfunc, endfunc) ->
((nextc) ->
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
num = 0
next = nextc()
if isarr
for val,i in obj
num++
applyfunc.apply this,[val,i,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
else
for key,val of obj
num++
applyfunc.apply this,[key,val,->
next.apply this,[num,endfunc].concat(a(arguments))
].concat(applyargs_array)
)(->
count = 0
result = []
return (num,next) ->
count++
if arguments.length > 0
args = a(arguments)
args.shift()
args.shift()
for arg,i in args
if result.length <= i
result.push([])
result[i].push(arg)
if count == num
next.apply this,result
)
###
for Loop
_for(i, f_judge, f_iter, firstarg_array, loopfunc, endfunc)
初期値・条件・イテレータを用いて、loopfuncを繰り返します。
i
カウンタの初期値です。
f_judge(n) 返値=true,false
カウンタに対する条件です。falseが返るとループが終了します。
※この関数は同期関数でなければなりません。
f_iter(n) 返値=カウンタ値
カウンタのイテレータです。引数がカウンタの現在の値で、返値を返すと、
カウンタに代入されます。
※この関数は同期関数でなければなりません。
firstarg_array
loopfuncへの初回の引数を、配列で示します。
[arg1,arg2]を渡すと、loopfunc(n,break,next,arg1,arg2)が呼ばれます。
loopfunc(n,_break,_next,...)
繰り返し実行する内容です。nはカウンタの現在値です。
続行する場合、_next(...)を呼び出します。_nextの引数は、次回のloopfuncの
呼び出しの際、引き渡されます。たとえば、_next(arg3,arg4)を呼び出せば、
loopfunc(n,next,arg3,arg4)が呼ばれます。
繰り返しを中断する場合、_break(...)を呼び出します。すると、
endfunc(n,...)が呼び出されます。
endfunc(n,...)
繰り返しの終了後に実行される関数です。nは終了時のカウンタの値です。
###
_for: (i, f_judge, f_iter, firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
if f_judge i
loopfunc.apply this,[i,->
#_break
endfunc.apply this,[i].concat(a(arguments))
,->
#_next
i = f_iter i
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,[i].concat(a(arguments))
).apply this,firstarg_array
###
for in Array or Object
_for_in(obj, firstargs, loopfunc, endfunc)
firstargs
初回のloopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(key,val,_break,_next,arg1,arg2)が呼ばれます。
loopfunc(key,val,_break,_next,...)
繰り返し実行する関数です。Objectの場合、key,valが得られます
続行する場合_next(...)、中断する場合_break(...)を呼び出します。
_nextの引数は、次回のloopfuncに渡されます。
_breakの引数は、endfuncに渡されます。
endfunc(...)
繰り返しの終了時に呼ばれます。
###
_for_in: (obj, firstargs, loopfunc, endfunc) ->
i = -1
isarr = ('Array' == Object.prototype.toString.call(obj).slice(8, -1))
if isarr
indexlimit = obj.length
else
indexlimit = Object.keys(obj).length
(@.y (func) ->
return ->
i += 1
if i < indexlimit
if isarr
loopfunc.apply this,[obj[i],i, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
key = Object.keys(obj)[i]
value = obj[key]
loopfunc.apply this,[key, value, ->
endfunc.apply this,arguments
,->
func.apply this,arguments
].concat(a(arguments))
else
endfunc.apply this,arguments
).apply this,firstargs
###
while Loop
_while(firstarg_array, loopfunc, endfunc)
終了条件のみを指定した繰り返しを行います。リトライループなどです。
firstarg_array
初回のf_judge, loopfuncの引数を配列にして示します。
[arg1,arg2]が渡されると、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
loopfunc(_break,_next,...)
繰り返し行う非同期処理です。
繰り返しを中断するときは_break(...)を呼ぶと、endfunc(...)が呼ばれます。
繰り返しを続行するときは_next(...)を呼ぶと、loopfunc(_break,_next,arg1,arg2)が呼ばれます。
endfunc(...)
次の処理です。上記の通り、引数を受け取ることができます。
###
_while: (firstarg_array, loopfunc, endfunc) ->
(@.y (func) ->
return ->
passargs = a(arguments)
passargs.unshift ->
#_next
func.apply this,arguments
passargs.unshift ->
#_break
endfunc.apply this,arguments
loopfunc.apply this,passargs
).apply this,firstarg_array
###
exception handling
myexc = new exc
例外管理オブジェクトを生成します。ここではmyexcとします。
myexc._try(block_args_array,f_block,e_array,f_catch,f_finally,f_next)
例外スコープを開始します。実処理はblock内、例外処理はf_catch内、
終了処理はf_finally内で行い、f_nextへと進みます。
f_finally内で_throwすると、当該終了処理は完了せずに例外送出します
block_args_array
blockに渡す引数を、配列にして指定します。
[arg1,arg2]を渡すと、f_block(arg1,arg2)が呼ばれます。
f_block(...)
実処理を行うスコープです。このexc例外を発生しうる関数を
呼び出すときはmyexcを渡して下さい。次へ進むときは
myexc._finally(...)を呼べば、f_finally(next,...)が呼ばれます。
e_array
f_catchで処理する例外の種類を列挙した配列です。
可読性のある文字列をお勧めします。
f_catch(_e,...)
_throwに渡された例外の種類と、その他の_throwに渡された引数が
得られます。e_arrayで列挙した例外は全て処理して下さい。
処理を終えたらmyexc._finally(...)を呼んで下さい。f_blockと同様です。
f_finally(next,...)
終了処理を簡潔に行います。処理を終えたら、next(...)を呼んで下さい。
f_next(...)が呼ばれます。基本的にはmyexcを引数に指定して下さい。
f_next(...)
次の処理を行う関数です。
myexc._throw(_e,...)
例外を発生させます。引数はf_catchに渡されます。
myexc._finally(...)
例外スコープのスタックをpopして、ユーザ終了処理を呼び出します。
引数はf_finallyに渡されます。
###
exc: class exc
_stack = []
constructor: ->
_try: (block_args_array,block,e_array,arg_catch,arg_finally,arg_next) ->
_stack.push({e_array:e_array,_catch:arg_catch,_finally:arg_finally,next:arg_next})
block.apply this,block_args_array
fa = ->
if _stack.length > 0
stackpop = _stack.pop()
stackpop._finally.apply this,arguments
else
return
_finally: ->
if _stack.length > 0
stackpop = _stack.pop()
if stackpop.next?
stackpop._finally.apply this,[stackpop.next].concat(a(arguments))
return
else
stackpop._finally.apply this,[->return].concat(a(arguments))
return
else
return
y = (func) ->
return ((p) -> return -> return func(p(p)).apply(this,arguments)
)((p) -> return -> return func(p(p)).apply(this,arguments)
)
_w = (loopfunc, endfunc) -> (y (func) -> return -> loopfunc(endfunc,func))()
_throw: (_e) =>
catchset = {}
uncaught = false
_w (_break,_next)=>
catchset = _stack.pop()
if catchset?
_stack.push catchset
result = catchset.e_array.indexOf _e
if result != -1
catchset._catch.apply this,[_e].concat(a(arguments))
return
else
if arguments.length <= 2
fa.call this,_next
else
passargs = a(arguments)
passargs.shift()
passargs.shift()
passargs.unshift(_next)
fa.apply this,passargs
else
uncaught = true
_break()
,->
if uncaught
console.log 'uncaught exception: '+_e.toString()
process.exit 1
return
)
###
todo:
引数チェック
firstarg_arrayが配列でないor(null)のときの処理など
関数を取る場合のチェック&nullチェック(devのみ?)
返値チェック
イテレータや終了条件など、同期関数の返値チェック
ループ関数に同期関数を入れられたときのstack overflowを避けるか分かりやすく
###
|
[
{
"context": "-terminal\": \"never\"\n \"circle-ci\":\n apiToken: \"aaeb24433649ae33eaddad16b2da35a553cf8874\"\n core:\n destroyEmptyPanes: false\n disable",
"end": 409,
"score": 0.9843556880950928,
"start": 369,
"tag": "KEY",
"value": "aaeb24433649ae33eaddad16b2da35a553cf8874"
... | src/atom/config.cson | nicinabox/dotfiles | 0 | "*":
"activate-power-mode":
autoToggle: false
"atom-alignment": {}
"atom-beautify":
general:
_analyticsUserId: "b1f78f78-1b50-45cf-8acd-d5fc00267baf"
"atom-ide-ui":
use:
"atom-ide-console": "never"
"atom-ide-outline-view": "never"
"atom-ide-refactor": "never"
"atom-ide-terminal": "never"
"circle-ci":
apiToken: "aaeb24433649ae33eaddad16b2da35a553cf8874"
core:
destroyEmptyPanes: false
disabledPackages: [
"github"
"background-tips"
"linter"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
"desktop.ini"
"node_modules"
"bower_components"
"__pycache__"
"*.pyc"
]
packagesWithKeymapsDisabled: [
"activate-power-mode"
"git-plus"
]
telemetryConsent: "limited"
themes: [
"one-dark-ui"
"oceanic-next"
]
titleBar: "custom-inset"
uriHandlerRegistration: "always"
useTreeSitterParsers: false
editor:
fontFamily: "Fira Code"
fontSize: 19
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrapHangingIndent: 2
"exception-reporting":
userId: "c17350f3-e8cb-2e43-d2e2-b460fc54dc04"
"file-icons": {}
"git-plus":
general:
_analyticsUserId: "ed178489-d1ba-4896-bf4c-8c58ba6d5d26"
splitPane: "Right"
"goto-definition":
contextMenuDisplayAtFirst: false
"language-babel":
taggedTemplateGrammar: [
"\"(?<=<style jsx>{)|(?<=<style jsx global>{)\":source.css.styled"
]
linter:
disabledProviders: [
"CoffeeLint"
]
lintOnChange: false
"linter-eslint":
advanced:
disableFSCache: true
disabling:
disableWhenNoEslintConfig: false
global:
eslintrcPath: "~"
"linter-ui-default":
panelHeight: 300
showPanel: true
"one-dark-ui":
hideDockButtons: true
"package-sync":
createOnChange: true
forceOverwrite: true
tabs:
enableVcsColoring: true
"todo-show":
sortBy: "Type"
"tree-view":
focusOnReveal: false
hideIgnoredNames: true
hideVcsIgnoredFiles: true
"vim-mode":
startInInsertMode: true
wakatime:
apikey: "Saved in your ~/.wakatime.cfg file"
debug: true
"wakatime-hidden":
lastInit: 1492555628
welcome:
showOnStartup: false
whitespace:
ignoreWhitespaceOnCurrentLine: false
| 211417 | "*":
"activate-power-mode":
autoToggle: false
"atom-alignment": {}
"atom-beautify":
general:
_analyticsUserId: "b1f78f78-1b50-45cf-8acd-d5fc00267baf"
"atom-ide-ui":
use:
"atom-ide-console": "never"
"atom-ide-outline-view": "never"
"atom-ide-refactor": "never"
"atom-ide-terminal": "never"
"circle-ci":
apiToken: "<KEY>"
core:
destroyEmptyPanes: false
disabledPackages: [
"github"
"background-tips"
"linter"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
"desktop.ini"
"node_modules"
"bower_components"
"__pycache__"
"*.pyc"
]
packagesWithKeymapsDisabled: [
"activate-power-mode"
"git-plus"
]
telemetryConsent: "limited"
themes: [
"one-dark-ui"
"oceanic-next"
]
titleBar: "custom-inset"
uriHandlerRegistration: "always"
useTreeSitterParsers: false
editor:
fontFamily: "Fira Code"
fontSize: 19
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrapHangingIndent: 2
"exception-reporting":
userId: "c17350f3-e8cb-2e43-d2e2-b460fc54dc04"
"file-icons": {}
"git-plus":
general:
_analyticsUserId: "ed178489-d1ba-4896-bf4c-8c58ba6d5d26"
splitPane: "Right"
"goto-definition":
contextMenuDisplayAtFirst: false
"language-babel":
taggedTemplateGrammar: [
"\"(?<=<style jsx>{)|(?<=<style jsx global>{)\":source.css.styled"
]
linter:
disabledProviders: [
"CoffeeLint"
]
lintOnChange: false
"linter-eslint":
advanced:
disableFSCache: true
disabling:
disableWhenNoEslintConfig: false
global:
eslintrcPath: "~"
"linter-ui-default":
panelHeight: 300
showPanel: true
"one-dark-ui":
hideDockButtons: true
"package-sync":
createOnChange: true
forceOverwrite: true
tabs:
enableVcsColoring: true
"todo-show":
sortBy: "Type"
"tree-view":
focusOnReveal: false
hideIgnoredNames: true
hideVcsIgnoredFiles: true
"vim-mode":
startInInsertMode: true
wakatime:
apikey: "Saved in your ~/.wakatime.cfg file"
debug: true
"wakatime-hidden":
lastInit: 1492555628
welcome:
showOnStartup: false
whitespace:
ignoreWhitespaceOnCurrentLine: false
| true | "*":
"activate-power-mode":
autoToggle: false
"atom-alignment": {}
"atom-beautify":
general:
_analyticsUserId: "b1f78f78-1b50-45cf-8acd-d5fc00267baf"
"atom-ide-ui":
use:
"atom-ide-console": "never"
"atom-ide-outline-view": "never"
"atom-ide-refactor": "never"
"atom-ide-terminal": "never"
"circle-ci":
apiToken: "PI:KEY:<KEY>END_PI"
core:
destroyEmptyPanes: false
disabledPackages: [
"github"
"background-tips"
"linter"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
"desktop.ini"
"node_modules"
"bower_components"
"__pycache__"
"*.pyc"
]
packagesWithKeymapsDisabled: [
"activate-power-mode"
"git-plus"
]
telemetryConsent: "limited"
themes: [
"one-dark-ui"
"oceanic-next"
]
titleBar: "custom-inset"
uriHandlerRegistration: "always"
useTreeSitterParsers: false
editor:
fontFamily: "Fira Code"
fontSize: 19
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrapHangingIndent: 2
"exception-reporting":
userId: "c17350f3-e8cb-2e43-d2e2-b460fc54dc04"
"file-icons": {}
"git-plus":
general:
_analyticsUserId: "ed178489-d1ba-4896-bf4c-8c58ba6d5d26"
splitPane: "Right"
"goto-definition":
contextMenuDisplayAtFirst: false
"language-babel":
taggedTemplateGrammar: [
"\"(?<=<style jsx>{)|(?<=<style jsx global>{)\":source.css.styled"
]
linter:
disabledProviders: [
"CoffeeLint"
]
lintOnChange: false
"linter-eslint":
advanced:
disableFSCache: true
disabling:
disableWhenNoEslintConfig: false
global:
eslintrcPath: "~"
"linter-ui-default":
panelHeight: 300
showPanel: true
"one-dark-ui":
hideDockButtons: true
"package-sync":
createOnChange: true
forceOverwrite: true
tabs:
enableVcsColoring: true
"todo-show":
sortBy: "Type"
"tree-view":
focusOnReveal: false
hideIgnoredNames: true
hideVcsIgnoredFiles: true
"vim-mode":
startInInsertMode: true
wakatime:
apikey: "Saved in your ~/.wakatime.cfg file"
debug: true
"wakatime-hidden":
lastInit: 1492555628
welcome:
showOnStartup: false
whitespace:
ignoreWhitespaceOnCurrentLine: false
|
[
{
"context": "\"\n and: \"és\"\n back: \"vissza\"\n changePassword: \"Jelszó megváltoztatása\"\n choosePassword: \"Válassz egy jelszót\"\n clickA",
"end": 152,
"score": 0.9989555478096008,
"start": 130,
"tag": "PASSWORD",
"value": "Jelszó megváltoztatása"
},
{
"context": "word: ... | t9n/hu.coffee | XavierSamuelHuppe/xav-accounts-t9n | 0 | # We need a dummy translation so that a text is found.
hu =
add: "hozzáadás"
and: "és"
back: "vissza"
changePassword: "Jelszó megváltoztatása"
choosePassword: "Válassz egy jelszót"
clickAgree: "A regisztráció gombra kattintva egyetértesz a mi"
configure: "Beállítás"
createAccount: "Felhasználó létrehozása"
currentPassword: "Jelenlegi jelszó"
dontHaveAnAccount: "Nincs még felhasználód?"
email: "Email"
emailAddress: "Email cím"
emailResetLink: "Visszaállító link küldése"
forgotPassword: "Elfelejtetted a jelszavadat?"
ifYouAlreadyHaveAnAccount: "Ha már van felhasználód, "
newPassword: "Új jelszó"
newPasswordAgain: "Új jelszó (ismét)"
optional: "Opcionális"
OR: "VAGY"
password: "Jelszó"
passwordAgain: "Jelszó (ismét)"
privacyPolicy: "Adatvédelmi irányelvek"
remove: "eltávolítás"
resetYourPassword: "Jelszó visszaállítása"
setPassword: "Jelszó beállítása"
sign: "Bejelentkezés"
signIn: "Bejelentkezés"
signin: "jelentkezz be"
signOut: "Kijelentkezés"
signUp: "Regisztráció"
signupCode: "Regisztrációs kód"
signUpWithYourEmailAddress: "Regisztráció email címmel"
terms: "Használati feltételek"
updateYourPassword: "Jelszó módosítása"
username: "Felhasználónév"
usernameOrEmail: "Felhasználónév vagy email"
with: "-"
info:
emailSent: "Email elküldve"
emailVerified: "Email cím igazolva"
passwordChanged: "Jelszó megváltoztatva"
passwordReset: "Jelszó visszaállítva"
error:
emailRequired: "Email cím megadása kötelező."
minChar: "A jelszónak legalább 7 karakter hoszúnak kell lennie."
pwdsDontMatch: "A jelszavak nem egyeznek"
pwOneDigit: "A jelszónak legalább egy számjegyet tartalmaznia kell."
pwOneLetter: "A jelszónak legalább egy betűt tartalmaznia kell."
signInRequired: "A művelet végrehajtásához be kell jelentkezned."
signupCodeIncorrect: "A regisztrációs kód hibás."
signupCodeRequired: "A regisztrációs kód megadása kötelező."
usernameIsEmail: "A felhasználónév nem lehet egy email cím."
usernameRequired: "Felhasználónév megadása kötelező."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "A megadott email cím már létezik."
"Email doesn't match the criteria.": "Email cím nem felel meg a feltételeknek."
"Invalid login token": "Érvénytelen belépési token"
"Login forbidden": "Belépés megtagadva"
#"Service " + options.service + " already configured"
"Service unknown": "Ismeretlen szolgáltatás"
"Unrecognized options for login request": "Ismeretlen beállítások a belépési kérelemhez"
"User validation failed": "Felhasználó azonosítás sikertelen"
"Username already exists.": "A felhasználónév már létezik."
"You are not logged in.": "Nem vagy bejelentkezve."
"You've been logged out by the server. Please log in again.": "A szerver kijelentkeztetett. Kérjük, jelentkezz be újra."
"Your session has expired. Please log in again.": "A munkamenet lejárt. Kérjük, jelentkezz be újra."
#---- accounts-oauth
"No matching login attempt found": "Nem található megegyező belépési próbálkozás"
#---- accounts-password-client
"Password is old. Please reset your password.": "A jelszó túl régi. Kérjük, változtasd meg a jelszavad."
#---- accounts-password
"Incorrect password": "Helytelen jelszó"
"Invalid email": "Érvénytelen email cím"
"Must be logged in": "A művelet végrehajtásához bejelentkezés szükséges"
"Need to set a username or email": "Felhasználónév vagy email cím beállítása kötelező"
"old password format": "régi jelszó formátum"
"Password may not be empty": "A jelszó nem lehet üres"
"Signups forbidden": "Regisztráció megtagadva"
"Token expired": "Token lejárt"
"Token has invalid email address": "A token érvénytelen email címet tartalmaz"
"User has no password set": "A felhasználóhoz nincs jelszó beállítva"
"User not found": "Felhasználó nem található"
"Verify email link expired": "Igazoló email link lejárt"
"Verify email link is for unknown address": "Az igazoló email link ismeretlen címhez tartozik"
#---- match
"Match failed": "Megegyeztetés sikertelen"
#---- Misc...
"Unknown error": "Ismeretlen hiba"
T9n.map "hu", hu | 38653 | # We need a dummy translation so that a text is found.
hu =
add: "hozzáadás"
and: "és"
back: "vissza"
changePassword: "<PASSWORD>"
choosePassword: "<PASSWORD>"
clickAgree: "A regisztráció gombra kattintva egyetértesz a mi"
configure: "Beállítás"
createAccount: "Felhasználó létrehozása"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Nincs még felhasználód?"
email: "Email"
emailAddress: "Email cím"
emailResetLink: "Visszaállító link küldése"
forgotPassword: "<PASSWORD>?"
ifYouAlreadyHaveAnAccount: "Ha már van felhasználód, "
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD> (ism<PASSWORD>)"
optional: "Opcionális"
OR: "VAGY"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD>)"
privacyPolicy: "Adatvédelmi irányelvek"
remove: "eltávolítás"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD>"
sign: "Bejelentkezés"
signIn: "Bejelentkezés"
signin: "jelentkezz be"
signOut: "Kijelentkezés"
signUp: "Regisztráció"
signupCode: "Regisztrációs kód"
signUpWithYourEmailAddress: "Regisztráció email címmel"
terms: "Használati feltételek"
updateYourPassword: "<PASSWORD>"
username: "Felhasználónév"
usernameOrEmail: "Felhasználónév vagy email"
with: "-"
info:
emailSent: "Email elküldve"
emailVerified: "Email cím igazolva"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "Email cím megadása kötelező."
minChar: "A jelszónak legalább 7 karakter hoszúnak kell lennie."
pwdsDontMatch: "A jelszavak nem egyeznek"
pwOneDigit: "A jelszónak legalább egy számjegyet tartalmaznia kell."
pwOneLetter: "A jelszónak legalább egy betűt tartalmaznia kell."
signInRequired: "A művelet végrehajtásához be kell jelentkezned."
signupCodeIncorrect: "A regisztrációs kód hibás."
signupCodeRequired: "A regisztrációs kód megadása kötelező."
usernameIsEmail: "A <NAME>használónév nem lehet egy email cím."
usernameRequired: "<NAME>tele<NAME>."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "A megadott email cím már létezik."
"Email doesn't match the criteria.": "Email cím nem felel meg a feltételeknek."
"Invalid login token": "Érvénytelen belépési token"
"Login forbidden": "Belépés megtagadva"
#"Service " + options.service + " already configured"
"Service unknown": "Ismeretlen szolgáltatás"
"Unrecognized options for login request": "Ismeretlen beállítások a belépési kérelemhez"
"User validation failed": "Felhasználó azonosítás sikertelen"
"Username already exists.": "A felhasználónév már létezik."
"You are not logged in.": "Nem vagy bejelentkezve."
"You've been logged out by the server. Please log in again.": "A szerver kijelentkeztetett. Kérjük, jelentkezz be újra."
"Your session has expired. Please log in again.": "A munkamenet lejárt. Kérjük, jelentkezz be újra."
#---- accounts-oauth
"No matching login attempt found": "Nem található megegyező belépési próbálkozás"
#---- accounts-password-client
"Password is old. Please reset your password.": "A jelszó túl régi. Kérjük, változtasd meg a jelszavad."
#---- accounts-password
"Incorrect password": "<PASSWORD>"
"Invalid email": "Érvénytelen email cím"
"Must be logged in": "A művelet végrehajtásához bejelentkezés szükséges"
"Need to set a username or email": "Felhasználónév vagy email cím beállítása kötelező"
"old password format": "régi jelszó formátum"
"Password may not be empty": "A jelszó nem lehet üres"
"Signups forbidden": "Regisztráció megtagadva"
"Token expired": "Token lejárt"
"Token has invalid email address": "A token érvénytelen email címet tartalmaz"
"User has no password set": "A felhasználóhoz nincs jelszó beállítva"
"User not found": "Felhasználó nem található"
"Verify email link expired": "Igazoló email link lejárt"
"Verify email link is for unknown address": "Az igazoló email link ismeretlen címhez tartozik"
#---- match
"Match failed": "Megegyeztetés sikertelen"
#---- Misc...
"Unknown error": "Ismeretlen hiba"
T9n.map "hu", hu | true | # We need a dummy translation so that a text is found.
hu =
add: "hozzáadás"
and: "és"
back: "vissza"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "A regisztráció gombra kattintva egyetértesz a mi"
configure: "Beállítás"
createAccount: "Felhasználó létrehozása"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Nincs még felhasználód?"
email: "Email"
emailAddress: "Email cím"
emailResetLink: "Visszaállító link küldése"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?"
ifYouAlreadyHaveAnAccount: "Ha már van felhasználód, "
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI (ismPI:PASSWORD:<PASSWORD>END_PI)"
optional: "Opcionális"
OR: "VAGY"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI)"
privacyPolicy: "Adatvédelmi irányelvek"
remove: "eltávolítás"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Bejelentkezés"
signIn: "Bejelentkezés"
signin: "jelentkezz be"
signOut: "Kijelentkezés"
signUp: "Regisztráció"
signupCode: "Regisztrációs kód"
signUpWithYourEmailAddress: "Regisztráció email címmel"
terms: "Használati feltételek"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
username: "Felhasználónév"
usernameOrEmail: "Felhasználónév vagy email"
with: "-"
info:
emailSent: "Email elküldve"
emailVerified: "Email cím igazolva"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "Email cím megadása kötelező."
minChar: "A jelszónak legalább 7 karakter hoszúnak kell lennie."
pwdsDontMatch: "A jelszavak nem egyeznek"
pwOneDigit: "A jelszónak legalább egy számjegyet tartalmaznia kell."
pwOneLetter: "A jelszónak legalább egy betűt tartalmaznia kell."
signInRequired: "A művelet végrehajtásához be kell jelentkezned."
signupCodeIncorrect: "A regisztrációs kód hibás."
signupCodeRequired: "A regisztrációs kód megadása kötelező."
usernameIsEmail: "A PI:NAME:<NAME>END_PIhasználónév nem lehet egy email cím."
usernameRequired: "PI:NAME:<NAME>END_PItelePI:NAME:<NAME>END_PI."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "A megadott email cím már létezik."
"Email doesn't match the criteria.": "Email cím nem felel meg a feltételeknek."
"Invalid login token": "Érvénytelen belépési token"
"Login forbidden": "Belépés megtagadva"
#"Service " + options.service + " already configured"
"Service unknown": "Ismeretlen szolgáltatás"
"Unrecognized options for login request": "Ismeretlen beállítások a belépési kérelemhez"
"User validation failed": "Felhasználó azonosítás sikertelen"
"Username already exists.": "A felhasználónév már létezik."
"You are not logged in.": "Nem vagy bejelentkezve."
"You've been logged out by the server. Please log in again.": "A szerver kijelentkeztetett. Kérjük, jelentkezz be újra."
"Your session has expired. Please log in again.": "A munkamenet lejárt. Kérjük, jelentkezz be újra."
#---- accounts-oauth
"No matching login attempt found": "Nem található megegyező belépési próbálkozás"
#---- accounts-password-client
"Password is old. Please reset your password.": "A jelszó túl régi. Kérjük, változtasd meg a jelszavad."
#---- accounts-password
"Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI"
"Invalid email": "Érvénytelen email cím"
"Must be logged in": "A művelet végrehajtásához bejelentkezés szükséges"
"Need to set a username or email": "Felhasználónév vagy email cím beállítása kötelező"
"old password format": "régi jelszó formátum"
"Password may not be empty": "A jelszó nem lehet üres"
"Signups forbidden": "Regisztráció megtagadva"
"Token expired": "Token lejárt"
"Token has invalid email address": "A token érvénytelen email címet tartalmaz"
"User has no password set": "A felhasználóhoz nincs jelszó beállítva"
"User not found": "Felhasználó nem található"
"Verify email link expired": "Igazoló email link lejárt"
"Verify email link is for unknown address": "Az igazoló email link ismeretlen címhez tartozik"
#---- match
"Match failed": "Megegyeztetés sikertelen"
#---- Misc...
"Unknown error": "Ismeretlen hiba"
T9n.map "hu", hu |
[
{
"context": "/bundle/dependencies/depsVars/hi', {joke: {joke2:'JOKER'}}\n expect(oClone).to.deep.equal o\n e",
"end": 1981,
"score": 0.5495238304138184,
"start": 1978,
"tag": "KEY",
"value": "JOK"
},
{
"context": " dependencies: depsVars: newKey: {joke: {joke2:'JOKER'}}\n... | source/spec/objects/setp-spec.coffee | anodynos/uBerscore | 1 | describe 'objects/setp:', ->
o =
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
describe 'existent paths:', ->
it "primitive", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars', 'just_a_String'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: 'just_a_String'
# expect(isSet).to.be.true
it "object, with sep at end & alt sep", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.depsVars.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: property: 'just_a_String'
expect(isSet).to.be.true
it "object, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: property: 'just_a_String'
expect(isSet).to.be.true
it "array item, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.anArray.2.arrayItem3',
{'3_is_now': 33}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3': {'3_is_now': 33} ]
dependencies: depsVars: "Bingo"
expect(isSet).to.be.true
describe 'inexistent key paths:', ->
it "not setting by default", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/hi', {joke: {joke2:'JOKER'}}
expect(oClone).to.deep.equal o
expect(isSet).to.be.false
describe 'options.create:', ->
it "create new objects for inexistent paths, adding object properties", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.moreDeps.evenMoreDeps.',
{property: 'just_a_String'}, {create:true, separator: '.'}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
moreDeps: evenMoreDeps: {property: 'just_a_String'}
expect(isSet).to.be.true
it "NOT overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/',
{property: 'just_a_String'}, {create:true}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
expect(isSet).to.be.false
describe 'options.overwrite:', ->
it "create new objects, overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey',
{joke: {joke2:'JOKER'}}, {overwrite:true}
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: newKey: {joke: {joke2:'JOKER'}}
expect(isSet).to.be.true
it "create new objects, preserving `oldValue`", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/anotherNewKey',
{joke: {joke2:'JOKER'}}, overwrite: '_oldValue'
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars:
_oldValue: 'Bingo'
newKey: anotherNewKey: {joke: {joke2:'JOKER'}}
expect(isSet).to.be.true | 57063 | describe 'objects/setp:', ->
o =
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
describe 'existent paths:', ->
it "primitive", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars', 'just_a_String'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: 'just_a_String'
# expect(isSet).to.be.true
it "object, with sep at end & alt sep", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.depsVars.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: property: 'just_a_String'
expect(isSet).to.be.true
it "object, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: property: 'just_a_String'
expect(isSet).to.be.true
it "array item, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.anArray.2.arrayItem3',
{'3_is_now': 33}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3': {'3_is_now': 33} ]
dependencies: depsVars: "Bingo"
expect(isSet).to.be.true
describe 'inexistent key paths:', ->
it "not setting by default", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/hi', {joke: {joke2:'<KEY>ER'}}
expect(oClone).to.deep.equal o
expect(isSet).to.be.false
describe 'options.create:', ->
it "create new objects for inexistent paths, adding object properties", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.moreDeps.evenMoreDeps.',
{property: 'just_a_String'}, {create:true, separator: '.'}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
moreDeps: evenMoreDeps: {property: 'just_a_String'}
expect(isSet).to.be.true
it "NOT overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/',
{property: 'just_a_String'}, {create:true}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
expect(isSet).to.be.false
describe 'options.overwrite:', ->
it "create new objects, overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey',
{joke: {joke2:'JOKER'}}, {overwrite:true}
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: newKey: {joke: {joke2:'J<KEY>ER'}}
expect(isSet).to.be.true
it "create new objects, preserving `oldValue`", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/anotherNewKey',
{joke: {joke2:'<KEY>'}}, overwrite: '_oldValue'
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars:
_oldValue: 'Bingo'
newKey: anotherNewKey: {joke: {joke2:'<KEY>'}}
expect(isSet).to.be.true | true | describe 'objects/setp:', ->
o =
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
describe 'existent paths:', ->
it "primitive", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars', 'just_a_String'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: 'just_a_String'
# expect(isSet).to.be.true
it "object, with sep at end & alt sep", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.depsVars.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: property: 'just_a_String'
expect(isSet).to.be.true
it "object, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.',
{property: 'just_a_String'}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: property: 'just_a_String'
expect(isSet).to.be.true
it "array item, overwriting object property", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.anArray.2.arrayItem3',
{'3_is_now': 33}, separator: '.'
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3': {'3_is_now': 33} ]
dependencies: depsVars: "Bingo"
expect(isSet).to.be.true
describe 'inexistent key paths:', ->
it "not setting by default", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/hi', {joke: {joke2:'PI:KEY:<KEY>END_PIER'}}
expect(oClone).to.deep.equal o
expect(isSet).to.be.false
describe 'options.create:', ->
it "create new objects for inexistent paths, adding object properties", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$.bundle.dependencies.moreDeps.evenMoreDeps.',
{property: 'just_a_String'}, {create:true, separator: '.'}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
moreDeps: evenMoreDeps: {property: 'just_a_String'}
expect(isSet).to.be.true
it "NOT overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/',
{property: 'just_a_String'}, {create:true}
expect(
oClone
).to.deep.equal
'$': bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies:
depsVars: "Bingo"
expect(isSet).to.be.false
describe 'options.overwrite:', ->
it "create new objects, overwritting primitives:", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey',
{joke: {joke2:'JOKER'}}, {overwrite:true}
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars: newKey: {joke: {joke2:'JPI:KEY:<KEY>END_PIER'}}
expect(isSet).to.be.true
it "create new objects, preserving `oldValue`", ->
oClone = _.clone o, true
isSet = _B.setp oClone, '$/bundle/dependencies/depsVars/newKey/anotherNewKey',
{joke: {joke2:'PI:KEY:<KEY>END_PI'}}, overwrite: '_oldValue'
expect(
oClone
).to.deep.equal
'$':
bundle:
anArray: ['arrayItem1', 2, 'arrayItem3':3 ]
dependencies: depsVars:
_oldValue: 'Bingo'
newKey: anotherNewKey: {joke: {joke2:'PI:KEY:<KEY>END_PI'}}
expect(isSet).to.be.true |
[
{
"context": "_defaults =\n id: \"1234\"\n primaryEmail: \"ben.franklin@example.com\"\n name: { givenName: \"Ben\", familyName: \"Fra",
"end": 761,
"score": 0.9999220967292786,
"start": 737,
"tag": "EMAIL",
"value": "ben.franklin@example.com"
},
{
"context": "n.frankli... | test/google_batch.coffee | Clever/node-google-admin-sdk | 11 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
before ->
nock.disableNetConnect()
describe 'Batch Requests', ->
before ->
@options =
token:
access: 'fake_access_token'
@up = new google_apis.UserProvisioning @options
# filter out random boundary strings and set them to a known value so messages can be diff'd
@boundary_filter = (res) ->
res.replace(/\n\-\-[0-9a-zA-Z=]+\n/g, '\n--===============1234567890123456789==\n')
.replace(/\n\-\-[0-9a-zA-Z=]+\-\-/g, '\n--===============1234567890123456789==--')
@user_defaults =
id: "1234"
primaryEmail: "ben.franklin@example.com"
name: { givenName: "Ben", familyName: "Franklin", fullName: "Ben Franklin" }
lastLoginTime: "2013-09-27T18:56:04.000Z"
creationTime: "2013-09-24T22:06:21.000Z"
emails: [{ address: "ben.franklin@example.com", primary: true }]
kind: "admin#directory#user"
isAdmin: false
isDelegatedAdmin: false
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
@request_helper = (ids) ->
request = "\n--===============1234567890123456789=="
for id in ids
request += "\nContent-Type: application/http\n\n" +
"GET /admin/directory/v1/users/#{id} HTTP/1.1\n" +
"--===============1234567890123456789=="
request + "--"
it 'requires options upon construction', ->
assert.throws ->
new google_apis.Batch()
, Error
it 'can perform multiple get requests', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
,
user_id: '5678'
expected_data: _.defaults
id: "5678"
primaryEmail: "admin@example.com"
name: { givenName: "The", familyName: "Admin", fullName: "The Admin" }
isAdmin: true
lastLoginTime: "2013-09-27T18:57:15.000Z"
creationTime: "2013-09-24T21:41:29.000Z"
emails: [{ address: "admin@example.com", primary: true }]
orgUnitPath: "/Google Administrators"
, @user_defaults
,
user_id: '9012'
expected_data: _.defaults
id: "9012"
primaryEmail: "matchmealso@ga4edu.org"
name: { givenName: "User2", familyName: "Match", fullName: "User2 Match" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-08-02T23:31:07.000Z"
emails: [{ address: "matchmealso@ga4edu.org", primary: true }]
orgUnitPath: "/NotAdmins"
, @user_defaults
]
expected_request = @request_helper ['1234', '5678', '9012']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
it 'can send requests with content', (done) ->
get_resp_body = _.defaults { isDelegatedAdmin: true }, @user_defaults
patch_req_body = {name: {familyName: 'Jefferson', givenName: 'Thomas'}}
patch_resp_body = _.defaults
kind: "admin#directory#user"
id: "55555"
primaryEmail: "thomas.jefferson@example.com"
name: { givenName: "Thomas", familyName: "Jefferson" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
emails: [{ address: "thomas.jefferson@example.com", primary: true }]
, @user_defaults
expected_request =
"\n--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"GET /admin/directory/v1/users/1234 HTTP/1.1\n" +
"--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"PATCH /admin/directory/v1/users/55555 HTTP/1.1\n" +
"Content-Type: application/json\n" +
"content-length: #{(JSON.stringify patch_req_body).length}\n\n" +
"#{JSON.stringify patch_req_body}\n" +
"--===============1234567890123456789==--"
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify get_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify patch_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = [(@up.get '1234'), (@up.patch '55555', patch_req_body)]
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, [get_resp_body, patch_resp_body]), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test, result.body
done()
it 'will throw a batch error correctly', (done) ->
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.post('/batch/admin/directory_v1')
.reply 404, "We accidently rimraf"
batch = new google_apis.Batch @options
batch.go [(@up.get 'bad_id'), (@up.get 'bad_id_2')], (err, results) ->
assert err?
done()
it 'will retry slowly if rate-limited', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
]
expected_request = @request_helper ['1234']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
| 186372 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
before ->
nock.disableNetConnect()
describe 'Batch Requests', ->
before ->
@options =
token:
access: 'fake_access_token'
@up = new google_apis.UserProvisioning @options
# filter out random boundary strings and set them to a known value so messages can be diff'd
@boundary_filter = (res) ->
res.replace(/\n\-\-[0-9a-zA-Z=]+\n/g, '\n--===============1234567890123456789==\n')
.replace(/\n\-\-[0-9a-zA-Z=]+\-\-/g, '\n--===============1234567890123456789==--')
@user_defaults =
id: "1234"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" }
lastLoginTime: "2013-09-27T18:56:04.000Z"
creationTime: "2013-09-24T22:06:21.000Z"
emails: [{ address: "<EMAIL>", primary: true }]
kind: "admin#directory#user"
isAdmin: false
isDelegatedAdmin: false
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
@request_helper = (ids) ->
request = "\n--===============1234567890123456789=="
for id in ids
request += "\nContent-Type: application/http\n\n" +
"GET /admin/directory/v1/users/#{id} HTTP/1.1\n" +
"--===============1234567890123456789=="
request + "--"
it 'requires options upon construction', ->
assert.throws ->
new google_apis.Batch()
, Error
it 'can perform multiple get requests', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
,
user_id: '5678'
expected_data: _.defaults
id: "5678"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" }
isAdmin: true
lastLoginTime: "2013-09-27T18:57:15.000Z"
creationTime: "2013-09-24T21:41:29.000Z"
emails: [{ address: "<EMAIL>", primary: true }]
orgUnitPath: "/Google Administrators"
, @user_defaults
,
user_id: '9012'
expected_data: _.defaults
id: "9012"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-08-02T23:31:07.000Z"
emails: [{ address: "<EMAIL>", primary: true }]
orgUnitPath: "/NotAdmins"
, @user_defaults
]
expected_request = @request_helper ['1234', '5678', '9012']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
it 'can send requests with content', (done) ->
get_resp_body = _.defaults { isDelegatedAdmin: true }, @user_defaults
patch_req_body = {name: {familyName: '<NAME>', givenName: '<NAME>'}}
patch_resp_body = _.defaults
kind: "admin#directory#user"
id: "55555"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
emails: [{ address: "<EMAIL>", primary: true }]
, @user_defaults
expected_request =
"\n--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"GET /admin/directory/v1/users/1234 HTTP/1.1\n" +
"--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"PATCH /admin/directory/v1/users/55555 HTTP/1.1\n" +
"Content-Type: application/json\n" +
"content-length: #{(JSON.stringify patch_req_body).length}\n\n" +
"#{JSON.stringify patch_req_body}\n" +
"--===============1234567890123456789==--"
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify get_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify patch_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = [(@up.get '1234'), (@up.patch '55555', patch_req_body)]
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, [get_resp_body, patch_resp_body]), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test, result.body
done()
it 'will throw a batch error correctly', (done) ->
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.post('/batch/admin/directory_v1')
.reply 404, "We accidently rimraf"
batch = new google_apis.Batch @options
batch.go [(@up.get 'bad_id'), (@up.get 'bad_id_2')], (err, results) ->
assert err?
done()
it 'will retry slowly if rate-limited', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
]
expected_request = @request_helper ['1234']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
| true | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
before ->
nock.disableNetConnect()
describe 'Batch Requests', ->
before ->
@options =
token:
access: 'fake_access_token'
@up = new google_apis.UserProvisioning @options
# filter out random boundary strings and set them to a known value so messages can be diff'd
@boundary_filter = (res) ->
res.replace(/\n\-\-[0-9a-zA-Z=]+\n/g, '\n--===============1234567890123456789==\n')
.replace(/\n\-\-[0-9a-zA-Z=]+\-\-/g, '\n--===============1234567890123456789==--')
@user_defaults =
id: "1234"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" }
lastLoginTime: "2013-09-27T18:56:04.000Z"
creationTime: "2013-09-24T22:06:21.000Z"
emails: [{ address: "PI:EMAIL:<EMAIL>END_PI", primary: true }]
kind: "admin#directory#user"
isAdmin: false
isDelegatedAdmin: false
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
@request_helper = (ids) ->
request = "\n--===============1234567890123456789=="
for id in ids
request += "\nContent-Type: application/http\n\n" +
"GET /admin/directory/v1/users/#{id} HTTP/1.1\n" +
"--===============1234567890123456789=="
request + "--"
it 'requires options upon construction', ->
assert.throws ->
new google_apis.Batch()
, Error
it 'can perform multiple get requests', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
,
user_id: '5678'
expected_data: _.defaults
id: "5678"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" }
isAdmin: true
lastLoginTime: "2013-09-27T18:57:15.000Z"
creationTime: "2013-09-24T21:41:29.000Z"
emails: [{ address: "PI:EMAIL:<EMAIL>END_PI", primary: true }]
orgUnitPath: "/Google Administrators"
, @user_defaults
,
user_id: '9012'
expected_data: _.defaults
id: "9012"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-08-02T23:31:07.000Z"
emails: [{ address: "PI:EMAIL:<EMAIL>END_PI", primary: true }]
orgUnitPath: "/NotAdmins"
, @user_defaults
]
expected_request = @request_helper ['1234', '5678', '9012']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
it 'can send requests with content', (done) ->
get_resp_body = _.defaults { isDelegatedAdmin: true }, @user_defaults
patch_req_body = {name: {familyName: 'PI:NAME:<NAME>END_PI', givenName: 'PI:NAME:<NAME>END_PI'}}
patch_resp_body = _.defaults
kind: "admin#directory#user"
id: "55555"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI" }
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
emails: [{ address: "PI:EMAIL:<EMAIL>END_PI", primary: true }]
, @user_defaults
expected_request =
"\n--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"GET /admin/directory/v1/users/1234 HTTP/1.1\n" +
"--===============1234567890123456789==\n" +
"Content-Type: application/http\n\n" +
"PATCH /admin/directory/v1/users/55555 HTTP/1.1\n" +
"Content-Type: application/json\n" +
"content-length: #{(JSON.stringify patch_req_body).length}\n\n" +
"#{JSON.stringify patch_req_body}\n" +
"--===============1234567890123456789==--"
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify get_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify patch_resp_body
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = [(@up.get '1234'), (@up.patch '55555', patch_req_body)]
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, [get_resp_body, patch_resp_body]), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test, result.body
done()
it 'will throw a batch error correctly', (done) ->
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.post('/batch/admin/directory_v1')
.reply 404, "We accidently rimraf"
batch = new google_apis.Batch @options
batch.go [(@up.get 'bad_id'), (@up.get 'bad_id_2')], (err, results) ->
assert err?
done()
it 'will retry slowly if rate-limited', (done) ->
#nock.recorder.rec()
test_data = [
user_id: '1234'
expected_data: _.defaults { isDelegatedAdmin: true }, @user_defaults
]
expected_request = @request_helper ['1234']
expected_reply = "--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
_.each test_data, (test) =>
expected_reply += "Content-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
expected_reply += JSON.stringify test.expected_data
expected_reply += "\r\n--batch_7av0UPcSyII=_ABKN5zORmiQ=\r\n"
expected_reply += "--"
nock('https://www.googleapis.com:443')
.get('/oauth2/v1/tokeninfo?access_token=fake_access_token')
.reply(200, "OK")
.filteringRequestBody(@boundary_filter)
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply(503, 'Enhance your calm')
.post('/batch/admin/directory_v1', expected_request)
.reply 200, expected_reply,
{ 'content-type': 'multipart/mixed; boundary=batch_7av0UPcSyII=_ABKN5zORmiQ=' }
queries = _(test_data).map (test) => @up.get test.user_id
batch = new google_apis.Batch @options
batch.go queries, (err, results) ->
assert.ifError err
_.each (_.zip results, test_data), ([result, test]) ->
assert.equal result.statusCode, 200
assert.deepEqual test.expected_data, result.body
done()
|
[
{
"context": "onstrainToCircle' module example project v1.0\n# by Marc Krenn, Sept. 2015 | marc.krenn@gmail.com | @marc_krenn\n",
"end": 65,
"score": 0.9998833537101746,
"start": 55,
"tag": "NAME",
"value": "Marc Krenn"
},
{
"context": "example project v1.0\n# by Marc Krenn, Sept. 20... | constrainToCircleExample.framer/app.coffee | marckrenn/framer-constrainToCircle | 15 | # 'constrainToCircle' module example project v1.0
# by Marc Krenn, Sept. 2015 | marc.krenn@gmail.com | @marc_krenn
# Include module
constrainToCircle = require "constrainToCircle"
# Set background
bg = new BackgroundLayer backgroundColor: "#28affa"
bg.bringToFront()
# Create layer
layerA = new Layer
width: 100
height: 100
backgroundColor: "#fff"
borderRadius: "100%"
# Constraints/circle layer
constraints = new Layer
width: 400
height: 400
backgroundColor: "rgba(255,255,255, 0.2)"
borderRadius: "100%"
# Center layers
constraints.center()
layerA.center()
# Find centerpoint of constraints-layer
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
# Enable dragging and constrain dragging-distance to a defined circle
# constrainToCircle.enable(layer,circleCenterX,circleCenterY,radius)
constrainToCircle.enable(layerA,circleCenterX,circleCenterY,constraints.width/2)
# ... can be disabled with
# constrainToCircle.disable(layerA)
# Animate to original position
layerA.on Events.DragEnd, ->
layerA.animate
properties:
x: circleCenterX
y : circleCenterY
curve: "spring(300,10,0)"
# Update on window-resize
window.onresize = ->
constraints.center()
layerA.center()
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
constrainToCircle.update(layerA,circleCenterX,circleCenterY,constraints.width/2) | 211111 | # 'constrainToCircle' module example project v1.0
# by <NAME>, Sept. 2015 | <EMAIL> | @marc_krenn
# Include module
constrainToCircle = require "constrainToCircle"
# Set background
bg = new BackgroundLayer backgroundColor: "#28affa"
bg.bringToFront()
# Create layer
layerA = new Layer
width: 100
height: 100
backgroundColor: "#fff"
borderRadius: "100%"
# Constraints/circle layer
constraints = new Layer
width: 400
height: 400
backgroundColor: "rgba(255,255,255, 0.2)"
borderRadius: "100%"
# Center layers
constraints.center()
layerA.center()
# Find centerpoint of constraints-layer
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
# Enable dragging and constrain dragging-distance to a defined circle
# constrainToCircle.enable(layer,circleCenterX,circleCenterY,radius)
constrainToCircle.enable(layerA,circleCenterX,circleCenterY,constraints.width/2)
# ... can be disabled with
# constrainToCircle.disable(layerA)
# Animate to original position
layerA.on Events.DragEnd, ->
layerA.animate
properties:
x: circleCenterX
y : circleCenterY
curve: "spring(300,10,0)"
# Update on window-resize
window.onresize = ->
constraints.center()
layerA.center()
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
constrainToCircle.update(layerA,circleCenterX,circleCenterY,constraints.width/2) | true | # 'constrainToCircle' module example project v1.0
# by PI:NAME:<NAME>END_PI, Sept. 2015 | PI:EMAIL:<EMAIL>END_PI | @marc_krenn
# Include module
constrainToCircle = require "constrainToCircle"
# Set background
bg = new BackgroundLayer backgroundColor: "#28affa"
bg.bringToFront()
# Create layer
layerA = new Layer
width: 100
height: 100
backgroundColor: "#fff"
borderRadius: "100%"
# Constraints/circle layer
constraints = new Layer
width: 400
height: 400
backgroundColor: "rgba(255,255,255, 0.2)"
borderRadius: "100%"
# Center layers
constraints.center()
layerA.center()
# Find centerpoint of constraints-layer
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
# Enable dragging and constrain dragging-distance to a defined circle
# constrainToCircle.enable(layer,circleCenterX,circleCenterY,radius)
constrainToCircle.enable(layerA,circleCenterX,circleCenterY,constraints.width/2)
# ... can be disabled with
# constrainToCircle.disable(layerA)
# Animate to original position
layerA.on Events.DragEnd, ->
layerA.animate
properties:
x: circleCenterX
y : circleCenterY
curve: "spring(300,10,0)"
# Update on window-resize
window.onresize = ->
constraints.center()
layerA.center()
circleCenterX = constraints.midX - (layerA.width/2)
circleCenterY = constraints.midY - (layerA.height/2)
constrainToCircle.update(layerA,circleCenterX,circleCenterY,constraints.width/2) |
[
{
"context": "###*\n * Gridfw \n * @copyright khalid RAFIK 2019\n###\n'use strict'\nparseRange = require 'range",
"end": 42,
"score": 0.9985482692718506,
"start": 30,
"tag": "NAME",
"value": "khalid RAFIK"
}
] | assets/index.coffee | gridfw/uploader | 0 | ###*
* Gridfw
* @copyright khalid RAFIK 2019
###
'use strict'
parseRange = require 'range-parser'
Busboy = require 'busboy'
RawBody= require 'raw-body'
Zlib = require 'zlib'
Iconv= require 'iconv-lite'
NativeFs = require 'fs'
fs = require 'mz/fs'
Path = require 'path'
# utils
_create= Object.create
#=include _settings.coffee
#=include _upload.coffee
REQUEST_PROTO=
###*
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|array}
* @public
###
range: (size, options) ->
range = @getHeader 'Range'
if range
parseRange size, range, options
###*
* Upload post data
* @param {Object} options.limits - @see busboy limits
* @param {function} options.onError(error, ctx) - do what ever when got error, reject error to cancel process
* @return {promise}
###
upload: _uploadPostData
CONTEXT_PROTO=
upload: _uploadPostData
class Uploader
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
# Load settings
_initSettings @app, settings
# enable
@enable()
return
###*
* destroy
###
destroy: -> @disable
###*
* Disable, enable
###
disable: ->
@app.removeProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
enable: ->
@app.addProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
module.exports = Uploader
| 151279 | ###*
* Gridfw
* @copyright <NAME> 2019
###
'use strict'
parseRange = require 'range-parser'
Busboy = require 'busboy'
RawBody= require 'raw-body'
Zlib = require 'zlib'
Iconv= require 'iconv-lite'
NativeFs = require 'fs'
fs = require 'mz/fs'
Path = require 'path'
# utils
_create= Object.create
#=include _settings.coffee
#=include _upload.coffee
REQUEST_PROTO=
###*
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|array}
* @public
###
range: (size, options) ->
range = @getHeader 'Range'
if range
parseRange size, range, options
###*
* Upload post data
* @param {Object} options.limits - @see busboy limits
* @param {function} options.onError(error, ctx) - do what ever when got error, reject error to cancel process
* @return {promise}
###
upload: _uploadPostData
CONTEXT_PROTO=
upload: _uploadPostData
class Uploader
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
# Load settings
_initSettings @app, settings
# enable
@enable()
return
###*
* destroy
###
destroy: -> @disable
###*
* Disable, enable
###
disable: ->
@app.removeProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
enable: ->
@app.addProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
module.exports = Uploader
| true | ###*
* Gridfw
* @copyright PI:NAME:<NAME>END_PI 2019
###
'use strict'
parseRange = require 'range-parser'
Busboy = require 'busboy'
RawBody= require 'raw-body'
Zlib = require 'zlib'
Iconv= require 'iconv-lite'
NativeFs = require 'fs'
fs = require 'mz/fs'
Path = require 'path'
# utils
_create= Object.create
#=include _settings.coffee
#=include _upload.coffee
REQUEST_PROTO=
###*
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|array}
* @public
###
range: (size, options) ->
range = @getHeader 'Range'
if range
parseRange size, range, options
###*
* Upload post data
* @param {Object} options.limits - @see busboy limits
* @param {function} options.onError(error, ctx) - do what ever when got error, reject error to cancel process
* @return {promise}
###
upload: _uploadPostData
CONTEXT_PROTO=
upload: _uploadPostData
class Uploader
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
# Load settings
_initSettings @app, settings
# enable
@enable()
return
###*
* destroy
###
destroy: -> @disable
###*
* Disable, enable
###
disable: ->
@app.removeProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
enable: ->
@app.addProperties 'Uploader',
Request: REQUEST_PROTO
Context: CONTEXT_PROTO
return
module.exports = Uploader
|
[
{
"context": "eep Fir'\n 'hex': '002900'\n }\n {\n 'name': 'Burnham'\n 'hex': '002E20'\n }\n {\n 'name': 'Interna",
"end": 449,
"score": 0.9539893865585327,
"start": 442,
"tag": "NAME",
"value": "Burnham"
},
{
"context": "ht Blue'\n 'hex': '003366'\n }\n {\n '... | lib/colornamer-colors.coffee | lysyi3m/colorname | 9 | module.exports = [
{
'name': 'Black'
'hex': '000000'
}
{
'name': 'Navy Blue'
'hex': '000080'
}
{
'name': 'Dark Blue'
'hex': '0000C8'
}
{
'name': 'Blue'
'hex': '0000FF'
}
{
'name': 'Stratos'
'hex': '000741'
}
{
'name': 'Swamp'
'hex': '001B1C'
}
{
'name': 'Resolution Blue'
'hex': '002387'
}
{
'name': 'Deep Fir'
'hex': '002900'
}
{
'name': 'Burnham'
'hex': '002E20'
}
{
'name': 'International Klein Blue'
'hex': '002FA7'
}
{
'name': 'Prussian Blue'
'hex': '003153'
}
{
'name': 'Midnight Blue'
'hex': '003366'
}
{
'name': 'Smalt'
'hex': '003399'
}
{
'name': 'Deep Teal'
'hex': '003532'
}
{
'name': 'Cyprus'
'hex': '003E40'
}
{
'name': 'Kaitoke Green'
'hex': '004620'
}
{
'name': 'Cobalt'
'hex': '0047AB'
}
{
'name': 'Crusoe'
'hex': '004816'
}
{
'name': 'Sherpa Blue'
'hex': '004950'
}
{
'name': 'Endeavour'
'hex': '0056A7'
}
{
'name': 'Camarone'
'hex': '00581A'
}
{
'name': 'Science Blue'
'hex': '0066CC'
}
{
'name': 'Blue Ribbon'
'hex': '0066FF'
}
{
'name': 'Tropical Rain Forest'
'hex': '00755E'
}
{
'name': 'Allports'
'hex': '0076A3'
}
{
'name': 'Deep Cerulean'
'hex': '007BA7'
}
{
'name': 'Lochmara'
'hex': '007EC7'
}
{
'name': 'Azure Radiance'
'hex': '007FFF'
}
{
'name': 'Teal'
'hex': '008080'
}
{
'name': 'Bondi Blue'
'hex': '0095B6'
}
{
'name': 'Pacific Blue'
'hex': '009DC4'
}
{
'name': 'Persian Green'
'hex': '00A693'
}
{
'name': 'Jade'
'hex': '00A86B'
}
{
'name': 'Caribbean Green'
'hex': '00CC99'
}
{
'name': 'Robin\'s Egg Blue'
'hex': '00CCCC'
}
{
'name': 'Green'
'hex': '00FF00'
}
{
'name': 'Spring Green'
'hex': '00FF7F'
}
{
'name': 'Cyan / Aqua'
'hex': '00FFFF'
}
{
'name': 'Blue Charcoal'
'hex': '010D1A'
}
{
'name': 'Midnight'
'hex': '011635'
}
{
'name': 'Holly'
'hex': '011D13'
}
{
'name': 'Daintree'
'hex': '012731'
}
{
'name': 'Cardin Green'
'hex': '01361C'
}
{
'name': 'County Green'
'hex': '01371A'
}
{
'name': 'Astronaut Blue'
'hex': '013E62'
}
{
'name': 'Regal Blue'
'hex': '013F6A'
}
{
'name': 'Aqua Deep'
'hex': '014B43'
}
{
'name': 'Orient'
'hex': '015E85'
}
{
'name': 'Blue Stone'
'hex': '016162'
}
{
'name': 'Fun Green'
'hex': '016D39'
}
{
'name': 'Pine Green'
'hex': '01796F'
}
{
'name': 'Blue Lagoon'
'hex': '017987'
}
{
'name': 'Deep Sea'
'hex': '01826B'
}
{
'name': 'Green Haze'
'hex': '01A368'
}
{
'name': 'English Holly'
'hex': '022D15'
}
{
'name': 'Sherwood Green'
'hex': '02402C'
}
{
'name': 'Congress Blue'
'hex': '02478E'
}
{
'name': 'Evening Sea'
'hex': '024E46'
}
{
'name': 'Bahama Blue'
'hex': '026395'
}
{
'name': 'Observatory'
'hex': '02866F'
}
{
'name': 'Cerulean'
'hex': '02A4D3'
}
{
'name': 'Tangaroa'
'hex': '03163C'
}
{
'name': 'Green Vogue'
'hex': '032B52'
}
{
'name': 'Mosque'
'hex': '036A6E'
}
{
'name': 'Midnight Moss'
'hex': '041004'
}
{
'name': 'Black Pearl'
'hex': '041322'
}
{
'name': 'Blue Whale'
'hex': '042E4C'
}
{
'name': 'Zuccini'
'hex': '044022'
}
{
'name': 'Teal Blue'
'hex': '044259'
}
{
'name': 'Deep Cove'
'hex': '051040'
}
{
'name': 'Gulf Blue'
'hex': '051657'
}
{
'name': 'Venice Blue'
'hex': '055989'
}
{
'name': 'Watercourse'
'hex': '056F57'
}
{
'name': 'Catalina Blue'
'hex': '062A78'
}
{
'name': 'Tiber'
'hex': '063537'
}
{
'name': 'Gossamer'
'hex': '069B81'
}
{
'name': 'Niagara'
'hex': '06A189'
}
{
'name': 'Tarawera'
'hex': '073A50'
}
{
'name': 'Jaguar'
'hex': '080110'
}
{
'name': 'Black Bean'
'hex': '081910'
}
{
'name': 'Deep Sapphire'
'hex': '082567'
}
{
'name': 'Elf Green'
'hex': '088370'
}
{
'name': 'Bright Turquoise'
'hex': '08E8DE'
}
{
'name': 'Downriver'
'hex': '092256'
}
{
'name': 'Palm Green'
'hex': '09230F'
}
{
'name': 'Madison'
'hex': '09255D'
}
{
'name': 'Bottle Green'
'hex': '093624'
}
{
'name': 'Deep Sea Green'
'hex': '095859'
}
{
'name': 'Salem'
'hex': '097F4B'
}
{
'name': 'Black Russian'
'hex': '0A001C'
}
{
'name': 'Dark Fern'
'hex': '0A480D'
}
{
'name': 'Japanese Laurel'
'hex': '0A6906'
}
{
'name': 'Atoll'
'hex': '0A6F75'
}
{
'name': 'Cod Gray'
'hex': '0B0B0B'
}
{
'name': 'Marshland'
'hex': '0B0F08'
}
{
'name': 'Gordons Green'
'hex': '0B1107'
}
{
'name': 'Black Forest'
'hex': '0B1304'
}
{
'name': 'San Felix'
'hex': '0B6207'
}
{
'name': 'Malachite'
'hex': '0BDA51'
}
{
'name': 'Ebony'
'hex': '0C0B1D'
}
{
'name': 'Woodsmoke'
'hex': '0C0D0F'
}
{
'name': 'Racing Green'
'hex': '0C1911'
}
{
'name': 'Surfie Green'
'hex': '0C7A79'
}
{
'name': 'Blue Chill'
'hex': '0C8990'
}
{
'name': 'Black Rock'
'hex': '0D0332'
}
{
'name': 'Bunker'
'hex': '0D1117'
}
{
'name': 'Aztec'
'hex': '0D1C19'
}
{
'name': 'Bush'
'hex': '0D2E1C'
}
{
'name': 'Cinder'
'hex': '0E0E18'
}
{
'name': 'Firefly'
'hex': '0E2A30'
}
{
'name': 'Torea Bay'
'hex': '0F2D9E'
}
{
'name': 'Vulcan'
'hex': '10121D'
}
{
'name': 'Green Waterloo'
'hex': '101405'
}
{
'name': 'Eden'
'hex': '105852'
}
{
'name': 'Arapawa'
'hex': '110C6C'
}
{
'name': 'Ultramarine'
'hex': '120A8F'
}
{
'name': 'Elephant'
'hex': '123447'
}
{
'name': 'Jewel'
'hex': '126B40'
}
{
'name': 'Diesel'
'hex': '130000'
}
{
'name': 'Asphalt'
'hex': '130A06'
}
{
'name': 'Blue Zodiac'
'hex': '13264D'
}
{
'name': 'Parsley'
'hex': '134F19'
}
{
'name': 'Nero'
'hex': '140600'
}
{
'name': 'Tory Blue'
'hex': '1450AA'
}
{
'name': 'Bunting'
'hex': '151F4C'
}
{
'name': 'Denim'
'hex': '1560BD'
}
{
'name': 'Genoa'
'hex': '15736B'
}
{
'name': 'Mirage'
'hex': '161928'
}
{
'name': 'Hunter Green'
'hex': '161D10'
}
{
'name': 'Big Stone'
'hex': '162A40'
}
{
'name': 'Celtic'
'hex': '163222'
}
{
'name': 'Timber Green'
'hex': '16322C'
}
{
'name': 'Gable Green'
'hex': '163531'
}
{
'name': 'Pine Tree'
'hex': '171F04'
}
{
'name': 'Chathams Blue'
'hex': '175579'
}
{
'name': 'Deep Forest Green'
'hex': '182D09'
}
{
'name': 'Blumine'
'hex': '18587A'
}
{
'name': 'Palm Leaf'
'hex': '19330E'
}
{
'name': 'Nile Blue'
'hex': '193751'
}
{
'name': 'Fun Blue'
'hex': '1959A8'
}
{
'name': 'Lucky Point'
'hex': '1A1A68'
}
{
'name': 'Mountain Meadow'
'hex': '1AB385'
}
{
'name': 'Tolopea'
'hex': '1B0245'
}
{
'name': 'Haiti'
'hex': '1B1035'
}
{
'name': 'Deep Koamaru'
'hex': '1B127B'
}
{
'name': 'Acadia'
'hex': '1B1404'
}
{
'name': 'Seaweed'
'hex': '1B2F11'
}
{
'name': 'Biscay'
'hex': '1B3162'
}
{
'name': 'Matisse'
'hex': '1B659D'
}
{
'name': 'Crowshead'
'hex': '1C1208'
}
{
'name': 'Rangoon Green'
'hex': '1C1E13'
}
{
'name': 'Persian Blue'
'hex': '1C39BB'
}
{
'name': 'Everglade'
'hex': '1C402E'
}
{
'name': 'Elm'
'hex': '1C7C7D'
}
{
'name': 'Green Pea'
'hex': '1D6142'
}
{
'name': 'Creole'
'hex': '1E0F04'
}
{
'name': 'Karaka'
'hex': '1E1609'
}
{
'name': 'El Paso'
'hex': '1E1708'
}
{
'name': 'Cello'
'hex': '1E385B'
}
{
'name': 'Te Papa Green'
'hex': '1E433C'
}
{
'name': 'Dodger Blue'
'hex': '1E90FF'
}
{
'name': 'Eastern Blue'
'hex': '1E9AB0'
}
{
'name': 'Night Rider'
'hex': '1F120F'
}
{
'name': 'Java'
'hex': '1FC2C2'
}
{
'name': 'Jacksons Purple'
'hex': '20208D'
}
{
'name': 'Cloud Burst'
'hex': '202E54'
}
{
'name': 'Blue Dianne'
'hex': '204852'
}
{
'name': 'Eternity'
'hex': '211A0E'
}
{
'name': 'Deep Blue'
'hex': '220878'
}
{
'name': 'Forest Green'
'hex': '228B22'
}
{
'name': 'Mallard'
'hex': '233418'
}
{
'name': 'Violet'
'hex': '240A40'
}
{
'name': 'Kilamanjaro'
'hex': '240C02'
}
{
'name': 'Log Cabin'
'hex': '242A1D'
}
{
'name': 'Black Olive'
'hex': '242E16'
}
{
'name': 'Green House'
'hex': '24500F'
}
{
'name': 'Graphite'
'hex': '251607'
}
{
'name': 'Cannon Black'
'hex': '251706'
}
{
'name': 'Port Gore'
'hex': '251F4F'
}
{
'name': 'Shark'
'hex': '25272C'
}
{
'name': 'Green Kelp'
'hex': '25311C'
}
{
'name': 'Curious Blue'
'hex': '2596D1'
}
{
'name': 'Paua'
'hex': '260368'
}
{
'name': 'Paris M'
'hex': '26056A'
}
{
'name': 'Wood Bark'
'hex': '261105'
}
{
'name': 'Gondola'
'hex': '261414'
}
{
'name': 'Steel Gray'
'hex': '262335'
}
{
'name': 'Ebony Clay'
'hex': '26283B'
}
{
'name': 'Bay of Many'
'hex': '273A81'
}
{
'name': 'Plantation'
'hex': '27504B'
}
{
'name': 'Eucalyptus'
'hex': '278A5B'
}
{
'name': 'Oil'
'hex': '281E15'
}
{
'name': 'Astronaut'
'hex': '283A77'
}
{
'name': 'Mariner'
'hex': '286ACD'
}
{
'name': 'Violent Violet'
'hex': '290C5E'
}
{
'name': 'Bastille'
'hex': '292130'
}
{
'name': 'Zeus'
'hex': '292319'
}
{
'name': 'Charade'
'hex': '292937'
}
{
'name': 'Jelly Bean'
'hex': '297B9A'
}
{
'name': 'Jungle Green'
'hex': '29AB87'
}
{
'name': 'Cherry Pie'
'hex': '2A0359'
}
{
'name': 'Coffee Bean'
'hex': '2A140E'
}
{
'name': 'Baltic Sea'
'hex': '2A2630'
}
{
'name': 'Turtle Green'
'hex': '2A380B'
}
{
'name': 'Cerulean Blue'
'hex': '2A52BE'
}
{
'name': 'Sepia Black'
'hex': '2B0202'
}
{
'name': 'Valhalla'
'hex': '2B194F'
}
{
'name': 'Heavy Metal'
'hex': '2B3228'
}
{
'name': 'Blue Gem'
'hex': '2C0E8C'
}
{
'name': 'Revolver'
'hex': '2C1632'
}
{
'name': 'Bleached Cedar'
'hex': '2C2133'
}
{
'name': 'Lochinvar'
'hex': '2C8C84'
}
{
'name': 'Mikado'
'hex': '2D2510'
}
{
'name': 'Outer Space'
'hex': '2D383A'
}
{
'name': 'St Tropaz'
'hex': '2D569B'
}
{
'name': 'Jacaranda'
'hex': '2E0329'
}
{
'name': 'Jacko Bean'
'hex': '2E1905'
}
{
'name': 'Rangitoto'
'hex': '2E3222'
}
{
'name': 'Rhino'
'hex': '2E3F62'
}
{
'name': 'Sea Green'
'hex': '2E8B57'
}
{
'name': 'Scooter'
'hex': '2EBFD4'
}
{
'name': 'Onion'
'hex': '2F270E'
}
{
'name': 'Governor Bay'
'hex': '2F3CB3'
}
{
'name': 'Sapphire'
'hex': '2F519E'
}
{
'name': 'Spectra'
'hex': '2F5A57'
}
{
'name': 'Casal'
'hex': '2F6168'
}
{
'name': 'Melanzane'
'hex': '300529'
}
{
'name': 'Cocoa Brown'
'hex': '301F1E'
}
{
'name': 'Woodrush'
'hex': '302A0F'
}
{
'name': 'San Juan'
'hex': '304B6A'
}
{
'name': 'Turquoise'
'hex': '30D5C8'
}
{
'name': 'Eclipse'
'hex': '311C17'
}
{
'name': 'Pickled Bluewood'
'hex': '314459'
}
{
'name': 'Azure'
'hex': '315BA1'
}
{
'name': 'Calypso'
'hex': '31728D'
}
{
'name': 'Paradiso'
'hex': '317D82'
}
{
'name': 'Persian Indigo'
'hex': '32127A'
}
{
'name': 'Blackcurrant'
'hex': '32293A'
}
{
'name': 'Mine Shaft'
'hex': '323232'
}
{
'name': 'Stromboli'
'hex': '325D52'
}
{
'name': 'Bilbao'
'hex': '327C14'
}
{
'name': 'Astral'
'hex': '327DA0'
}
{
'name': 'Christalle'
'hex': '33036B'
}
{
'name': 'Thunder'
'hex': '33292F'
}
{
'name': 'Shamrock'
'hex': '33CC99'
}
{
'name': 'Tamarind'
'hex': '341515'
}
{
'name': 'Mardi Gras'
'hex': '350036'
}
{
'name': 'Valentino'
'hex': '350E42'
}
{
'name': 'Jagger'
'hex': '350E57'
}
{
'name': 'Tuna'
'hex': '353542'
}
{
'name': 'Chambray'
'hex': '354E8C'
}
{
'name': 'Martinique'
'hex': '363050'
}
{
'name': 'Tuatara'
'hex': '363534'
}
{
'name': 'Waiouru'
'hex': '363C0D'
}
{
'name': 'Ming'
'hex': '36747D'
}
{
'name': 'La Palma'
'hex': '368716'
}
{
'name': 'Chocolate'
'hex': '370202'
}
{
'name': 'Clinker'
'hex': '371D09'
}
{
'name': 'Brown Tumbleweed'
'hex': '37290E'
}
{
'name': 'Birch'
'hex': '373021'
}
{
'name': 'Oracle'
'hex': '377475'
}
{
'name': 'Blue Diamond'
'hex': '380474'
}
{
'name': 'Grape'
'hex': '381A51'
}
{
'name': 'Dune'
'hex': '383533'
}
{
'name': 'Oxford Blue'
'hex': '384555'
}
{
'name': 'Clover'
'hex': '384910'
}
{
'name': 'Limed Spruce'
'hex': '394851'
}
{
'name': 'Dell'
'hex': '396413'
}
{
'name': 'Toledo'
'hex': '3A0020'
}
{
'name': 'Sambuca'
'hex': '3A2010'
}
{
'name': 'Jacarta'
'hex': '3A2A6A'
}
{
'name': 'William'
'hex': '3A686C'
}
{
'name': 'Killarney'
'hex': '3A6A47'
}
{
'name': 'Keppel'
'hex': '3AB09E'
}
{
'name': 'Temptress'
'hex': '3B000B'
}
{
'name': 'Aubergine'
'hex': '3B0910'
}
{
'name': 'Jon'
'hex': '3B1F1F'
}
{
'name': 'Treehouse'
'hex': '3B2820'
}
{
'name': 'Amazon'
'hex': '3B7A57'
}
{
'name': 'Boston Blue'
'hex': '3B91B4'
}
{
'name': 'Windsor'
'hex': '3C0878'
}
{
'name': 'Rebel'
'hex': '3C1206'
}
{
'name': 'Meteorite'
'hex': '3C1F76'
}
{
'name': 'Dark Ebony'
'hex': '3C2005'
}
{
'name': 'Camouflage'
'hex': '3C3910'
}
{
'name': 'Bright Gray'
'hex': '3C4151'
}
{
'name': 'Cape Cod'
'hex': '3C4443'
}
{
'name': 'Lunar Green'
'hex': '3C493A'
}
{
'name': 'Bean '
'hex': '3D0C02'
}
{
'name': 'Bistre'
'hex': '3D2B1F'
}
{
'name': 'Goblin'
'hex': '3D7D52'
}
{
'name': 'Kingfisher Daisy'
'hex': '3E0480'
}
{
'name': 'Cedar'
'hex': '3E1C14'
}
{
'name': 'English Walnut'
'hex': '3E2B23'
}
{
'name': 'Black Marlin'
'hex': '3E2C1C'
}
{
'name': 'Ship Gray'
'hex': '3E3A44'
}
{
'name': 'Pelorous'
'hex': '3EABBF'
}
{
'name': 'Bronze'
'hex': '3F2109'
}
{
'name': 'Cola'
'hex': '3F2500'
}
{
'name': 'Madras'
'hex': '3F3002'
}
{
'name': 'Minsk'
'hex': '3F307F'
}
{
'name': 'Cabbage Pont'
'hex': '3F4C3A'
}
{
'name': 'Tom Thumb'
'hex': '3F583B'
}
{
'name': 'Mineral Green'
'hex': '3F5D53'
}
{
'name': 'Puerto Rico'
'hex': '3FC1AA'
}
{
'name': 'Harlequin'
'hex': '3FFF00'
}
{
'name': 'Brown Pod'
'hex': '401801'
}
{
'name': 'Cork'
'hex': '40291D'
}
{
'name': 'Masala'
'hex': '403B38'
}
{
'name': 'Thatch Green'
'hex': '403D19'
}
{
'name': 'Fiord'
'hex': '405169'
}
{
'name': 'Viridian'
'hex': '40826D'
}
{
'name': 'Chateau Green'
'hex': '40A860'
}
{
'name': 'Ripe Plum'
'hex': '410056'
}
{
'name': 'Paco'
'hex': '411F10'
}
{
'name': 'Deep Oak'
'hex': '412010'
}
{
'name': 'Merlin'
'hex': '413C37'
}
{
'name': 'Gun Powder'
'hex': '414257'
}
{
'name': 'East Bay'
'hex': '414C7D'
}
{
'name': 'Royal Blue'
'hex': '4169E1'
}
{
'name': 'Ocean Green'
'hex': '41AA78'
}
{
'name': 'Burnt Maroon'
'hex': '420303'
}
{
'name': 'Lisbon Brown'
'hex': '423921'
}
{
'name': 'Faded Jade'
'hex': '427977'
}
{
'name': 'Scarlet Gum'
'hex': '431560'
}
{
'name': 'Iroko'
'hex': '433120'
}
{
'name': 'Armadillo'
'hex': '433E37'
}
{
'name': 'River Bed'
'hex': '434C59'
}
{
'name': 'Green Leaf'
'hex': '436A0D'
}
{
'name': 'Barossa'
'hex': '44012D'
}
{
'name': 'Morocco Brown'
'hex': '441D00'
}
{
'name': 'Mako'
'hex': '444954'
}
{
'name': 'Kelp'
'hex': '454936'
}
{
'name': 'San Marino'
'hex': '456CAC'
}
{
'name': 'Picton Blue'
'hex': '45B1E8'
}
{
'name': 'Loulou'
'hex': '460B41'
}
{
'name': 'Crater Brown'
'hex': '462425'
}
{
'name': 'Gray Asparagus'
'hex': '465945'
}
{
'name': 'Steel Blue'
'hex': '4682B4'
}
{
'name': 'Rustic Red'
'hex': '480404'
}
{
'name': 'Bulgarian Rose'
'hex': '480607'
}
{
'name': 'Clairvoyant'
'hex': '480656'
}
{
'name': 'Cocoa Bean'
'hex': '481C1C'
}
{
'name': 'Woody Brown'
'hex': '483131'
}
{
'name': 'Taupe'
'hex': '483C32'
}
{
'name': 'Van Cleef'
'hex': '49170C'
}
{
'name': 'Brown Derby'
'hex': '492615'
}
{
'name': 'Metallic Bronze'
'hex': '49371B'
}
{
'name': 'Verdun Green'
'hex': '495400'
}
{
'name': 'Blue Bayoux'
'hex': '496679'
}
{
'name': 'Bismark'
'hex': '497183'
}
{
'name': 'Bracken'
'hex': '4A2A04'
}
{
'name': 'Deep Bronze'
'hex': '4A3004'
}
{
'name': 'Mondo'
'hex': '4A3C30'
}
{
'name': 'Tundora'
'hex': '4A4244'
}
{
'name': 'Gravel'
'hex': '4A444B'
}
{
'name': 'Trout'
'hex': '4A4E5A'
}
{
'name': 'Pigment Indigo'
'hex': '4B0082'
}
{
'name': 'Nandor'
'hex': '4B5D52'
}
{
'name': 'Saddle'
'hex': '4C3024'
}
{
'name': 'Abbey'
'hex': '4C4F56'
}
{
'name': 'Blackberry'
'hex': '4D0135'
}
{
'name': 'Cab Sav'
'hex': '4D0A18'
}
{
'name': 'Indian Tan'
'hex': '4D1E01'
}
{
'name': 'Cowboy'
'hex': '4D282D'
}
{
'name': 'Livid Brown'
'hex': '4D282E'
}
{
'name': 'Rock'
'hex': '4D3833'
}
{
'name': 'Punga'
'hex': '4D3D14'
}
{
'name': 'Bronzetone'
'hex': '4D400F'
}
{
'name': 'Woodland'
'hex': '4D5328'
}
{
'name': 'Mahogany'
'hex': '4E0606'
}
{
'name': 'Bossanova'
'hex': '4E2A5A'
}
{
'name': 'Matterhorn'
'hex': '4E3B41'
}
{
'name': 'Bronze Olive'
'hex': '4E420C'
}
{
'name': 'Mulled Wine'
'hex': '4E4562'
}
{
'name': 'Axolotl'
'hex': '4E6649'
}
{
'name': 'Wedgewood'
'hex': '4E7F9E'
}
{
'name': 'Shakespeare'
'hex': '4EABD1'
}
{
'name': 'Honey Flower'
'hex': '4F1C70'
}
{
'name': 'Daisy Bush'
'hex': '4F2398'
}
{
'name': 'Indigo'
'hex': '4F69C6'
}
{
'name': 'Fern Green'
'hex': '4F7942'
}
{
'name': 'Fruit Salad'
'hex': '4F9D5D'
}
{
'name': 'Apple'
'hex': '4FA83D'
}
{
'name': 'Mortar'
'hex': '504351'
}
{
'name': 'Kashmir Blue'
'hex': '507096'
}
{
'name': 'Cutty Sark'
'hex': '507672'
}
{
'name': 'Emerald'
'hex': '50C878'
}
{
'name': 'Emperor'
'hex': '514649'
}
{
'name': 'Chalet Green'
'hex': '516E3D'
}
{
'name': 'Como'
'hex': '517C66'
}
{
'name': 'Smalt Blue'
'hex': '51808F'
}
{
'name': 'Castro'
'hex': '52001F'
}
{
'name': 'Maroon Oak'
'hex': '520C17'
}
{
'name': 'Gigas'
'hex': '523C94'
}
{
'name': 'Voodoo'
'hex': '533455'
}
{
'name': 'Victoria'
'hex': '534491'
}
{
'name': 'Hippie Green'
'hex': '53824B'
}
{
'name': 'Heath'
'hex': '541012'
}
{
'name': 'Judge Gray'
'hex': '544333'
}
{
'name': 'Fuscous Gray'
'hex': '54534D'
}
{
'name': 'Vida Loca'
'hex': '549019'
}
{
'name': 'Cioccolato'
'hex': '55280C'
}
{
'name': 'Saratoga'
'hex': '555B10'
}
{
'name': 'Finlandia'
'hex': '556D56'
}
{
'name': 'Havelock Blue'
'hex': '5590D9'
}
{
'name': 'Fountain Blue'
'hex': '56B4BE'
}
{
'name': 'Spring Leaves'
'hex': '578363'
}
{
'name': 'Saddle Brown'
'hex': '583401'
}
{
'name': 'Scarpa Flow'
'hex': '585562'
}
{
'name': 'Cactus'
'hex': '587156'
}
{
'name': 'Hippie Blue'
'hex': '589AAF'
}
{
'name': 'Wine Berry'
'hex': '591D35'
}
{
'name': 'Brown Bramble'
'hex': '592804'
}
{
'name': 'Congo Brown'
'hex': '593737'
}
{
'name': 'Millbrook'
'hex': '594433'
}
{
'name': 'Waikawa Gray'
'hex': '5A6E9C'
}
{
'name': 'Horizon'
'hex': '5A87A0'
}
{
'name': 'Jambalaya'
'hex': '5B3013'
}
{
'name': 'Bordeaux'
'hex': '5C0120'
}
{
'name': 'Mulberry Wood'
'hex': '5C0536'
}
{
'name': 'Carnaby Tan'
'hex': '5C2E01'
}
{
'name': 'Comet'
'hex': '5C5D75'
}
{
'name': 'Redwood'
'hex': '5D1E0F'
}
{
'name': 'Don Juan'
'hex': '5D4C51'
}
{
'name': 'Chicago'
'hex': '5D5C58'
}
{
'name': 'Verdigris'
'hex': '5D5E37'
}
{
'name': 'Dingley'
'hex': '5D7747'
}
{
'name': 'Breaker Bay'
'hex': '5DA19F'
}
{
'name': 'Kabul'
'hex': '5E483E'
}
{
'name': 'Hemlock'
'hex': '5E5D3B'
}
{
'name': 'Irish Coffee'
'hex': '5F3D26'
}
{
'name': 'Mid Gray'
'hex': '5F5F6E'
}
{
'name': 'Shuttle Gray'
'hex': '5F6672'
}
{
'name': 'Aqua Forest'
'hex': '5FA777'
}
{
'name': 'Tradewind'
'hex': '5FB3AC'
}
{
'name': 'Horses Neck'
'hex': '604913'
}
{
'name': 'Smoky'
'hex': '605B73'
}
{
'name': 'Corduroy'
'hex': '606E68'
}
{
'name': 'Danube'
'hex': '6093D1'
}
{
'name': 'Espresso'
'hex': '612718'
}
{
'name': 'Eggplant'
'hex': '614051'
}
{
'name': 'Costa Del Sol'
'hex': '615D30'
}
{
'name': 'Glade Green'
'hex': '61845F'
}
{
'name': 'Buccaneer'
'hex': '622F30'
}
{
'name': 'Quincy'
'hex': '623F2D'
}
{
'name': 'Butterfly Bush'
'hex': '624E9A'
}
{
'name': 'West Coast'
'hex': '625119'
}
{
'name': 'Finch'
'hex': '626649'
}
{
'name': 'Patina'
'hex': '639A8F'
}
{
'name': 'Fern'
'hex': '63B76C'
}
{
'name': 'Blue Violet'
'hex': '6456B7'
}
{
'name': 'Dolphin'
'hex': '646077'
}
{
'name': 'Storm Dust'
'hex': '646463'
}
{
'name': 'Siam'
'hex': '646A54'
}
{
'name': 'Nevada'
'hex': '646E75'
}
{
'name': 'Cornflower Blue'
'hex': '6495ED'
}
{
'name': 'Viking'
'hex': '64CCDB'
}
{
'name': 'Rosewood'
'hex': '65000B'
}
{
'name': 'Cherrywood'
'hex': '651A14'
}
{
'name': 'Purple Heart'
'hex': '652DC1'
}
{
'name': 'Fern Frond'
'hex': '657220'
}
{
'name': 'Willow Grove'
'hex': '65745D'
}
{
'name': 'Hoki'
'hex': '65869F'
}
{
'name': 'Pompadour'
'hex': '660045'
}
{
'name': 'Purple'
'hex': '660099'
}
{
'name': 'Tyrian Purple'
'hex': '66023C'
}
{
'name': 'Dark Tan'
'hex': '661010'
}
{
'name': 'Silver Tree'
'hex': '66B58F'
}
{
'name': 'Bright Green'
'hex': '66FF00'
}
{
'name': 'Screamin\' Green'
'hex': '66FF66'
}
{
'name': 'Black Rose'
'hex': '67032D'
}
{
'name': 'Scampi'
'hex': '675FA6'
}
{
'name': 'Ironside Gray'
'hex': '676662'
}
{
'name': 'Viridian Green'
'hex': '678975'
}
{
'name': 'Christi'
'hex': '67A712'
}
{
'name': 'Nutmeg Wood Finish'
'hex': '683600'
}
{
'name': 'Zambezi'
'hex': '685558'
}
{
'name': 'Salt Box'
'hex': '685E6E'
}
{
'name': 'Tawny Port'
'hex': '692545'
}
{
'name': 'Finn'
'hex': '692D54'
}
{
'name': 'Scorpion'
'hex': '695F62'
}
{
'name': 'Lynch'
'hex': '697E9A'
}
{
'name': 'Spice'
'hex': '6A442E'
}
{
'name': 'Himalaya'
'hex': '6A5D1B'
}
{
'name': 'Soya Bean'
'hex': '6A6051'
}
{
'name': 'Hairy Heath'
'hex': '6B2A14'
}
{
'name': 'Royal Purple'
'hex': '6B3FA0'
}
{
'name': 'Shingle Fawn'
'hex': '6B4E31'
}
{
'name': 'Dorado'
'hex': '6B5755'
}
{
'name': 'Bermuda Gray'
'hex': '6B8BA2'
}
{
'name': 'Olive Drab'
'hex': '6B8E23'
}
{
'name': 'Eminence'
'hex': '6C3082'
}
{
'name': 'Turquoise Blue'
'hex': '6CDAE7'
}
{
'name': 'Lonestar'
'hex': '6D0101'
}
{
'name': 'Pine Cone'
'hex': '6D5E54'
}
{
'name': 'Dove Gray'
'hex': '6D6C6C'
}
{
'name': 'Juniper'
'hex': '6D9292'
}
{
'name': 'Gothic'
'hex': '6D92A1'
}
{
'name': 'Red Oxide'
'hex': '6E0902'
}
{
'name': 'Moccaccino'
'hex': '6E1D14'
}
{
'name': 'Pickled Bean'
'hex': '6E4826'
}
{
'name': 'Dallas'
'hex': '6E4B26'
}
{
'name': 'Kokoda'
'hex': '6E6D57'
}
{
'name': 'Pale Sky'
'hex': '6E7783'
}
{
'name': 'Cafe Royale'
'hex': '6F440C'
}
{
'name': 'Flint'
'hex': '6F6A61'
}
{
'name': 'Highland'
'hex': '6F8E63'
}
{
'name': 'Limeade'
'hex': '6F9D02'
}
{
'name': 'Downy'
'hex': '6FD0C5'
}
{
'name': 'Persian Plum'
'hex': '701C1C'
}
{
'name': 'Sepia'
'hex': '704214'
}
{
'name': 'Antique Bronze'
'hex': '704A07'
}
{
'name': 'Ferra'
'hex': '704F50'
}
{
'name': 'Coffee'
'hex': '706555'
}
{
'name': 'Slate Gray'
'hex': '708090'
}
{
'name': 'Cedar Wood Finish'
'hex': '711A00'
}
{
'name': 'Metallic Copper'
'hex': '71291D'
}
{
'name': 'Affair'
'hex': '714693'
}
{
'name': 'Studio'
'hex': '714AB2'
}
{
'name': 'Tobacco Brown'
'hex': '715D47'
}
{
'name': 'Yellow Metal'
'hex': '716338'
}
{
'name': 'Peat'
'hex': '716B56'
}
{
'name': 'Olivetone'
'hex': '716E10'
}
{
'name': 'Storm Gray'
'hex': '717486'
}
{
'name': 'Sirocco'
'hex': '718080'
}
{
'name': 'Aquamarine Blue'
'hex': '71D9E2'
}
{
'name': 'Venetian Red'
'hex': '72010F'
}
{
'name': 'Old Copper'
'hex': '724A2F'
}
{
'name': 'Go Ben'
'hex': '726D4E'
}
{
'name': 'Raven'
'hex': '727B89'
}
{
'name': 'Seance'
'hex': '731E8F'
}
{
'name': 'Raw Umber'
'hex': '734A12'
}
{
'name': 'Kimberly'
'hex': '736C9F'
}
{
'name': 'Crocodile'
'hex': '736D58'
}
{
'name': 'Crete'
'hex': '737829'
}
{
'name': 'Xanadu'
'hex': '738678'
}
{
'name': 'Spicy Mustard'
'hex': '74640D'
}
{
'name': 'Limed Ash'
'hex': '747D63'
}
{
'name': 'Rolling Stone'
'hex': '747D83'
}
{
'name': 'Blue Smoke'
'hex': '748881'
}
{
'name': 'Laurel'
'hex': '749378'
}
{
'name': 'Mantis'
'hex': '74C365'
}
{
'name': 'Russett'
'hex': '755A57'
}
{
'name': 'Deluge'
'hex': '7563A8'
}
{
'name': 'Cosmic'
'hex': '76395D'
}
{
'name': 'Blue Marguerite'
'hex': '7666C6'
}
{
'name': 'Lima'
'hex': '76BD17'
}
{
'name': 'Sky Blue'
'hex': '76D7EA'
}
{
'name': 'Dark Burgundy'
'hex': '770F05'
}
{
'name': 'Crown of Thorns'
'hex': '771F1F'
}
{
'name': 'Walnut'
'hex': '773F1A'
}
{
'name': 'Pablo'
'hex': '776F61'
}
{
'name': 'Pacifika'
'hex': '778120'
}
{
'name': 'Oxley'
'hex': '779E86'
}
{
'name': 'Pastel Green'
'hex': '77DD77'
}
{
'name': 'Japanese Maple'
'hex': '780109'
}
{
'name': 'Mocha'
'hex': '782D19'
}
{
'name': 'Peanut'
'hex': '782F16'
}
{
'name': 'Camouflage Green'
'hex': '78866B'
}
{
'name': 'Wasabi'
'hex': '788A25'
}
{
'name': 'Ship Cove'
'hex': '788BBA'
}
{
'name': 'Sea Nymph'
'hex': '78A39C'
}
{
'name': 'Roman Coffee'
'hex': '795D4C'
}
{
'name': 'Old Lavender'
'hex': '796878'
}
{
'name': 'Rum'
'hex': '796989'
}
{
'name': 'Fedora'
'hex': '796A78'
}
{
'name': 'Sandstone'
'hex': '796D62'
}
{
'name': 'Spray'
'hex': '79DEEC'
}
{
'name': 'Siren'
'hex': '7A013A'
}
{
'name': 'Fuchsia Blue'
'hex': '7A58C1'
}
{
'name': 'Boulder'
'hex': '7A7A7A'
}
{
'name': 'Wild Blue Yonder'
'hex': '7A89B8'
}
{
'name': 'De York'
'hex': '7AC488'
}
{
'name': 'Red Beech'
'hex': '7B3801'
}
{
'name': 'Cinnamon'
'hex': '7B3F00'
}
{
'name': 'Yukon Gold'
'hex': '7B6608'
}
{
'name': 'Tapa'
'hex': '7B7874'
}
{
'name': 'Waterloo '
'hex': '7B7C94'
}
{
'name': 'Flax Smoke'
'hex': '7B8265'
}
{
'name': 'Amulet'
'hex': '7B9F80'
}
{
'name': 'Asparagus'
'hex': '7BA05B'
}
{
'name': 'Kenyan Copper'
'hex': '7C1C05'
}
{
'name': 'Pesto'
'hex': '7C7631'
}
{
'name': 'Topaz'
'hex': '7C778A'
}
{
'name': 'Concord'
'hex': '7C7B7A'
}
{
'name': 'Jumbo'
'hex': '7C7B82'
}
{
'name': 'Trendy Green'
'hex': '7C881A'
}
{
'name': 'Gumbo'
'hex': '7CA1A6'
}
{
'name': 'Acapulco'
'hex': '7CB0A1'
}
{
'name': 'Neptune'
'hex': '7CB7BB'
}
{
'name': 'Pueblo'
'hex': '7D2C14'
}
{
'name': 'Bay Leaf'
'hex': '7DA98D'
}
{
'name': 'Malibu'
'hex': '7DC8F7'
}
{
'name': 'Bermuda'
'hex': '7DD8C6'
}
{
'name': 'Copper Canyon'
'hex': '7E3A15'
}
{
'name': 'Claret'
'hex': '7F1734'
}
{
'name': 'Peru Tan'
'hex': '7F3A02'
}
{
'name': 'Falcon'
'hex': '7F626D'
}
{
'name': 'Mobster'
'hex': '7F7589'
}
{
'name': 'Moody Blue'
'hex': '7F76D3'
}
{
'name': 'Chartreuse'
'hex': '7FFF00'
}
{
'name': 'Aquamarine'
'hex': '7FFFD4'
}
{
'name': 'Maroon'
'hex': '800000'
}
{
'name': 'Rose Bud Cherry'
'hex': '800B47'
}
{
'name': 'Falu Red'
'hex': '801818'
}
{
'name': 'Red Robin'
'hex': '80341F'
}
{
'name': 'Vivid Violet'
'hex': '803790'
}
{
'name': 'Russet'
'hex': '80461B'
}
{
'name': 'Friar Gray'
'hex': '807E79'
}
{
'name': 'Olive'
'hex': '808000'
}
{
'name': 'Gray'
'hex': '808080'
}
{
'name': 'Gulf Stream'
'hex': '80B3AE'
}
{
'name': 'Glacier'
'hex': '80B3C4'
}
{
'name': 'Seagull'
'hex': '80CCEA'
}
{
'name': 'Nutmeg'
'hex': '81422C'
}
{
'name': 'Spicy Pink'
'hex': '816E71'
}
{
'name': 'Empress'
'hex': '817377'
}
{
'name': 'Spanish Green'
'hex': '819885'
}
{
'name': 'Sand Dune'
'hex': '826F65'
}
{
'name': 'Gunsmoke'
'hex': '828685'
}
{
'name': 'Battleship Gray'
'hex': '828F72'
}
{
'name': 'Merlot'
'hex': '831923'
}
{
'name': 'Shadow'
'hex': '837050'
}
{
'name': 'Chelsea Cucumber'
'hex': '83AA5D'
}
{
'name': 'Monte Carlo'
'hex': '83D0C6'
}
{
'name': 'Plum'
'hex': '843179'
}
{
'name': 'Granny Smith'
'hex': '84A0A0'
}
{
'name': 'Chetwode Blue'
'hex': '8581D9'
}
{
'name': 'Bandicoot'
'hex': '858470'
}
{
'name': 'Bali Hai'
'hex': '859FAF'
}
{
'name': 'Half Baked'
'hex': '85C4CC'
}
{
'name': 'Red Devil'
'hex': '860111'
}
{
'name': 'Lotus'
'hex': '863C3C'
}
{
'name': 'Ironstone'
'hex': '86483C'
}
{
'name': 'Bull Shot'
'hex': '864D1E'
}
{
'name': 'Rusty Nail'
'hex': '86560A'
}
{
'name': 'Bitter'
'hex': '868974'
}
{
'name': 'Regent Gray'
'hex': '86949F'
}
{
'name': 'Disco'
'hex': '871550'
}
{
'name': 'Americano'
'hex': '87756E'
}
{
'name': 'Hurricane'
'hex': '877C7B'
}
{
'name': 'Oslo Gray'
'hex': '878D91'
}
{
'name': 'Sushi'
'hex': '87AB39'
}
{
'name': 'Spicy Mix'
'hex': '885342'
}
{
'name': 'Kumera'
'hex': '886221'
}
{
'name': 'Suva Gray'
'hex': '888387'
}
{
'name': 'Avocado'
'hex': '888D65'
}
{
'name': 'Camelot'
'hex': '893456'
}
{
'name': 'Solid Pink'
'hex': '893843'
}
{
'name': 'Cannon Pink'
'hex': '894367'
}
{
'name': 'Makara'
'hex': '897D6D'
}
{
'name': 'Burnt Umber'
'hex': '8A3324'
}
{
'name': 'True V'
'hex': '8A73D6'
}
{
'name': 'Clay Creek'
'hex': '8A8360'
}
{
'name': 'Monsoon'
'hex': '8A8389'
}
{
'name': 'Stack'
'hex': '8A8F8A'
}
{
'name': 'Jordy Blue'
'hex': '8AB9F1'
}
{
'name': 'Electric Violet'
'hex': '8B00FF'
}
{
'name': 'Monarch'
'hex': '8B0723'
}
{
'name': 'Corn Harvest'
'hex': '8B6B0B'
}
{
'name': 'Olive Haze'
'hex': '8B8470'
}
{
'name': 'Schooner'
'hex': '8B847E'
}
{
'name': 'Natural Gray'
'hex': '8B8680'
}
{
'name': 'Mantle'
'hex': '8B9C90'
}
{
'name': 'Portage'
'hex': '8B9FEE'
}
{
'name': 'Envy'
'hex': '8BA690'
}
{
'name': 'Cascade'
'hex': '8BA9A5'
}
{
'name': 'Riptide'
'hex': '8BE6D8'
}
{
'name': 'Cardinal Pink'
'hex': '8C055E'
}
{
'name': 'Mule Fawn'
'hex': '8C472F'
}
{
'name': 'Potters Clay'
'hex': '8C5738'
}
{
'name': 'Trendy Pink'
'hex': '8C6495'
}
{
'name': 'Paprika'
'hex': '8D0226'
}
{
'name': 'Sanguine Brown'
'hex': '8D3D38'
}
{
'name': 'Tosca'
'hex': '8D3F3F'
}
{
'name': 'Cement'
'hex': '8D7662'
}
{
'name': 'Granite Green'
'hex': '8D8974'
}
{
'name': 'Manatee'
'hex': '8D90A1'
}
{
'name': 'Polo Blue'
'hex': '8DA8CC'
}
{
'name': 'Red Berry'
'hex': '8E0000'
}
{
'name': 'Rope'
'hex': '8E4D1E'
}
{
'name': 'Opium'
'hex': '8E6F70'
}
{
'name': 'Domino'
'hex': '8E775E'
}
{
'name': 'Mamba'
'hex': '8E8190'
}
{
'name': 'Nepal'
'hex': '8EABC1'
}
{
'name': 'Pohutukawa'
'hex': '8F021C'
}
{
'name': 'El Salva'
'hex': '8F3E33'
}
{
'name': 'Korma'
'hex': '8F4B0E'
}
{
'name': 'Squirrel'
'hex': '8F8176'
}
{
'name': 'Vista Blue'
'hex': '8FD6B4'
}
{
'name': 'Burgundy'
'hex': '900020'
}
{
'name': 'Old Brick'
'hex': '901E1E'
}
{
'name': 'Hemp'
'hex': '907874'
}
{
'name': 'Almond Frost'
'hex': '907B71'
}
{
'name': 'Sycamore'
'hex': '908D39'
}
{
'name': 'Sangria'
'hex': '92000A'
}
{
'name': 'Cumin'
'hex': '924321'
}
{
'name': 'Beaver'
'hex': '926F5B'
}
{
'name': 'Stonewall'
'hex': '928573'
}
{
'name': 'Venus'
'hex': '928590'
}
{
'name': 'Medium Purple'
'hex': '9370DB'
}
{
'name': 'Cornflower'
'hex': '93CCEA'
}
{
'name': 'Algae Green'
'hex': '93DFB8'
}
{
'name': 'Copper Rust'
'hex': '944747'
}
{
'name': 'Arrowtown'
'hex': '948771'
}
{
'name': 'Scarlett'
'hex': '950015'
}
{
'name': 'Strikemaster'
'hex': '956387'
}
{
'name': 'Mountain Mist'
'hex': '959396'
}
{
'name': 'Carmine'
'hex': '960018'
}
{
'name': 'Brown'
'hex': '964B00'
}
{
'name': 'Leather'
'hex': '967059'
}
{
'name': 'Purple Mountain\'s Majesty'
'hex': '9678B6'
}
{
'name': 'Lavender Purple'
'hex': '967BB6'
}
{
'name': 'Pewter'
'hex': '96A8A1'
}
{
'name': 'Summer Green'
'hex': '96BBAB'
}
{
'name': 'Au Chico'
'hex': '97605D'
}
{
'name': 'Wisteria'
'hex': '9771B5'
}
{
'name': 'Atlantis'
'hex': '97CD2D'
}
{
'name': 'Vin Rouge'
'hex': '983D61'
}
{
'name': 'Lilac Bush'
'hex': '9874D3'
}
{
'name': 'Bazaar'
'hex': '98777B'
}
{
'name': 'Hacienda'
'hex': '98811B'
}
{
'name': 'Pale Oyster'
'hex': '988D77'
}
{
'name': 'Mint Green'
'hex': '98FF98'
}
{
'name': 'Fresh Eggplant'
'hex': '990066'
}
{
'name': 'Violet Eggplant'
'hex': '991199'
}
{
'name': 'Tamarillo'
'hex': '991613'
}
{
'name': 'Totem Pole'
'hex': '991B07'
}
{
'name': 'Copper Rose'
'hex': '996666'
}
{
'name': 'Amethyst'
'hex': '9966CC'
}
{
'name': 'Mountbatten Pink'
'hex': '997A8D'
}
{
'name': 'Blue Bell'
'hex': '9999CC'
}
{
'name': 'Prairie Sand'
'hex': '9A3820'
}
{
'name': 'Toast'
'hex': '9A6E61'
}
{
'name': 'Gurkha'
'hex': '9A9577'
}
{
'name': 'Olivine'
'hex': '9AB973'
}
{
'name': 'Shadow Green'
'hex': '9AC2B8'
}
{
'name': 'Oregon'
'hex': '9B4703'
}
{
'name': 'Lemon Grass'
'hex': '9B9E8F'
}
{
'name': 'Stiletto'
'hex': '9C3336'
}
{
'name': 'Hawaiian Tan'
'hex': '9D5616'
}
{
'name': 'Gull Gray'
'hex': '9DACB7'
}
{
'name': 'Pistachio'
'hex': '9DC209'
}
{
'name': 'Granny Smith Apple'
'hex': '9DE093'
}
{
'name': 'Anakiwa'
'hex': '9DE5FF'
}
{
'name': 'Chelsea Gem'
'hex': '9E5302'
}
{
'name': 'Sepia Skin'
'hex': '9E5B40'
}
{
'name': 'Sage'
'hex': '9EA587'
}
{
'name': 'Citron'
'hex': '9EA91F'
}
{
'name': 'Rock Blue'
'hex': '9EB1CD'
}
{
'name': 'Morning Glory'
'hex': '9EDEE0'
}
{
'name': 'Cognac'
'hex': '9F381D'
}
{
'name': 'Reef Gold'
'hex': '9F821C'
}
{
'name': 'Star Dust'
'hex': '9F9F9C'
}
{
'name': 'Santas Gray'
'hex': '9FA0B1'
}
{
'name': 'Sinbad'
'hex': '9FD7D3'
}
{
'name': 'Feijoa'
'hex': '9FDD8C'
}
{
'name': 'Tabasco'
'hex': 'A02712'
}
{
'name': 'Buttered Rum'
'hex': 'A1750D'
}
{
'name': 'Hit Gray'
'hex': 'A1ADB5'
}
{
'name': 'Citrus'
'hex': 'A1C50A'
}
{
'name': 'Aqua Island'
'hex': 'A1DAD7'
}
{
'name': 'Water Leaf'
'hex': 'A1E9DE'
}
{
'name': 'Flirt'
'hex': 'A2006D'
}
{
'name': 'Rouge'
'hex': 'A23B6C'
}
{
'name': 'Cape Palliser'
'hex': 'A26645'
}
{
'name': 'Gray Chateau'
'hex': 'A2AAB3'
}
{
'name': 'Edward'
'hex': 'A2AEAB'
}
{
'name': 'Pharlap'
'hex': 'A3807B'
}
{
'name': 'Amethyst Smoke'
'hex': 'A397B4'
}
{
'name': 'Blizzard Blue'
'hex': 'A3E3ED'
}
{
'name': 'Delta'
'hex': 'A4A49D'
}
{
'name': 'Wistful'
'hex': 'A4A6D3'
}
{
'name': 'Green Smoke'
'hex': 'A4AF6E'
}
{
'name': 'Jazzberry Jam'
'hex': 'A50B5E'
}
{
'name': 'Zorba'
'hex': 'A59B91'
}
{
'name': 'Bahia'
'hex': 'A5CB0C'
}
{
'name': 'Roof Terracotta'
'hex': 'A62F20'
}
{
'name': 'Paarl'
'hex': 'A65529'
}
{
'name': 'Barley Corn'
'hex': 'A68B5B'
}
{
'name': 'Donkey Brown'
'hex': 'A69279'
}
{
'name': 'Dawn'
'hex': 'A6A29A'
}
{
'name': 'Mexican Red'
'hex': 'A72525'
}
{
'name': 'Luxor Gold'
'hex': 'A7882C'
}
{
'name': 'Rich Gold'
'hex': 'A85307'
}
{
'name': 'Reno Sand'
'hex': 'A86515'
}
{
'name': 'Coral Tree'
'hex': 'A86B6B'
}
{
'name': 'Dusty Gray'
'hex': 'A8989B'
}
{
'name': 'Dull Lavender'
'hex': 'A899E6'
}
{
'name': 'Tallow'
'hex': 'A8A589'
}
{
'name': 'Bud'
'hex': 'A8AE9C'
}
{
'name': 'Locust'
'hex': 'A8AF8E'
}
{
'name': 'Norway'
'hex': 'A8BD9F'
}
{
'name': 'Chinook'
'hex': 'A8E3BD'
}
{
'name': 'Gray Olive'
'hex': 'A9A491'
}
{
'name': 'Aluminium'
'hex': 'A9ACB6'
}
{
'name': 'Cadet Blue'
'hex': 'A9B2C3'
}
{
'name': 'Schist'
'hex': 'A9B497'
}
{
'name': 'Tower Gray'
'hex': 'A9BDBF'
}
{
'name': 'Perano'
'hex': 'A9BEF2'
}
{
'name': 'Opal'
'hex': 'A9C6C2'
}
{
'name': 'Night Shadz'
'hex': 'AA375A'
}
{
'name': 'Fire'
'hex': 'AA4203'
}
{
'name': 'Muesli'
'hex': 'AA8B5B'
}
{
'name': 'Sandal'
'hex': 'AA8D6F'
}
{
'name': 'Shady Lady'
'hex': 'AAA5A9'
}
{
'name': 'Logan'
'hex': 'AAA9CD'
}
{
'name': 'Spun Pearl'
'hex': 'AAABB7'
}
{
'name': 'Regent St Blue'
'hex': 'AAD6E6'
}
{
'name': 'Magic Mint'
'hex': 'AAF0D1'
}
{
'name': 'Lipstick'
'hex': 'AB0563'
}
{
'name': 'Royal Heath'
'hex': 'AB3472'
}
{
'name': 'Sandrift'
'hex': 'AB917A'
}
{
'name': 'Cold Purple'
'hex': 'ABA0D9'
}
{
'name': 'Bronco'
'hex': 'ABA196'
}
{
'name': 'Limed Oak'
'hex': 'AC8A56'
}
{
'name': 'East Side'
'hex': 'AC91CE'
}
{
'name': 'Lemon Ginger'
'hex': 'AC9E22'
}
{
'name': 'Napa'
'hex': 'ACA494'
}
{
'name': 'Hillary'
'hex': 'ACA586'
}
{
'name': 'Cloudy'
'hex': 'ACA59F'
}
{
'name': 'Silver Chalice'
'hex': 'ACACAC'
}
{
'name': 'Swamp Green'
'hex': 'ACB78E'
}
{
'name': 'Spring Rain'
'hex': 'ACCBB1'
}
{
'name': 'Conifer'
'hex': 'ACDD4D'
}
{
'name': 'Celadon'
'hex': 'ACE1AF'
}
{
'name': 'Mandalay'
'hex': 'AD781B'
}
{
'name': 'Casper'
'hex': 'ADBED1'
}
{
'name': 'Moss Green'
'hex': 'ADDFAD'
}
{
'name': 'Padua'
'hex': 'ADE6C4'
}
{
'name': 'Green Yellow'
'hex': 'ADFF2F'
}
{
'name': 'Hippie Pink'
'hex': 'AE4560'
}
{
'name': 'Desert'
'hex': 'AE6020'
}
{
'name': 'Bouquet'
'hex': 'AE809E'
}
{
'name': 'Medium Carmine'
'hex': 'AF4035'
}
{
'name': 'Apple Blossom'
'hex': 'AF4D43'
}
{
'name': 'Brown Rust'
'hex': 'AF593E'
}
{
'name': 'Driftwood'
'hex': 'AF8751'
}
{
'name': 'Alpine'
'hex': 'AF8F2C'
}
{
'name': 'Lucky'
'hex': 'AF9F1C'
}
{
'name': 'Martini'
'hex': 'AFA09E'
}
{
'name': 'Bombay'
'hex': 'AFB1B8'
}
{
'name': 'Pigeon Post'
'hex': 'AFBDD9'
}
{
'name': 'Cadillac'
'hex': 'B04C6A'
}
{
'name': 'Matrix'
'hex': 'B05D54'
}
{
'name': 'Tapestry'
'hex': 'B05E81'
}
{
'name': 'Mai Tai'
'hex': 'B06608'
}
{
'name': 'Del Rio'
'hex': 'B09A95'
}
{
'name': 'Powder Blue'
'hex': 'B0E0E6'
}
{
'name': 'Inch Worm'
'hex': 'B0E313'
}
{
'name': 'Bright Red'
'hex': 'B10000'
}
{
'name': 'Vesuvius'
'hex': 'B14A0B'
}
{
'name': 'Pumpkin Skin'
'hex': 'B1610B'
}
{
'name': 'Santa Fe'
'hex': 'B16D52'
}
{
'name': 'Teak'
'hex': 'B19461'
}
{
'name': 'Fringy Flower'
'hex': 'B1E2C1'
}
{
'name': 'Ice Cold'
'hex': 'B1F4E7'
}
{
'name': 'Shiraz'
'hex': 'B20931'
}
{
'name': 'Biloba Flower'
'hex': 'B2A1EA'
}
{
'name': 'Tall Poppy'
'hex': 'B32D29'
}
{
'name': 'Fiery Orange'
'hex': 'B35213'
}
{
'name': 'Hot Toddy'
'hex': 'B38007'
}
{
'name': 'Taupe Gray'
'hex': 'B3AF95'
}
{
'name': 'La Rioja'
'hex': 'B3C110'
}
{
'name': 'Well Read'
'hex': 'B43332'
}
{
'name': 'Blush'
'hex': 'B44668'
}
{
'name': 'Jungle Mist'
'hex': 'B4CFD3'
}
{
'name': 'Turkish Rose'
'hex': 'B57281'
}
{
'name': 'Lavender'
'hex': 'B57EDC'
}
{
'name': 'Mongoose'
'hex': 'B5A27F'
}
{
'name': 'Olive Green'
'hex': 'B5B35C'
}
{
'name': 'Jet Stream'
'hex': 'B5D2CE'
}
{
'name': 'Cruise'
'hex': 'B5ECDF'
}
{
'name': 'Hibiscus'
'hex': 'B6316C'
}
{
'name': 'Thatch'
'hex': 'B69D98'
}
{
'name': 'Heathered Gray'
'hex': 'B6B095'
}
{
'name': 'Eagle'
'hex': 'B6BAA4'
}
{
'name': 'Spindle'
'hex': 'B6D1EA'
}
{
'name': 'Gum Leaf'
'hex': 'B6D3BF'
}
{
'name': 'Rust'
'hex': 'B7410E'
}
{
'name': 'Muddy Waters'
'hex': 'B78E5C'
}
{
'name': 'Sahara'
'hex': 'B7A214'
}
{
'name': 'Husk'
'hex': 'B7A458'
}
{
'name': 'Nobel'
'hex': 'B7B1B1'
}
{
'name': 'Heather'
'hex': 'B7C3D0'
}
{
'name': 'Madang'
'hex': 'B7F0BE'
}
{
'name': 'Milano Red'
'hex': 'B81104'
}
{
'name': 'Copper'
'hex': 'B87333'
}
{
'name': 'Gimblet'
'hex': 'B8B56A'
}
{
'name': 'Green Spring'
'hex': 'B8C1B1'
}
{
'name': 'Celery'
'hex': 'B8C25D'
}
{
'name': 'Sail'
'hex': 'B8E0F9'
}
{
'name': 'Chestnut'
'hex': 'B94E48'
}
{
'name': 'Crail'
'hex': 'B95140'
}
{
'name': 'Marigold'
'hex': 'B98D28'
}
{
'name': 'Wild Willow'
'hex': 'B9C46A'
}
{
'name': 'Rainee'
'hex': 'B9C8AC'
}
{
'name': 'Guardsman Red'
'hex': 'BA0101'
}
{
'name': 'Rock Spray'
'hex': 'BA450C'
}
{
'name': 'Bourbon'
'hex': 'BA6F1E'
}
{
'name': 'Pirate Gold'
'hex': 'BA7F03'
}
{
'name': 'Nomad'
'hex': 'BAB1A2'
}
{
'name': 'Submarine'
'hex': 'BAC7C9'
}
{
'name': 'Charlotte'
'hex': 'BAEEF9'
}
{
'name': 'Medium Red Violet'
'hex': 'BB3385'
}
{
'name': 'Brandy Rose'
'hex': 'BB8983'
}
{
'name': 'Rio Grande'
'hex': 'BBD009'
}
{
'name': 'Surf'
'hex': 'BBD7C1'
}
{
'name': 'Powder Ash'
'hex': 'BCC9C2'
}
{
'name': 'Tuscany'
'hex': 'BD5E2E'
}
{
'name': 'Quicksand'
'hex': 'BD978E'
}
{
'name': 'Silk'
'hex': 'BDB1A8'
}
{
'name': 'Malta'
'hex': 'BDB2A1'
}
{
'name': 'Chatelle'
'hex': 'BDB3C7'
}
{
'name': 'Lavender Gray'
'hex': 'BDBBD7'
}
{
'name': 'French Gray'
'hex': 'BDBDC6'
}
{
'name': 'Clay Ash'
'hex': 'BDC8B3'
}
{
'name': 'Loblolly'
'hex': 'BDC9CE'
}
{
'name': 'French Pass'
'hex': 'BDEDFD'
}
{
'name': 'London Hue'
'hex': 'BEA6C3'
}
{
'name': 'Pink Swan'
'hex': 'BEB5B7'
}
{
'name': 'Fuego'
'hex': 'BEDE0D'
}
{
'name': 'Rose of Sharon'
'hex': 'BF5500'
}
{
'name': 'Tide'
'hex': 'BFB8B0'
}
{
'name': 'Blue Haze'
'hex': 'BFBED8'
}
{
'name': 'Silver Sand'
'hex': 'BFC1C2'
}
{
'name': 'Key Lime Pie'
'hex': 'BFC921'
}
{
'name': 'Ziggurat'
'hex': 'BFDBE2'
}
{
'name': 'Lime'
'hex': 'BFFF00'
}
{
'name': 'Thunderbird'
'hex': 'C02B18'
}
{
'name': 'Mojo'
'hex': 'C04737'
}
{
'name': 'Old Rose'
'hex': 'C08081'
}
{
'name': 'Silver'
'hex': 'C0C0C0'
}
{
'name': 'Pale Leaf'
'hex': 'C0D3B9'
}
{
'name': 'Pixie Green'
'hex': 'C0D8B6'
}
{
'name': 'Tia Maria'
'hex': 'C1440E'
}
{
'name': 'Fuchsia Pink'
'hex': 'C154C1'
}
{
'name': 'Buddha Gold'
'hex': 'C1A004'
}
{
'name': 'Bison Hide'
'hex': 'C1B7A4'
}
{
'name': 'Tea'
'hex': 'C1BAB0'
}
{
'name': 'Gray Suit'
'hex': 'C1BECD'
}
{
'name': 'Sprout'
'hex': 'C1D7B0'
}
{
'name': 'Sulu'
'hex': 'C1F07C'
}
{
'name': 'Indochine'
'hex': 'C26B03'
}
{
'name': 'Twine'
'hex': 'C2955D'
}
{
'name': 'Cotton Seed'
'hex': 'C2BDB6'
}
{
'name': 'Pumice'
'hex': 'C2CAC4'
}
{
'name': 'Jagged Ice'
'hex': 'C2E8E5'
}
{
'name': 'Maroon Flush'
'hex': 'C32148'
}
{
'name': 'Indian Khaki'
'hex': 'C3B091'
}
{
'name': 'Pale Slate'
'hex': 'C3BFC1'
}
{
'name': 'Gray Nickel'
'hex': 'C3C3BD'
}
{
'name': 'Periwinkle Gray'
'hex': 'C3CDE6'
}
{
'name': 'Tiara'
'hex': 'C3D1D1'
}
{
'name': 'Tropical Blue'
'hex': 'C3DDF9'
}
{
'name': 'Cardinal'
'hex': 'C41E3A'
}
{
'name': 'Fuzzy Wuzzy Brown'
'hex': 'C45655'
}
{
'name': 'Orange Roughy'
'hex': 'C45719'
}
{
'name': 'Mist Gray'
'hex': 'C4C4BC'
}
{
'name': 'Coriander'
'hex': 'C4D0B0'
}
{
'name': 'Mint Tulip'
'hex': 'C4F4EB'
}
{
'name': 'Mulberry'
'hex': 'C54B8C'
}
{
'name': 'Nugget'
'hex': 'C59922'
}
{
'name': 'Tussock'
'hex': 'C5994B'
}
{
'name': 'Sea Mist'
'hex': 'C5DBCA'
}
{
'name': 'Yellow Green'
'hex': 'C5E17A'
}
{
'name': 'Brick Red'
'hex': 'C62D42'
}
{
'name': 'Contessa'
'hex': 'C6726B'
}
{
'name': 'Oriental Pink'
'hex': 'C69191'
}
{
'name': 'Roti'
'hex': 'C6A84B'
}
{
'name': 'Ash'
'hex': 'C6C3B5'
}
{
'name': 'Kangaroo'
'hex': 'C6C8BD'
}
{
'name': 'Las Palmas'
'hex': 'C6E610'
}
{
'name': 'Monza'
'hex': 'C7031E'
}
{
'name': 'Red Violet'
'hex': 'C71585'
}
{
'name': 'Coral Reef'
'hex': 'C7BCA2'
}
{
'name': 'Melrose'
'hex': 'C7C1FF'
}
{
'name': 'Cloud'
'hex': 'C7C4BF'
}
{
'name': 'Ghost'
'hex': 'C7C9D5'
}
{
'name': 'Pine Glade'
'hex': 'C7CD90'
}
{
'name': 'Botticelli'
'hex': 'C7DDE5'
}
{
'name': 'Antique Brass'
'hex': 'C88A65'
}
{
'name': 'Lilac'
'hex': 'C8A2C8'
}
{
'name': 'Hokey Pokey'
'hex': 'C8A528'
}
{
'name': 'Lily'
'hex': 'C8AABF'
}
{
'name': 'Laser'
'hex': 'C8B568'
}
{
'name': 'Edgewater'
'hex': 'C8E3D7'
}
{
'name': 'Piper'
'hex': 'C96323'
}
{
'name': 'Pizza'
'hex': 'C99415'
}
{
'name': 'Light Wisteria'
'hex': 'C9A0DC'
}
{
'name': 'Rodeo Dust'
'hex': 'C9B29B'
}
{
'name': 'Sundance'
'hex': 'C9B35B'
}
{
'name': 'Earls Green'
'hex': 'C9B93B'
}
{
'name': 'Silver Rust'
'hex': 'C9C0BB'
}
{
'name': 'Conch'
'hex': 'C9D9D2'
}
{
'name': 'Reef'
'hex': 'C9FFA2'
}
{
'name': 'Aero Blue'
'hex': 'C9FFE5'
}
{
'name': 'Flush Mahogany'
'hex': 'CA3435'
}
{
'name': 'Turmeric'
'hex': 'CABB48'
}
{
'name': 'Paris White'
'hex': 'CADCD4'
}
{
'name': 'Bitter Lemon'
'hex': 'CAE00D'
}
{
'name': 'Skeptic'
'hex': 'CAE6DA'
}
{
'name': 'Viola'
'hex': 'CB8FA9'
}
{
'name': 'Foggy Gray'
'hex': 'CBCAB6'
}
{
'name': 'Green Mist'
'hex': 'CBD3B0'
}
{
'name': 'Nebula'
'hex': 'CBDBD6'
}
{
'name': 'Persian Red'
'hex': 'CC3333'
}
{
'name': 'Burnt Orange'
'hex': 'CC5500'
}
{
'name': 'Ochre'
'hex': 'CC7722'
}
{
'name': 'Puce'
'hex': 'CC8899'
}
{
'name': 'Thistle Green'
'hex': 'CCCAA8'
}
{
'name': 'Periwinkle'
'hex': 'CCCCFF'
}
{
'name': 'Electric Lime'
'hex': 'CCFF00'
}
{
'name': 'Tenn'
'hex': 'CD5700'
}
{
'name': 'Chestnut Rose'
'hex': 'CD5C5C'
}
{
'name': 'Brandy Punch'
'hex': 'CD8429'
}
{
'name': 'Onahau'
'hex': 'CDF4FF'
}
{
'name': 'Sorrell Brown'
'hex': 'CEB98F'
}
{
'name': 'Cold Turkey'
'hex': 'CEBABA'
}
{
'name': 'Yuma'
'hex': 'CEC291'
}
{
'name': 'Chino'
'hex': 'CEC7A7'
}
{
'name': 'Eunry'
'hex': 'CFA39D'
}
{
'name': 'Old Gold'
'hex': 'CFB53B'
}
{
'name': 'Tasman'
'hex': 'CFDCCF'
}
{
'name': 'Surf Crest'
'hex': 'CFE5D2'
}
{
'name': 'Humming Bird'
'hex': 'CFF9F3'
}
{
'name': 'Scandal'
'hex': 'CFFAF4'
}
{
'name': 'Red Stage'
'hex': 'D05F04'
}
{
'name': 'Hopbush'
'hex': 'D06DA1'
}
{
'name': 'Meteor'
'hex': 'D07D12'
}
{
'name': 'Perfume'
'hex': 'D0BEF8'
}
{
'name': 'Prelude'
'hex': 'D0C0E5'
}
{
'name': 'Tea Green'
'hex': 'D0F0C0'
}
{
'name': 'Geebung'
'hex': 'D18F1B'
}
{
'name': 'Vanilla'
'hex': 'D1BEA8'
}
{
'name': 'Soft Amber'
'hex': 'D1C6B4'
}
{
'name': 'Celeste'
'hex': 'D1D2CA'
}
{
'name': 'Mischka'
'hex': 'D1D2DD'
}
{
'name': 'Pear'
'hex': 'D1E231'
}
{
'name': 'Hot Cinnamon'
'hex': 'D2691E'
}
{
'name': 'Raw Sienna'
'hex': 'D27D46'
}
{
'name': 'Careys Pink'
'hex': 'D29EAA'
}
{
'name': 'Tan'
'hex': 'D2B48C'
}
{
'name': 'Deco'
'hex': 'D2DA97'
}
{
'name': 'Blue Romance'
'hex': 'D2F6DE'
}
{
'name': 'Gossip'
'hex': 'D2F8B0'
}
{
'name': 'Sisal'
'hex': 'D3CBBA'
}
{
'name': 'Swirl'
'hex': 'D3CDC5'
}
{
'name': 'Charm'
'hex': 'D47494'
}
{
'name': 'Clam Shell'
'hex': 'D4B6AF'
}
{
'name': 'Straw'
'hex': 'D4BF8D'
}
{
'name': 'Akaroa'
'hex': 'D4C4A8'
}
{
'name': 'Bird Flower'
'hex': 'D4CD16'
}
{
'name': 'Iron'
'hex': 'D4D7D9'
}
{
'name': 'Geyser'
'hex': 'D4DFE2'
}
{
'name': 'Hawkes Blue'
'hex': 'D4E2FC'
}
{
'name': 'Grenadier'
'hex': 'D54600'
}
{
'name': 'Can Can'
'hex': 'D591A4'
}
{
'name': 'Whiskey'
'hex': 'D59A6F'
}
{
'name': 'Winter Hazel'
'hex': 'D5D195'
}
{
'name': 'Granny Apple'
'hex': 'D5F6E3'
}
{
'name': 'My Pink'
'hex': 'D69188'
}
{
'name': 'Tacha'
'hex': 'D6C562'
}
{
'name': 'Moon Raker'
'hex': 'D6CEF6'
}
{
'name': 'Quill Gray'
'hex': 'D6D6D1'
}
{
'name': 'Snowy Mint'
'hex': 'D6FFDB'
}
{
'name': 'New York Pink'
'hex': 'D7837F'
}
{
'name': 'Pavlova'
'hex': 'D7C498'
}
{
'name': 'Fog'
'hex': 'D7D0FF'
}
{
'name': 'Valencia'
'hex': 'D84437'
}
{
'name': 'Japonica'
'hex': 'D87C63'
}
{
'name': 'Thistle'
'hex': 'D8BFD8'
}
{
'name': 'Maverick'
'hex': 'D8C2D5'
}
{
'name': 'Foam'
'hex': 'D8FCFA'
}
{
'name': 'Cabaret'
'hex': 'D94972'
}
{
'name': 'Burning Sand'
'hex': 'D99376'
}
{
'name': 'Cameo'
'hex': 'D9B99B'
}
{
'name': 'Timberwolf'
'hex': 'D9D6CF'
}
{
'name': 'Tana'
'hex': 'D9DCC1'
}
{
'name': 'Link Water'
'hex': 'D9E4F5'
}
{
'name': 'Mabel'
'hex': 'D9F7FF'
}
{
'name': 'Cerise'
'hex': 'DA3287'
}
{
'name': 'Flame Pea'
'hex': 'DA5B38'
}
{
'name': 'Bamboo'
'hex': 'DA6304'
}
{
'name': 'Red Damask'
'hex': 'DA6A41'
}
{
'name': 'Orchid'
'hex': 'DA70D6'
}
{
'name': 'Copperfield'
'hex': 'DA8A67'
}
{
'name': 'Golden Grass'
'hex': 'DAA520'
}
{
'name': 'Zanah'
'hex': 'DAECD6'
}
{
'name': 'Iceberg'
'hex': 'DAF4F0'
}
{
'name': 'Oyster Bay'
'hex': 'DAFAFF'
}
{
'name': 'Cranberry'
'hex': 'DB5079'
}
{
'name': 'Petite Orchid'
'hex': 'DB9690'
}
{
'name': 'Di Serria'
'hex': 'DB995E'
}
{
'name': 'Alto'
'hex': 'DBDBDB'
}
{
'name': 'Frosted Mint'
'hex': 'DBFFF8'
}
{
'name': 'Crimson'
'hex': 'DC143C'
}
{
'name': 'Punch'
'hex': 'DC4333'
}
{
'name': 'Galliano'
'hex': 'DCB20C'
}
{
'name': 'Blossom'
'hex': 'DCB4BC'
}
{
'name': 'Wattle'
'hex': 'DCD747'
}
{
'name': 'Westar'
'hex': 'DCD9D2'
}
{
'name': 'Moon Mist'
'hex': 'DCDDCC'
}
{
'name': 'Caper'
'hex': 'DCEDB4'
}
{
'name': 'Swans Down'
'hex': 'DCF0EA'
}
{
'name': 'Swiss Coffee'
'hex': 'DDD6D5'
}
{
'name': 'White Ice'
'hex': 'DDF9F1'
}
{
'name': 'Cerise Red'
'hex': 'DE3163'
}
{
'name': 'Roman'
'hex': 'DE6360'
}
{
'name': 'Tumbleweed'
'hex': 'DEA681'
}
{
'name': 'Gold Tips'
'hex': 'DEBA13'
}
{
'name': 'Brandy'
'hex': 'DEC196'
}
{
'name': 'Wafer'
'hex': 'DECBC6'
}
{
'name': 'Sapling'
'hex': 'DED4A4'
}
{
'name': 'Barberry'
'hex': 'DED717'
}
{
'name': 'Beryl Green'
'hex': 'DEE5C0'
}
{
'name': 'Pattens Blue'
'hex': 'DEF5FF'
}
{
'name': 'Heliotrope'
'hex': 'DF73FF'
}
{
'name': 'Apache'
'hex': 'DFBE6F'
}
{
'name': 'Chenin'
'hex': 'DFCD6F'
}
{
'name': 'Lola'
'hex': 'DFCFDB'
}
{
'name': 'Willow Brook'
'hex': 'DFECDA'
}
{
'name': 'Chartreuse Yellow'
'hex': 'DFFF00'
}
{
'name': 'Mauve'
'hex': 'E0B0FF'
}
{
'name': 'Anzac'
'hex': 'E0B646'
}
{
'name': 'Harvest Gold'
'hex': 'E0B974'
}
{
'name': 'Calico'
'hex': 'E0C095'
}
{
'name': 'Baby Blue'
'hex': 'E0FFFF'
}
{
'name': 'Sunglo'
'hex': 'E16865'
}
{
'name': 'Equator'
'hex': 'E1BC64'
}
{
'name': 'Pink Flare'
'hex': 'E1C0C8'
}
{
'name': 'Periglacial Blue'
'hex': 'E1E6D6'
}
{
'name': 'Kidnapper'
'hex': 'E1EAD4'
}
{
'name': 'Tara'
'hex': 'E1F6E8'
}
{
'name': 'Mandy'
'hex': 'E25465'
}
{
'name': 'Terracotta'
'hex': 'E2725B'
}
{
'name': 'Golden Bell'
'hex': 'E28913'
}
{
'name': 'Shocking'
'hex': 'E292C0'
}
{
'name': 'Dixie'
'hex': 'E29418'
}
{
'name': 'Light Orchid'
'hex': 'E29CD2'
}
{
'name': 'Snuff'
'hex': 'E2D8ED'
}
{
'name': 'Mystic'
'hex': 'E2EBED'
}
{
'name': 'Apple Green'
'hex': 'E2F3EC'
}
{
'name': 'Razzmatazz'
'hex': 'E30B5C'
}
{
'name': 'Alizarin Crimson'
'hex': 'E32636'
}
{
'name': 'Cinnabar'
'hex': 'E34234'
}
{
'name': 'Cavern Pink'
'hex': 'E3BEBE'
}
{
'name': 'Peppermint'
'hex': 'E3F5E1'
}
{
'name': 'Mindaro'
'hex': 'E3F988'
}
{
'name': 'Deep Blush'
'hex': 'E47698'
}
{
'name': 'Gamboge'
'hex': 'E49B0F'
}
{
'name': 'Melanie'
'hex': 'E4C2D5'
}
{
'name': 'Twilight'
'hex': 'E4CFDE'
}
{
'name': 'Bone'
'hex': 'E4D1C0'
}
{
'name': 'Sunflower'
'hex': 'E4D422'
}
{
'name': 'Grain Brown'
'hex': 'E4D5B7'
}
{
'name': 'Zombie'
'hex': 'E4D69B'
}
{
'name': 'Frostee'
'hex': 'E4F6E7'
}
{
'name': 'Snow Flurry'
'hex': 'E4FFD1'
}
{
'name': 'Amaranth'
'hex': 'E52B50'
}
{
'name': 'Zest'
'hex': 'E5841B'
}
{
'name': 'Dust Storm'
'hex': 'E5CCC9'
}
{
'name': 'Stark White'
'hex': 'E5D7BD'
}
{
'name': 'Hampton'
'hex': 'E5D8AF'
}
{
'name': 'Bon Jour'
'hex': 'E5E0E1'
}
{
'name': 'Mercury'
'hex': 'E5E5E5'
}
{
'name': 'Polar'
'hex': 'E5F9F6'
}
{
'name': 'Trinidad'
'hex': 'E64E03'
}
{
'name': 'Gold Sand'
'hex': 'E6BE8A'
}
{
'name': 'Cashmere'
'hex': 'E6BEA5'
}
{
'name': 'Double Spanish White'
'hex': 'E6D7B9'
}
{
'name': 'Satin Linen'
'hex': 'E6E4D4'
}
{
'name': 'Harp'
'hex': 'E6F2EA'
}
{
'name': 'Off Green'
'hex': 'E6F8F3'
}
{
'name': 'Hint of Green'
'hex': 'E6FFE9'
}
{
'name': 'Tranquil'
'hex': 'E6FFFF'
}
{
'name': 'Mango Tango'
'hex': 'E77200'
}
{
'name': 'Christine'
'hex': 'E7730A'
}
{
'name': 'Tonys Pink'
'hex': 'E79F8C'
}
{
'name': 'Kobi'
'hex': 'E79FC4'
}
{
'name': 'Rose Fog'
'hex': 'E7BCB4'
}
{
'name': 'Corn'
'hex': 'E7BF05'
}
{
'name': 'Putty'
'hex': 'E7CD8C'
}
{
'name': 'Gray Nurse'
'hex': 'E7ECE6'
}
{
'name': 'Lily White'
'hex': 'E7F8FF'
}
{
'name': 'Bubbles'
'hex': 'E7FEFF'
}
{
'name': 'Fire Bush'
'hex': 'E89928'
}
{
'name': 'Shilo'
'hex': 'E8B9B3'
}
{
'name': 'Pearl Bush'
'hex': 'E8E0D5'
}
{
'name': 'Green White'
'hex': 'E8EBE0'
}
{
'name': 'Chrome White'
'hex': 'E8F1D4'
}
{
'name': 'Gin'
'hex': 'E8F2EB'
}
{
'name': 'Aqua Squeeze'
'hex': 'E8F5F2'
}
{
'name': 'Clementine'
'hex': 'E96E00'
}
{
'name': 'Burnt Sienna'
'hex': 'E97451'
}
{
'name': 'Tahiti Gold'
'hex': 'E97C07'
}
{
'name': 'Oyster Pink'
'hex': 'E9CECD'
}
{
'name': 'Confetti'
'hex': 'E9D75A'
}
{
'name': 'Ebb'
'hex': 'E9E3E3'
}
{
'name': 'Ottoman'
'hex': 'E9F8ED'
}
{
'name': 'Clear Day'
'hex': 'E9FFFD'
}
{
'name': 'Carissma'
'hex': 'EA88A8'
}
{
'name': 'Porsche'
'hex': 'EAAE69'
}
{
'name': 'Tulip Tree'
'hex': 'EAB33B'
}
{
'name': 'Rob Roy'
'hex': 'EAC674'
}
{
'name': 'Raffia'
'hex': 'EADAB8'
}
{
'name': 'White Rock'
'hex': 'EAE8D4'
}
{
'name': 'Panache'
'hex': 'EAF6EE'
}
{
'name': 'Solitude'
'hex': 'EAF6FF'
}
{
'name': 'Aqua Spring'
'hex': 'EAF9F5'
}
{
'name': 'Dew'
'hex': 'EAFFFE'
}
{
'name': 'Apricot'
'hex': 'EB9373'
}
{
'name': 'Zinnwaldite'
'hex': 'EBC2AF'
}
{
'name': 'Fuel Yellow'
'hex': 'ECA927'
}
{
'name': 'Ronchi'
'hex': 'ECC54E'
}
{
'name': 'French Lilac'
'hex': 'ECC7EE'
}
{
'name': 'Just Right'
'hex': 'ECCDB9'
}
{
'name': 'Wild Rice'
'hex': 'ECE090'
}
{
'name': 'Fall Green'
'hex': 'ECEBBD'
}
{
'name': 'Aths Special'
'hex': 'ECEBCE'
}
{
'name': 'Starship'
'hex': 'ECF245'
}
{
'name': 'Red Ribbon'
'hex': 'ED0A3F'
}
{
'name': 'Tango'
'hex': 'ED7A1C'
}
{
'name': 'Carrot Orange'
'hex': 'ED9121'
}
{
'name': 'Sea Pink'
'hex': 'ED989E'
}
{
'name': 'Tacao'
'hex': 'EDB381'
}
{
'name': 'Desert Sand'
'hex': 'EDC9AF'
}
{
'name': 'Pancho'
'hex': 'EDCDAB'
}
{
'name': 'Chamois'
'hex': 'EDDCB1'
}
{
'name': 'Primrose'
'hex': 'EDEA99'
}
{
'name': 'Frost'
'hex': 'EDF5DD'
}
{
'name': 'Aqua Haze'
'hex': 'EDF5F5'
}
{
'name': 'Zumthor'
'hex': 'EDF6FF'
}
{
'name': 'Narvik'
'hex': 'EDF9F1'
}
{
'name': 'Honeysuckle'
'hex': 'EDFC84'
}
{
'name': 'Lavender Magenta'
'hex': 'EE82EE'
}
{
'name': 'Beauty Bush'
'hex': 'EEC1BE'
}
{
'name': 'Chalky'
'hex': 'EED794'
}
{
'name': 'Almond'
'hex': 'EED9C4'
}
{
'name': 'Flax'
'hex': 'EEDC82'
}
{
'name': 'Bizarre'
'hex': 'EEDEDA'
}
{
'name': 'Double Colonial White'
'hex': 'EEE3AD'
}
{
'name': 'Cararra'
'hex': 'EEEEE8'
}
{
'name': 'Manz'
'hex': 'EEEF78'
}
{
'name': 'Tahuna Sands'
'hex': 'EEF0C8'
}
{
'name': 'Athens Gray'
'hex': 'EEF0F3'
}
{
'name': 'Tusk'
'hex': 'EEF3C3'
}
{
'name': 'Loafer'
'hex': 'EEF4DE'
}
{
'name': 'Catskill White'
'hex': 'EEF6F7'
}
{
'name': 'Twilight Blue'
'hex': 'EEFDFF'
}
{
'name': 'Jonquil'
'hex': 'EEFF9A'
}
{
'name': 'Rice Flower'
'hex': 'EEFFE2'
}
{
'name': 'Jaffa'
'hex': 'EF863F'
}
{
'name': 'Gallery'
'hex': 'EFEFEF'
}
{
'name': 'Porcelain'
'hex': 'EFF2F3'
}
{
'name': 'Mauvelous'
'hex': 'F091A9'
}
{
'name': 'Golden Dream'
'hex': 'F0D52D'
}
{
'name': 'Golden Sand'
'hex': 'F0DB7D'
}
{
'name': 'Buff'
'hex': 'F0DC82'
}
{
'name': 'Prim'
'hex': 'F0E2EC'
}
{
'name': 'Khaki'
'hex': 'F0E68C'
}
{
'name': 'Selago'
'hex': 'F0EEFD'
}
{
'name': 'Titan White'
'hex': 'F0EEFF'
}
{
'name': 'Alice Blue'
'hex': 'F0F8FF'
}
{
'name': 'Feta'
'hex': 'F0FCEA'
}
{
'name': 'Gold Drop'
'hex': 'F18200'
}
{
'name': 'Wewak'
'hex': 'F19BAB'
}
{
'name': 'Sahara Sand'
'hex': 'F1E788'
}
{
'name': 'Parchment'
'hex': 'F1E9D2'
}
{
'name': 'Blue Chalk'
'hex': 'F1E9FF'
}
{
'name': 'Mint Julep'
'hex': 'F1EEC1'
}
{
'name': 'Seashell'
'hex': 'F1F1F1'
}
{
'name': 'Saltpan'
'hex': 'F1F7F2'
}
{
'name': 'Tidal'
'hex': 'F1FFAD'
}
{
'name': 'Chiffon'
'hex': 'F1FFC8'
}
{
'name': 'Flamingo'
'hex': 'F2552A'
}
{
'name': 'Tangerine'
'hex': 'F28500'
}
{
'name': 'Mandys Pink'
'hex': 'F2C3B2'
}
{
'name': 'Concrete'
'hex': 'F2F2F2'
}
{
'name': 'Black Squeeze'
'hex': 'F2FAFA'
}
{
'name': 'Pomegranate'
'hex': 'F34723'
}
{
'name': 'Buttercup'
'hex': 'F3AD16'
}
{
'name': 'New Orleans'
'hex': 'F3D69D'
}
{
'name': 'Vanilla Ice'
'hex': 'F3D9DF'
}
{
'name': 'Sidecar'
'hex': 'F3E7BB'
}
{
'name': 'Dawn Pink'
'hex': 'F3E9E5'
}
{
'name': 'Wheatfield'
'hex': 'F3EDCF'
}
{
'name': 'Canary'
'hex': 'F3FB62'
}
{
'name': 'Orinoco'
'hex': 'F3FBD4'
}
{
'name': 'Carla'
'hex': 'F3FFD8'
}
{
'name': 'Hollywood Cerise'
'hex': 'F400A1'
}
{
'name': 'Sandy brown'
'hex': 'F4A460'
}
{
'name': 'Saffron'
'hex': 'F4C430'
}
{
'name': 'Ripe Lemon'
'hex': 'F4D81C'
}
{
'name': 'Janna'
'hex': 'F4EBD3'
}
{
'name': 'Pampas'
'hex': 'F4F2EE'
}
{
'name': 'Wild Sand'
'hex': 'F4F4F4'
}
{
'name': 'Zircon'
'hex': 'F4F8FF'
}
{
'name': 'Froly'
'hex': 'F57584'
}
{
'name': 'Cream Can'
'hex': 'F5C85C'
}
{
'name': 'Manhattan'
'hex': 'F5C999'
}
{
'name': 'Maize'
'hex': 'F5D5A0'
}
{
'name': 'Wheat'
'hex': 'F5DEB3'
}
{
'name': 'Sandwisp'
'hex': 'F5E7A2'
}
{
'name': 'Pot Pourri'
'hex': 'F5E7E2'
}
{
'name': 'Albescent White'
'hex': 'F5E9D3'
}
{
'name': 'Soft Peach'
'hex': 'F5EDEF'
}
{
'name': 'Ecru White'
'hex': 'F5F3E5'
}
{
'name': 'Beige'
'hex': 'F5F5DC'
}
{
'name': 'Golden Fizz'
'hex': 'F5FB3D'
}
{
'name': 'Australian Mint'
'hex': 'F5FFBE'
}
{
'name': 'French Rose'
'hex': 'F64A8A'
}
{
'name': 'Brilliant Rose'
'hex': 'F653A6'
}
{
'name': 'Illusion'
'hex': 'F6A4C9'
}
{
'name': 'Merino'
'hex': 'F6F0E6'
}
{
'name': 'Black Haze'
'hex': 'F6F7F7'
}
{
'name': 'Spring Sun'
'hex': 'F6FFDC'
}
{
'name': 'Violet Red'
'hex': 'F7468A'
}
{
'name': 'Chilean Fire'
'hex': 'F77703'
}
{
'name': 'Persian Pink'
'hex': 'F77FBE'
}
{
'name': 'Rajah'
'hex': 'F7B668'
}
{
'name': 'Azalea'
'hex': 'F7C8DA'
}
{
'name': 'We Peep'
'hex': 'F7DBE6'
}
{
'name': 'Quarter Spanish White'
'hex': 'F7F2E1'
}
{
'name': 'Whisper'
'hex': 'F7F5FA'
}
{
'name': 'Snow Drift'
'hex': 'F7FAF7'
}
{
'name': 'Casablanca'
'hex': 'F8B853'
}
{
'name': 'Chantilly'
'hex': 'F8C3DF'
}
{
'name': 'Cherub'
'hex': 'F8D9E9'
}
{
'name': 'Marzipan'
'hex': 'F8DB9D'
}
{
'name': 'Energy Yellow'
'hex': 'F8DD5C'
}
{
'name': 'Givry'
'hex': 'F8E4BF'
}
{
'name': 'White Linen'
'hex': 'F8F0E8'
}
{
'name': 'Magnolia'
'hex': 'F8F4FF'
}
{
'name': 'Spring Wood'
'hex': 'F8F6F1'
}
{
'name': 'Coconut Cream'
'hex': 'F8F7DC'
}
{
'name': 'White Lilac'
'hex': 'F8F7FC'
}
{
'name': 'Desert Storm'
'hex': 'F8F8F7'
}
{
'name': 'Texas'
'hex': 'F8F99C'
}
{
'name': 'Corn Field'
'hex': 'F8FACD'
}
{
'name': 'Mimosa'
'hex': 'F8FDD3'
}
{
'name': 'Carnation'
'hex': 'F95A61'
}
{
'name': 'Saffron Mango'
'hex': 'F9BF58'
}
{
'name': 'Carousel Pink'
'hex': 'F9E0ED'
}
{
'name': 'Dairy Cream'
'hex': 'F9E4BC'
}
{
'name': 'Portica'
'hex': 'F9E663'
}
{
'name': 'Amour'
'hex': 'F9EAF3'
}
{
'name': 'Rum Swizzle'
'hex': 'F9F8E4'
}
{
'name': 'Dolly'
'hex': 'F9FF8B'
}
{
'name': 'Sugar Cane'
'hex': 'F9FFF6'
}
{
'name': 'Ecstasy'
'hex': 'FA7814'
}
{
'name': 'Tan Hide'
'hex': 'FA9D5A'
}
{
'name': 'Corvette'
'hex': 'FAD3A2'
}
{
'name': 'Peach Yellow'
'hex': 'FADFAD'
}
{
'name': 'Turbo'
'hex': 'FAE600'
}
{
'name': 'Astra'
'hex': 'FAEAB9'
}
{
'name': 'Champagne'
'hex': 'FAECCC'
}
{
'name': 'Linen'
'hex': 'FAF0E6'
}
{
'name': 'Fantasy'
'hex': 'FAF3F0'
}
{
'name': 'Citrine White'
'hex': 'FAF7D6'
}
{
'name': 'Alabaster'
'hex': 'FAFAFA'
}
{
'name': 'Hint of Yellow'
'hex': 'FAFDE4'
}
{
'name': 'Milan'
'hex': 'FAFFA4'
}
{
'name': 'Brink Pink'
'hex': 'FB607F'
}
{
'name': 'Geraldine'
'hex': 'FB8989'
}
{
'name': 'Lavender Rose'
'hex': 'FBA0E3'
}
{
'name': 'Sea Buckthorn'
'hex': 'FBA129'
}
{
'name': 'Sun'
'hex': 'FBAC13'
}
{
'name': 'Lavender Pink'
'hex': 'FBAED2'
}
{
'name': 'Rose Bud'
'hex': 'FBB2A3'
}
{
'name': 'Cupid'
'hex': 'FBBEDA'
}
{
'name': 'Classic Rose'
'hex': 'FBCCE7'
}
{
'name': 'Apricot Peach'
'hex': 'FBCEB1'
}
{
'name': 'Banana Mania'
'hex': 'FBE7B2'
}
{
'name': 'Marigold Yellow'
'hex': 'FBE870'
}
{
'name': 'Festival'
'hex': 'FBE96C'
}
{
'name': 'Sweet Corn'
'hex': 'FBEA8C'
}
{
'name': 'Candy Corn'
'hex': 'FBEC5D'
}
{
'name': 'Hint of Red'
'hex': 'FBF9F9'
}
{
'name': 'Shalimar'
'hex': 'FBFFBA'
}
{
'name': 'Shocking Pink'
'hex': 'FC0FC0'
}
{
'name': 'Tickle Me Pink'
'hex': 'FC80A5'
}
{
'name': 'Tree Poppy'
'hex': 'FC9C1D'
}
{
'name': 'Lightning Yellow'
'hex': 'FCC01E'
}
{
'name': 'Goldenrod'
'hex': 'FCD667'
}
{
'name': 'Candlelight'
'hex': 'FCD917'
}
{
'name': 'Cherokee'
'hex': 'FCDA98'
}
{
'name': 'Double Pearl Lusta'
'hex': 'FCF4D0'
}
{
'name': 'Pearl Lusta'
'hex': 'FCF4DC'
}
{
'name': 'Vista White'
'hex': 'FCF8F7'
}
{
'name': 'Bianca'
'hex': 'FCFBF3'
}
{
'name': 'Moon Glow'
'hex': 'FCFEDA'
}
{
'name': 'China Ivory'
'hex': 'FCFFE7'
}
{
'name': 'Ceramic'
'hex': 'FCFFF9'
}
{
'name': 'Torch Red'
'hex': 'FD0E35'
}
{
'name': 'Wild Watermelon'
'hex': 'FD5B78'
}
{
'name': 'Crusta'
'hex': 'FD7B33'
}
{
'name': 'Sorbus'
'hex': 'FD7C07'
}
{
'name': 'Sweet Pink'
'hex': 'FD9FA2'
}
{
'name': 'Light Apricot'
'hex': 'FDD5B1'
}
{
'name': 'Pig Pink'
'hex': 'FDD7E4'
}
{
'name': 'Cinderella'
'hex': 'FDE1DC'
}
{
'name': 'Golden Glow'
'hex': 'FDE295'
}
{
'name': 'Lemon'
'hex': 'FDE910'
}
{
'name': 'Old Lace'
'hex': 'FDF5E6'
}
{
'name': 'Half Colonial White'
'hex': 'FDF6D3'
}
{
'name': 'Drover'
'hex': 'FDF7AD'
}
{
'name': 'Pale Prim'
'hex': 'FDFEB8'
}
{
'name': 'Cumulus'
'hex': 'FDFFD5'
}
{
'name': 'Persian Rose'
'hex': 'FE28A2'
}
{
'name': 'Sunset Orange'
'hex': 'FE4C40'
}
{
'name': 'Bittersweet'
'hex': 'FE6F5E'
}
{
'name': 'California'
'hex': 'FE9D04'
}
{
'name': 'Yellow Sea'
'hex': 'FEA904'
}
{
'name': 'Melon'
'hex': 'FEBAAD'
}
{
'name': 'Bright Sun'
'hex': 'FED33C'
}
{
'name': 'Dandelion'
'hex': 'FED85D'
}
{
'name': 'Salomie'
'hex': 'FEDB8D'
}
{
'name': 'Cape Honey'
'hex': 'FEE5AC'
}
{
'name': 'Remy'
'hex': 'FEEBF3'
}
{
'name': 'Oasis'
'hex': 'FEEFCE'
}
{
'name': 'Bridesmaid'
'hex': 'FEF0EC'
}
{
'name': 'Beeswax'
'hex': 'FEF2C7'
}
{
'name': 'Bleach White'
'hex': 'FEF3D8'
}
{
'name': 'Pipi'
'hex': 'FEF4CC'
}
{
'name': 'Half Spanish White'
'hex': 'FEF4DB'
}
{
'name': 'Wisp Pink'
'hex': 'FEF4F8'
}
{
'name': 'Provincial Pink'
'hex': 'FEF5F1'
}
{
'name': 'Half Dutch White'
'hex': 'FEF7DE'
}
{
'name': 'Solitaire'
'hex': 'FEF8E2'
}
{
'name': 'White Pointer'
'hex': 'FEF8FF'
}
{
'name': 'Off Yellow'
'hex': 'FEF9E3'
}
{
'name': 'Orange White'
'hex': 'FEFCED'
}
{
'name': 'Red'
'hex': 'FF0000'
}
{
'name': 'Rose'
'hex': 'FF007F'
}
{
'name': 'Purple Pizzazz'
'hex': 'FF00CC'
}
{
'name': 'Magenta / Fuchsia'
'hex': 'FF00FF'
}
{
'name': 'Scarlet'
'hex': 'FF2400'
}
{
'name': 'Wild Strawberry'
'hex': 'FF3399'
}
{
'name': 'Razzle Dazzle Rose'
'hex': 'FF33CC'
}
{
'name': 'Radical Red'
'hex': 'FF355E'
}
{
'name': 'Red Orange'
'hex': 'FF3F34'
}
{
'name': 'Coral Red'
'hex': 'FF4040'
}
{
'name': 'Vermilion'
'hex': 'FF4D00'
}
{
'name': 'International Orange'
'hex': 'FF4F00'
}
{
'name': 'Outrageous Orange'
'hex': 'FF6037'
}
{
'name': 'Blaze Orange'
'hex': 'FF6600'
}
{
'name': 'Pink Flamingo'
'hex': 'FF66FF'
}
{
'name': 'Orange'
'hex': 'FF681F'
}
{
'name': 'Hot Pink'
'hex': 'FF69B4'
}
{
'name': 'Persimmon'
'hex': 'FF6B53'
}
{
'name': 'Blush Pink'
'hex': 'FF6FFF'
}
{
'name': 'Burning Orange'
'hex': 'FF7034'
}
{
'name': 'Pumpkin'
'hex': 'FF7518'
}
{
'name': 'Flamenco'
'hex': 'FF7D07'
}
{
'name': 'Flush Orange'
'hex': 'FF7F00'
}
{
'name': 'Coral'
'hex': 'FF7F50'
}
{
'name': 'Salmon'
'hex': 'FF8C69'
}
{
'name': 'Pizazz'
'hex': 'FF9000'
}
{
'name': 'West Side'
'hex': 'FF910F'
}
{
'name': 'Pink Salmon'
'hex': 'FF91A4'
}
{
'name': 'Neon Carrot'
'hex': 'FF9933'
}
{
'name': 'Atomic Tangerine'
'hex': 'FF9966'
}
{
'name': 'Vivid Tangerine'
'hex': 'FF9980'
}
{
'name': 'Sunshade'
'hex': 'FF9E2C'
}
{
'name': 'Orange Peel'
'hex': 'FFA000'
}
{
'name': 'Mona Lisa'
'hex': 'FFA194'
}
{
'name': 'Web Orange'
'hex': 'FFA500'
}
{
'name': 'Carnation Pink'
'hex': 'FFA6C9'
}
{
'name': 'Hit Pink'
'hex': 'FFAB81'
}
{
'name': 'Yellow Orange'
'hex': 'FFAE42'
}
{
'name': 'Cornflower Lilac'
'hex': 'FFB0AC'
}
{
'name': 'Sundown'
'hex': 'FFB1B3'
}
{
'name': 'My Sin'
'hex': 'FFB31F'
}
{
'name': 'Texas Rose'
'hex': 'FFB555'
}
{
'name': 'Cotton Candy'
'hex': 'FFB7D5'
}
{
'name': 'Macaroni and Cheese'
'hex': 'FFB97B'
}
{
'name': 'Selective Yellow'
'hex': 'FFBA00'
}
{
'name': 'Koromiko'
'hex': 'FFBD5F'
}
{
'name': 'Amber'
'hex': 'FFBF00'
}
{
'name': 'Wax Flower'
'hex': 'FFC0A8'
}
{
'name': 'Pink'
'hex': 'FFC0CB'
}
{
'name': 'Your Pink'
'hex': 'FFC3C0'
}
{
'name': 'Supernova'
'hex': 'FFC901'
}
{
'name': 'Flesh'
'hex': 'FFCBA4'
}
{
'name': 'Sunglow'
'hex': 'FFCC33'
}
{
'name': 'Golden Tainoi'
'hex': 'FFCC5C'
}
{
'name': 'Peach Orange'
'hex': 'FFCC99'
}
{
'name': 'Chardonnay'
'hex': 'FFCD8C'
}
{
'name': 'Pastel Pink'
'hex': 'FFD1DC'
}
{
'name': 'Romantic'
'hex': 'FFD2B7'
}
{
'name': 'Grandis'
'hex': 'FFD38C'
}
{
'name': 'Gold'
'hex': 'FFD700'
}
{
'name': 'School bus Yellow'
'hex': 'FFD800'
}
{
'name': 'Cosmos'
'hex': 'FFD8D9'
}
{
'name': 'Mustard'
'hex': 'FFDB58'
}
{
'name': 'Peach Schnapps'
'hex': 'FFDCD6'
}
{
'name': 'Caramel'
'hex': 'FFDDAF'
}
{
'name': 'Tuft Bush'
'hex': 'FFDDCD'
}
{
'name': 'Watusi'
'hex': 'FFDDCF'
}
{
'name': 'Pink Lace'
'hex': 'FFDDF4'
}
{
'name': 'Navajo White'
'hex': 'FFDEAD'
}
{
'name': 'Frangipani'
'hex': 'FFDEB3'
}
{
'name': 'Pippin'
'hex': 'FFE1DF'
}
{
'name': 'Pale Rose'
'hex': 'FFE1F2'
}
{
'name': 'Negroni'
'hex': 'FFE2C5'
}
{
'name': 'Cream Brulee'
'hex': 'FFE5A0'
}
{
'name': 'Peach'
'hex': 'FFE5B4'
}
{
'name': 'Tequila'
'hex': 'FFE6C7'
}
{
'name': 'Kournikova'
'hex': 'FFE772'
}
{
'name': 'Sandy Beach'
'hex': 'FFEAC8'
}
{
'name': 'Karry'
'hex': 'FFEAD4'
}
{
'name': 'Broom'
'hex': 'FFEC13'
}
{
'name': 'Colonial White'
'hex': 'FFEDBC'
}
{
'name': 'Derby'
'hex': 'FFEED8'
}
{
'name': 'Vis Vis'
'hex': 'FFEFA1'
}
{
'name': 'Egg White'
'hex': 'FFEFC1'
}
{
'name': 'Papaya Whip'
'hex': 'FFEFD5'
}
{
'name': 'Fair Pink'
'hex': 'FFEFEC'
}
{
'name': 'Peach Cream'
'hex': 'FFF0DB'
}
{
'name': 'Lavender blush'
'hex': 'FFF0F5'
}
{
'name': 'Gorse'
'hex': 'FFF14F'
}
{
'name': 'Buttermilk'
'hex': 'FFF1B5'
}
{
'name': 'Pink Lady'
'hex': 'FFF1D8'
}
{
'name': 'Forget Me Not'
'hex': 'FFF1EE'
}
{
'name': 'Tutu'
'hex': 'FFF1F9'
}
{
'name': 'Picasso'
'hex': 'FFF39D'
}
{
'name': 'Chardon'
'hex': 'FFF3F1'
}
{
'name': 'Paris Daisy'
'hex': 'FFF46E'
}
{
'name': 'Barley White'
'hex': 'FFF4CE'
}
{
'name': 'Egg Sour'
'hex': 'FFF4DD'
}
{
'name': 'Sazerac'
'hex': 'FFF4E0'
}
{
'name': 'Serenade'
'hex': 'FFF4E8'
}
{
'name': 'Chablis'
'hex': 'FFF4F3'
}
{
'name': 'Seashell Peach'
'hex': 'FFF5EE'
}
{
'name': 'Sauvignon'
'hex': 'FFF5F3'
}
{
'name': 'Milk Punch'
'hex': 'FFF6D4'
}
{
'name': 'Varden'
'hex': 'FFF6DF'
}
{
'name': 'Rose White'
'hex': 'FFF6F5'
}
{
'name': 'Baja White'
'hex': 'FFF8D1'
}
{
'name': 'Gin Fizz'
'hex': 'FFF9E2'
}
{
'name': 'Early Dawn'
'hex': 'FFF9E6'
}
{
'name': 'Lemon Chiffon'
'hex': 'FFFACD'
}
{
'name': 'Bridal Heath'
'hex': 'FFFAF4'
}
{
'name': 'Scotch Mist'
'hex': 'FFFBDC'
}
{
'name': 'Soapstone'
'hex': 'FFFBF9'
}
{
'name': 'Witch Haze'
'hex': 'FFFC99'
}
{
'name': 'Buttery White'
'hex': 'FFFCEA'
}
{
'name': 'Island Spice'
'hex': 'FFFCEE'
}
{
'name': 'Cream'
'hex': 'FFFDD0'
}
{
'name': 'Chilean Heath'
'hex': 'FFFDE6'
}
{
'name': 'Travertine'
'hex': 'FFFDE8'
}
{
'name': 'Orchid White'
'hex': 'FFFDF3'
}
{
'name': 'Quarter Pearl Lusta'
'hex': 'FFFDF4'
}
{
'name': 'Half and Half'
'hex': 'FFFEE1'
}
{
'name': 'Apricot White'
'hex': 'FFFEEC'
}
{
'name': 'Rice Cake'
'hex': 'FFFEF0'
}
{
'name': 'Black White'
'hex': 'FFFEF6'
}
{
'name': 'Romance'
'hex': 'FFFEFD'
}
{
'name': 'Yellow'
'hex': 'FFFF00'
}
{
'name': 'Laser Lemon'
'hex': 'FFFF66'
}
{
'name': 'Pale Canary'
'hex': 'FFFF99'
}
{
'name': 'Portafino'
'hex': 'FFFFB4'
}
{
'name': 'Ivory'
'hex': 'FFFFF0'
}
{
'name': 'White'
'hex': 'FFFFFF'
}
]
| 194039 | module.exports = [
{
'name': 'Black'
'hex': '000000'
}
{
'name': 'Navy Blue'
'hex': '000080'
}
{
'name': 'Dark Blue'
'hex': '0000C8'
}
{
'name': 'Blue'
'hex': '0000FF'
}
{
'name': 'Stratos'
'hex': '000741'
}
{
'name': 'Swamp'
'hex': '001B1C'
}
{
'name': 'Resolution Blue'
'hex': '002387'
}
{
'name': 'Deep Fir'
'hex': '002900'
}
{
'name': '<NAME>'
'hex': '002E20'
}
{
'name': 'International Klein Blue'
'hex': '002FA7'
}
{
'name': 'Prussian Blue'
'hex': '003153'
}
{
'name': 'Midnight Blue'
'hex': '003366'
}
{
'name': '<NAME>'
'hex': '003399'
}
{
'name': 'Deep Teal'
'hex': '003532'
}
{
'name': '<NAME>'
'hex': '003E40'
}
{
'name': '<NAME>'
'hex': '004620'
}
{
'name': '<NAME>'
'hex': '0047AB'
}
{
'name': '<NAME>'
'hex': '004816'
}
{
'name': 'Sherpa Blue'
'hex': '004950'
}
{
'name': 'Endeavour'
'hex': '0056A7'
}
{
'name': '<NAME>'
'hex': '00581A'
}
{
'name': 'Science Blue'
'hex': '0066CC'
}
{
'name': 'Blue Ribbon'
'hex': '0066FF'
}
{
'name': 'Tropical Rain Forest'
'hex': '00755E'
}
{
'name': 'Allports'
'hex': '0076A3'
}
{
'name': 'Deep Cerulean'
'hex': '007BA7'
}
{
'name': 'Lochmara'
'hex': '007EC7'
}
{
'name': 'Azure Radiance'
'hex': '007FFF'
}
{
'name': '<NAME>'
'hex': '008080'
}
{
'name': '<NAME>'
'hex': '0095B6'
}
{
'name': '<NAME>'
'hex': '009DC4'
}
{
'name': '<NAME>'
'hex': '00A693'
}
{
'name': '<NAME>'
'hex': '00A86B'
}
{
'name': '<NAME>'
'hex': '00CC99'
}
{
'name': '<NAME>'
'hex': '00CCCC'
}
{
'name': 'Green'
'hex': '00FF00'
}
{
'name': 'Spring Green'
'hex': '00FF7F'
}
{
'name': 'Cyan / Aqua'
'hex': '00FFFF'
}
{
'name': 'Blue Charcoal'
'hex': '010D1A'
}
{
'name': 'Midnight'
'hex': '011635'
}
{
'name': '<NAME>'
'hex': '011D13'
}
{
'name': '<NAME>'
'hex': '012731'
}
{
'name': 'Cardin Green'
'hex': '01361C'
}
{
'name': 'County Green'
'hex': '01371A'
}
{
'name': 'Astronaut Blue'
'hex': '013E62'
}
{
'name': 'Regal Blue'
'hex': '013F6A'
}
{
'name': 'Aqua Deep'
'hex': '014B43'
}
{
'name': 'Orient'
'hex': '015E85'
}
{
'name': 'Blue Stone'
'hex': '016162'
}
{
'name': 'Fun Green'
'hex': '016D39'
}
{
'name': 'Pine Green'
'hex': '01796F'
}
{
'name': 'Blue Lagoon'
'hex': '017987'
}
{
'name': 'Deep Sea'
'hex': '01826B'
}
{
'name': 'Green Haze'
'hex': '01A368'
}
{
'name': 'English Holly'
'hex': '022D15'
}
{
'name': 'Sherwood Green'
'hex': '02402C'
}
{
'name': 'Congress Blue'
'hex': '02478E'
}
{
'name': 'Evening Sea'
'hex': '024E46'
}
{
'name': 'Bahama Blue'
'hex': '026395'
}
{
'name': 'Observatory'
'hex': '02866F'
}
{
'name': 'Cerulean'
'hex': '02A4D3'
}
{
'name': 'Tangaroa'
'hex': '03163C'
}
{
'name': 'Green V<NAME>ue'
'hex': '032B52'
}
{
'name': '<NAME>'
'hex': '036A6E'
}
{
'name': 'Midnight Mo<NAME>'
'hex': '041004'
}
{
'name': 'Black Pearl'
'hex': '041322'
}
{
'name': 'Blue Whale'
'hex': '042E4C'
}
{
'name': '<NAME>'
'hex': '044022'
}
{
'name': 'Te<NAME> Blue'
'hex': '044259'
}
{
'name': 'Deep C<NAME>'
'hex': '051040'
}
{
'name': '<NAME>'
'hex': '051657'
}
{
'name': '<NAME>'
'hex': '055989'
}
{
'name': '<NAME>'
'hex': '056F57'
}
{
'name': '<NAME>'
'hex': '062A78'
}
{
'name': '<NAME>'
'hex': '063537'
}
{
'name': '<NAME>'
'hex': '069B81'
}
{
'name': '<NAME>'
'hex': '06A189'
}
{
'name': '<NAME>'
'hex': '073A50'
}
{
'name': '<NAME>'
'hex': '080110'
}
{
'name': '<NAME>'
'hex': '081910'
}
{
'name': '<NAME>'
'hex': '082567'
}
{
'name': '<NAME>'
'hex': '088370'
}
{
'name': '<NAME>'
'hex': '08E8DE'
}
{
'name': '<NAME>'
'hex': '092256'
}
{
'name': '<NAME>'
'hex': '09230F'
}
{
'name': '<NAME>'
'hex': '09255D'
}
{
'name': '<NAME>'
'hex': '093624'
}
{
'name': '<NAME>'
'hex': '095859'
}
{
'name': '<NAME>'
'hex': '097F4B'
}
{
'name': '<NAME>'
'hex': '0A001C'
}
{
'name': '<NAME>'
'hex': '0A480D'
}
{
'name': '<NAME>'
'hex': '0A6906'
}
{
'name': '<NAME>'
'hex': '0A6F75'
}
{
'name': '<NAME>'
'hex': '0B0B0B'
}
{
'name': '<NAME>'
'hex': '0B0F08'
}
{
'name': '<NAME>'
'hex': '0B1107'
}
{
'name': '<NAME>'
'hex': '0B1304'
}
{
'name': '<NAME>'
'hex': '0B6207'
}
{
'name': '<NAME>'
'hex': '0BDA51'
}
{
'name': '<NAME>'
'hex': '0C0B1D'
}
{
'name': '<NAME>'
'hex': '0C0D0F'
}
{
'name': '<NAME>'
'hex': '0C1911'
}
{
'name': '<NAME>'
'hex': '0C7A79'
}
{
'name': '<NAME>'
'hex': '0C8990'
}
{
'name': '<NAME>'
'hex': '0D0332'
}
{
'name': '<NAME>'
'hex': '0D1117'
}
{
'name': '<NAME>'
'hex': '0D1C19'
}
{
'name': '<NAME>'
'hex': '0D2E1C'
}
{
'name': '<NAME>'
'hex': '0E0E18'
}
{
'name': '<NAME>'
'hex': '0E2A30'
}
{
'name': '<NAME>'
'hex': '0F2D9E'
}
{
'name': '<NAME>'
'hex': '10121D'
}
{
'name': '<NAME>'
'hex': '101405'
}
{
'name': '<NAME>'
'hex': '105852'
}
{
'name': '<NAME>'
'hex': '110C6C'
}
{
'name': '<NAME>'
'hex': '120A8F'
}
{
'name': '<NAME>'
'hex': '123447'
}
{
'name': '<NAME>'
'hex': '126B40'
}
{
'name': '<NAME>'
'hex': '130000'
}
{
'name': '<NAME>'
'hex': '130A06'
}
{
'name': '<NAME>'
'hex': '13264D'
}
{
'name': '<NAME>'
'hex': '134F19'
}
{
'name': '<NAME>'
'hex': '140600'
}
{
'name': '<NAME>'
'hex': '1450AA'
}
{
'name': '<NAME>'
'hex': '151F4C'
}
{
'name': '<NAME>'
'hex': '1560BD'
}
{
'name': '<NAME>'
'hex': '15736B'
}
{
'name': '<NAME>'
'hex': '161928'
}
{
'name': '<NAME>'
'hex': '161D10'
}
{
'name': '<NAME>'
'hex': '162A40'
}
{
'name': '<NAME>'
'hex': '163222'
}
{
'name': '<NAME>'
'hex': '16322C'
}
{
'name': '<NAME>'
'hex': '163531'
}
{
'name': '<NAME>'
'hex': '171F04'
}
{
'name': '<NAME>'
'hex': '175579'
}
{
'name': '<NAME>'
'hex': '182D09'
}
{
'name': '<NAME>'
'hex': '18587A'
}
{
'name': '<NAME>'
'hex': '19330E'
}
{
'name': '<NAME>'
'hex': '193751'
}
{
'name': '<NAME>'
'hex': '1959A8'
}
{
'name': '<NAME>'
'hex': '1A1A68'
}
{
'name': 'Mountain Meadow'
'hex': '1AB385'
}
{
'name': '<NAME>'
'hex': '1B0245'
}
{
'name': '<NAME>'
'hex': '1B1035'
}
{
'name': '<NAME>'
'hex': '1B127B'
}
{
'name': '<NAME>'
'hex': '1B1404'
}
{
'name': '<NAME>'
'hex': '1B2F11'
}
{
'name': '<NAME>'
'hex': '1B3162'
}
{
'name': '<NAME>'
'hex': '1B659D'
}
{
'name': '<NAME>'
'hex': '1C1208'
}
{
'name': '<NAME>'
'hex': '1C1E13'
}
{
'name': 'Persian <NAME>'
'hex': '1C39BB'
}
{
'name': '<NAME>'
'hex': '1C402E'
}
{
'name': '<NAME>'
'hex': '1C7C7D'
}
{
'name': '<NAME>'
'hex': '1D6142'
}
{
'name': '<NAME>'
'hex': '1E0F04'
}
{
'name': '<NAME>'
'hex': '1E1609'
}
{
'name': '<NAME>'
'hex': '1E1708'
}
{
'name': '<NAME>'
'hex': '1E385B'
}
{
'name': 'Te Papa Green'
'hex': '1E433C'
}
{
'name': 'Dodger Blue'
'hex': '1E90FF'
}
{
'name': 'Eastern Blue'
'hex': '1E9AB0'
}
{
'name': 'Night Rider'
'hex': '1F120F'
}
{
'name': 'Java'
'hex': '1FC2C2'
}
{
'name': '<NAME>'
'hex': '20208D'
}
{
'name': '<NAME>'
'hex': '202E54'
}
{
'name': '<NAME>'
'hex': '204852'
}
{
'name': '<NAME>'
'hex': '211A0E'
}
{
'name': '<NAME>'
'hex': '220878'
}
{
'name': '<NAME>'
'hex': '228B22'
}
{
'name': '<NAME>'
'hex': '233418'
}
{
'name': '<NAME>'
'hex': '240A40'
}
{
'name': '<NAME>'
'hex': '240C02'
}
{
'name': '<NAME>'
'hex': '242A1D'
}
{
'name': '<NAME>'
'hex': '242E16'
}
{
'name': '<NAME>'
'hex': '24500F'
}
{
'name': '<NAME>'
'hex': '251607'
}
{
'name': '<NAME>'
'hex': '251706'
}
{
'name': '<NAME>'
'hex': '251F4F'
}
{
'name': '<NAME>'
'hex': '25272C'
}
{
'name': '<NAME>'
'hex': '25311C'
}
{
'name': '<NAME>'
'hex': '2596D1'
}
{
'name': '<NAME>'
'hex': '260368'
}
{
'name': '<NAME>'
'hex': '26056A'
}
{
'name': '<NAME>'
'hex': '261105'
}
{
'name': '<NAME>'
'hex': '261414'
}
{
'name': '<NAME>'
'hex': '262335'
}
{
'name': '<NAME>'
'hex': '26283B'
}
{
'name': '<NAME>'
'hex': '273A81'
}
{
'name': '<NAME>'
'hex': '27504B'
}
{
'name': '<NAME>'
'hex': '278A5B'
}
{
'name': '<NAME>'
'hex': '281E15'
}
{
'name': '<NAME>'
'hex': '283A77'
}
{
'name': '<NAME>'
'hex': '286ACD'
}
{
'name': '<NAME>'
'hex': '290C5E'
}
{
'name': '<NAME>'
'hex': '292130'
}
{
'name': '<NAME>'
'hex': '292319'
}
{
'name': '<NAME>'
'hex': '292937'
}
{
'name': '<NAME>'
'hex': '297B9A'
}
{
'name': '<NAME>'
'hex': '29AB87'
}
{
'name': '<NAME>'
'hex': '2A0359'
}
{
'name': '<NAME>'
'hex': '2A140E'
}
{
'name': '<NAME>'
'hex': '2A2630'
}
{
'name': '<NAME>'
'hex': '2A380B'
}
{
'name': '<NAME>'
'hex': '2A52BE'
}
{
'name': '<NAME>'
'hex': '2B0202'
}
{
'name': '<NAME>'
'hex': '2B194F'
}
{
'name': 'Heavy Metal'
'hex': '2B3228'
}
{
'name': '<NAME>'
'hex': '2C0E8C'
}
{
'name': '<NAME>'
'hex': '2C1632'
}
{
'name': '<NAME>'
'hex': '2C2133'
}
{
'name': '<NAME>'
'hex': '2C8C84'
}
{
'name': '<NAME>'
'hex': '2D2510'
}
{
'name': '<NAME>'
'hex': '2D383A'
}
{
'name': '<NAME>'
'hex': '2D569B'
}
{
'name': '<NAME>'
'hex': '2E0329'
}
{
'name': '<NAME>'
'hex': '2E1905'
}
{
'name': '<NAME>'
'hex': '2E3222'
}
{
'name': '<NAME>'
'hex': '2E3F62'
}
{
'name': '<NAME>'
'hex': '2E8B57'
}
{
'name': '<NAME>'
'hex': '2EBFD4'
}
{
'name': '<NAME>'
'hex': '2F270E'
}
{
'name': '<NAME>'
'hex': '2F3CB3'
}
{
'name': '<NAME>'
'hex': '2F519E'
}
{
'name': '<NAME>'
'hex': '2F5A57'
}
{
'name': '<NAME>'
'hex': '2F6168'
}
{
'name': '<NAME>'
'hex': '300529'
}
{
'name': '<NAME>'
'hex': '301F1E'
}
{
'name': '<NAME>'
'hex': '302A0F'
}
{
'name': '<NAME>'
'hex': '304B6A'
}
{
'name': '<NAME>'
'hex': '30D5C8'
}
{
'name': '<NAME>'
'hex': '311C17'
}
{
'name': '<NAME>'
'hex': '314459'
}
{
'name': '<NAME>'
'hex': '315BA1'
}
{
'name': '<NAME>'
'hex': '31728D'
}
{
'name': '<NAME>'
'hex': '317D82'
}
{
'name': '<NAME>'
'hex': '32127A'
}
{
'name': '<NAME>'
'hex': '32293A'
}
{
'name': '<NAME>'
'hex': '323232'
}
{
'name': '<NAME>'
'hex': '325D52'
}
{
'name': '<NAME>'
'hex': '327C14'
}
{
'name': '<NAME>'
'hex': '327DA0'
}
{
'name': '<NAME>'
'hex': '33036B'
}
{
'name': '<NAME>'
'hex': '33292F'
}
{
'name': '<NAME>'
'hex': '33CC99'
}
{
'name': '<NAME>'
'hex': '341515'
}
{
'name': '<NAME>'
'hex': '350036'
}
{
'name': '<NAME>'
'hex': '350E42'
}
{
'name': '<NAME>'
'hex': '350E57'
}
{
'name': '<NAME>'
'hex': '353542'
}
{
'name': '<NAME>'
'hex': '354E8C'
}
{
'name': '<NAME>'
'hex': '363050'
}
{
'name': '<NAME>'
'hex': '363534'
}
{
'name': '<NAME>'
'hex': '363C0D'
}
{
'name': '<NAME>'
'hex': '36747D'
}
{
'name': '<NAME>'
'hex': '368716'
}
{
'name': '<NAME>'
'hex': '370202'
}
{
'name': '<NAME>'
'hex': '371D09'
}
{
'name': '<NAME>'
'hex': '37290E'
}
{
'name': '<NAME>'
'hex': '373021'
}
{
'name': '<NAME>'
'hex': '377475'
}
{
'name': '<NAME>'
'hex': '380474'
}
{
'name': '<NAME>'
'hex': '381A51'
}
{
'name': '<NAME>'
'hex': '383533'
}
{
'name': '<NAME>'
'hex': '384555'
}
{
'name': '<NAME>'
'hex': '384910'
}
{
'name': '<NAME>'
'hex': '394851'
}
{
'name': '<NAME>'
'hex': '396413'
}
{
'name': '<NAME>'
'hex': '3A0020'
}
{
'name': '<NAME>'
'hex': '3A2010'
}
{
'name': '<NAME>'
'hex': '3A2A6A'
}
{
'name': '<NAME>'
'hex': '3A686C'
}
{
'name': '<NAME>'
'hex': '3A6A47'
}
{
'name': '<NAME>'
'hex': '3AB09E'
}
{
'name': '<NAME>'
'hex': '3B000B'
}
{
'name': '<NAME>'
'hex': '3B0910'
}
{
'name': '<NAME>'
'hex': '3B1F1F'
}
{
'name': '<NAME>'
'hex': '3B2820'
}
{
'name': '<NAME>'
'hex': '3B7A57'
}
{
'name': '<NAME>'
'hex': '3B91B4'
}
{
'name': '<NAME>'
'hex': '3C0878'
}
{
'name': '<NAME>'
'hex': '3C1206'
}
{
'name': '<NAME>'
'hex': '3C1F76'
}
{
'name': '<NAME>'
'hex': '3C2005'
}
{
'name': '<NAME>'
'hex': '3C3910'
}
{
'name': '<NAME>'
'hex': '3C4151'
}
{
'name': '<NAME>'
'hex': '3C4443'
}
{
'name': '<NAME>'
'hex': '3C493A'
}
{
'name': '<NAME> '
'hex': '3D0C02'
}
{
'name': '<NAME>'
'hex': '3D2B1F'
}
{
'name': '<NAME>'
'hex': '3D7D52'
}
{
'name': '<NAME>'
'hex': '3E0480'
}
{
'name': '<NAME>'
'hex': '3E1C14'
}
{
'name': '<NAME>'
'hex': '3E2B23'
}
{
'name': '<NAME>'
'hex': '3E2C1C'
}
{
'name': '<NAME>'
'hex': '3E3A44'
}
{
'name': '<NAME>'
'hex': '3EABBF'
}
{
'name': '<NAME>'
'hex': '3F2109'
}
{
'name': '<NAME>'
'hex': '3F2500'
}
{
'name': '<NAME>'
'hex': '3F3002'
}
{
'name': '<NAME>'
'hex': '3F307F'
}
{
'name': '<NAME>'
'hex': '3F4C3A'
}
{
'name': '<NAME>'
'hex': '3F583B'
}
{
'name': '<NAME>'
'hex': '3F5D53'
}
{
'name': '<NAME>'
'hex': '3FC1AA'
}
{
'name': '<NAME>'
'hex': '3FFF00'
}
{
'name': '<NAME>'
'hex': '401801'
}
{
'name': '<NAME>'
'hex': '40291D'
}
{
'name': '<NAME>'
'hex': '403B38'
}
{
'name': '<NAME>'
'hex': '403D19'
}
{
'name': '<NAME>'
'hex': '405169'
}
{
'name': '<NAME>'
'hex': '40826D'
}
{
'name': '<NAME>'
'hex': '40A860'
}
{
'name': '<NAME>'
'hex': '410056'
}
{
'name': '<NAME>'
'hex': '411F10'
}
{
'name': '<NAME>'
'hex': '412010'
}
{
'name': '<NAME>'
'hex': '413C37'
}
{
'name': '<NAME>'
'hex': '414257'
}
{
'name': '<NAME>'
'hex': '414C7D'
}
{
'name': '<NAME>'
'hex': '4169E1'
}
{
'name': '<NAME>'
'hex': '41AA78'
}
{
'name': '<NAME>'
'hex': '420303'
}
{
'name': '<NAME>'
'hex': '423921'
}
{
'name': '<NAME>'
'hex': '427977'
}
{
'name': '<NAME>'
'hex': '431560'
}
{
'name': '<NAME>'
'hex': '433120'
}
{
'name': '<NAME>'
'hex': '433E37'
}
{
'name': 'R<NAME>'
'hex': '434C59'
}
{
'name': '<NAME>'
'hex': '436A0D'
}
{
'name': '<NAME>'
'hex': '44012D'
}
{
'name': '<NAME>'
'hex': '441D00'
}
{
'name': '<NAME>'
'hex': '444954'
}
{
'name': '<NAME>'
'hex': '454936'
}
{
'name': '<NAME>'
'hex': '456CAC'
}
{
'name': '<NAME>'
'hex': '45B1E8'
}
{
'name': '<NAME>'
'hex': '460B41'
}
{
'name': '<NAME>'
'hex': '462425'
}
{
'name': '<NAME>'
'hex': '465945'
}
{
'name': '<NAME>'
'hex': '4682B4'
}
{
'name': '<NAME>'
'hex': '480404'
}
{
'name': '<NAME>'
'hex': '480607'
}
{
'name': '<NAME>'
'hex': '480656'
}
{
'name': '<NAME>'
'hex': '481C1C'
}
{
'name': '<NAME>'
'hex': '483131'
}
{
'name': '<NAME>'
'hex': '483C32'
}
{
'name': '<NAME>'
'hex': '49170C'
}
{
'name': '<NAME>'
'hex': '492615'
}
{
'name': '<NAME>'
'hex': '49371B'
}
{
'name': '<NAME>'
'hex': '495400'
}
{
'name': '<NAME>ou<NAME>'
'hex': '496679'
}
{
'name': '<NAME>'
'hex': '497183'
}
{
'name': '<NAME>'
'hex': '4A2A04'
}
{
'name': '<NAME>'
'hex': '4A3004'
}
{
'name': '<NAME>'
'hex': '4A3C30'
}
{
'name': '<NAME>'
'hex': '4A4244'
}
{
'name': '<NAME>'
'hex': '4A444B'
}
{
'name': '<NAME>'
'hex': '4A4E5A'
}
{
'name': '<NAME>'
'hex': '4B0082'
}
{
'name': '<NAME>'
'hex': '4B5D52'
}
{
'name': '<NAME>'
'hex': '4C3024'
}
{
'name': '<NAME>'
'hex': '4C4F56'
}
{
'name': '<NAME>'
'hex': '4D0135'
}
{
'name': '<NAME>'
'hex': '4D0A18'
}
{
'name': '<NAME>'
'hex': '4D1E01'
}
{
'name': '<NAME>'
'hex': '4D282D'
}
{
'name': '<NAME>'
'hex': '4D282E'
}
{
'name': '<NAME>'
'hex': '4D3833'
}
{
'name': '<NAME>'
'hex': '4D3D14'
}
{
'name': '<NAME>'
'hex': '4D400F'
}
{
'name': '<NAME>'
'hex': '4D5328'
}
{
'name': '<NAME>'
'hex': '4E0606'
}
{
'name': '<NAME>'
'hex': '4E2A5A'
}
{
'name': '<NAME>'
'hex': '4E3B41'
}
{
'name': '<NAME>'
'hex': '4E420C'
}
{
'name': '<NAME>'
'hex': '4E4562'
}
{
'name': '<NAME>'
'hex': '4E6649'
}
{
'name': '<NAME>'
'hex': '4E7F9E'
}
{
'name': '<NAME>'
'hex': '4EABD1'
}
{
'name': '<NAME>'
'hex': '4F1C70'
}
{
'name': '<NAME>'
'hex': '4F2398'
}
{
'name': '<NAME>'
'hex': '4F69C6'
}
{
'name': '<NAME>'
'hex': '4F7942'
}
{
'name': '<NAME>'
'hex': '4F9D5D'
}
{
'name': '<NAME>'
'hex': '4FA83D'
}
{
'name': '<NAME>'
'hex': '504351'
}
{
'name': '<NAME>'
'hex': '507096'
}
{
'name': '<NAME>'
'hex': '507672'
}
{
'name': '<NAME>'
'hex': '50C878'
}
{
'name': '<NAME>'
'hex': '514649'
}
{
'name': '<NAME>'
'hex': '516E3D'
}
{
'name': '<NAME>'
'hex': '517C66'
}
{
'name': '<NAME>'
'hex': '51808F'
}
{
'name': '<NAME>'
'hex': '52001F'
}
{
'name': '<NAME>'
'hex': '520C17'
}
{
'name': '<NAME>'
'hex': '523C94'
}
{
'name': '<NAME>'
'hex': '533455'
}
{
'name': '<NAME>'
'hex': '534491'
}
{
'name': '<NAME>'
'hex': '53824B'
}
{
'name': '<NAME>'
'hex': '541012'
}
{
'name': '<NAME>'
'hex': '544333'
}
{
'name': '<NAME>'
'hex': '54534D'
}
{
'name': '<NAME>'
'hex': '549019'
}
{
'name': '<NAME>'
'hex': '55280C'
}
{
'name': '<NAME>'
'hex': '555B10'
}
{
'name': '<NAME>'
'hex': '556D56'
}
{
'name': '<NAME>'
'hex': '5590D9'
}
{
'name': '<NAME>'
'hex': '56B4BE'
}
{
'name': '<NAME>'
'hex': '578363'
}
{
'name': '<NAME>'
'hex': '583401'
}
{
'name': '<NAME>'
'hex': '585562'
}
{
'name': '<NAME>'
'hex': '587156'
}
{
'name': '<NAME>'
'hex': '589AAF'
}
{
'name': '<NAME>'
'hex': '591D35'
}
{
'name': '<NAME>'
'hex': '592804'
}
{
'name': '<NAME>'
'hex': '593737'
}
{
'name': '<NAME>'
'hex': '594433'
}
{
'name': '<NAME>'
'hex': '5A6E9C'
}
{
'name': '<NAME>'
'hex': '5A87A0'
}
{
'name': '<NAME>'
'hex': '5B3013'
}
{
'name': '<NAME>'
'hex': '5C0120'
}
{
'name': '<NAME>'
'hex': '5C0536'
}
{
'name': '<NAME>'
'hex': '5C2E01'
}
{
'name': '<NAME>'
'hex': '5C5D75'
}
{
'name': '<NAME>'
'hex': '5D1E0F'
}
{
'name': '<NAME>'
'hex': '5D4C51'
}
{
'name': '<NAME>'
'hex': '5D5C58'
}
{
'name': '<NAME>'
'hex': '5D5E37'
}
{
'name': '<NAME>'
'hex': '5D7747'
}
{
'name': '<NAME>'
'hex': '5DA19F'
}
{
'name': '<NAME>'
'hex': '5E483E'
}
{
'name': '<NAME>'
'hex': '5E5D3B'
}
{
'name': '<NAME>'
'hex': '5F3D26'
}
{
'name': '<NAME>'
'hex': '5F5F6E'
}
{
'name': '<NAME>'
'hex': '5F6672'
}
{
'name': '<NAME>'
'hex': '5FA777'
}
{
'name': '<NAME>'
'hex': '5FB3AC'
}
{
'name': '<NAME>'
'hex': '604913'
}
{
'name': '<NAME>'
'hex': '605B73'
}
{
'name': '<NAME>'
'hex': '606E68'
}
{
'name': '<NAME>'
'hex': '6093D1'
}
{
'name': '<NAME>'
'hex': '612718'
}
{
'name': '<NAME>'
'hex': '614051'
}
{
'name': '<NAME>'
'hex': '615D30'
}
{
'name': '<NAME>'
'hex': '61845F'
}
{
'name': '<NAME>'
'hex': '622F30'
}
{
'name': '<NAME>'
'hex': '623F2D'
}
{
'name': '<NAME>'
'hex': '624E9A'
}
{
'name': 'West Coast'
'hex': '625119'
}
{
'name': '<NAME>'
'hex': '626649'
}
{
'name': '<NAME>'
'hex': '639A8F'
}
{
'name': '<NAME>'
'hex': '63B76C'
}
{
'name': 'Blue V<NAME>let'
'hex': '6456B7'
}
{
'name': '<NAME>'
'hex': '646077'
}
{
'name': '<NAME>'
'hex': '646463'
}
{
'name': '<NAME>'
'hex': '646A54'
}
{
'name': '<NAME>'
'hex': '646E75'
}
{
'name': '<NAME>'
'hex': '6495ED'
}
{
'name': '<NAME>'
'hex': '64CCDB'
}
{
'name': '<NAME>'
'hex': '65000B'
}
{
'name': '<NAME>'
'hex': '651A14'
}
{
'name': '<NAME>'
'hex': '652DC1'
}
{
'name': '<NAME>'
'hex': '657220'
}
{
'name': '<NAME>'
'hex': '65745D'
}
{
'name': '<NAME>'
'hex': '65869F'
}
{
'name': '<NAME>'
'hex': '660045'
}
{
'name': '<NAME>'
'hex': '660099'
}
{
'name': '<NAME>'
'hex': '66023C'
}
{
'name': '<NAME>'
'hex': '661010'
}
{
'name': '<NAME>'
'hex': '66B58F'
}
{
'name': '<NAME>'
'hex': '66FF00'
}
{
'name': '<NAME>'
'hex': '66FF66'
}
{
'name': '<NAME>'
'hex': '67032D'
}
{
'name': '<NAME>'
'hex': '675FA6'
}
{
'name': '<NAME>'
'hex': '676662'
}
{
'name': '<NAME>'
'hex': '678975'
}
{
'name': '<NAME>'
'hex': '67A712'
}
{
'name': '<NAME>'
'hex': '683600'
}
{
'name': '<NAME>'
'hex': '685558'
}
{
'name': '<NAME>'
'hex': '685E6E'
}
{
'name': '<NAME>'
'hex': '692545'
}
{
'name': '<NAME>'
'hex': '692D54'
}
{
'name': '<NAME>'
'hex': '695F62'
}
{
'name': '<NAME>'
'hex': '697E9A'
}
{
'name': '<NAME>'
'hex': '6A442E'
}
{
'name': '<NAME>'
'hex': '6A5D1B'
}
{
'name': '<NAME>'
'hex': '6A6051'
}
{
'name': '<NAME>'
'hex': '6B2A14'
}
{
'name': '<NAME>'
'hex': '6B3FA0'
}
{
'name': '<NAME>'
'hex': '6B4E31'
}
{
'name': '<NAME>'
'hex': '6B5755'
}
{
'name': '<NAME>'
'hex': '6B8BA2'
}
{
'name': '<NAME>'
'hex': '6B8E23'
}
{
'name': '<NAME>'
'hex': '6C3082'
}
{
'name': '<NAME>'
'hex': '6CDAE7'
}
{
'name': '<NAME>'
'hex': '6D0101'
}
{
'name': '<NAME>'
'hex': '6D5E54'
}
{
'name': '<NAME>'
'hex': '6D6C6C'
}
{
'name': '<NAME>'
'hex': '6D9292'
}
{
'name': '<NAME>'
'hex': '6D92A1'
}
{
'name': '<NAME>'
'hex': '6E0902'
}
{
'name': '<NAME>'
'hex': '6E1D14'
}
{
'name': '<NAME>'
'hex': '6E4826'
}
{
'name': '<NAME>'
'hex': '6E4B26'
}
{
'name': '<NAME>'
'hex': '6E6D57'
}
{
'name': '<NAME>'
'hex': '6E7783'
}
{
'name': '<NAME>'
'hex': '6F440C'
}
{
'name': '<NAME>'
'hex': '6F6A61'
}
{
'name': '<NAME>'
'hex': '6F8E63'
}
{
'name': '<NAME>'
'hex': '6F9D02'
}
{
'name': '<NAME>'
'hex': '6FD0C5'
}
{
'name': '<NAME>'
'hex': '701C1C'
}
{
'name': '<NAME>'
'hex': '704214'
}
{
'name': '<NAME>ronze'
'hex': '704A07'
}
{
'name': '<NAME>'
'hex': '704F50'
}
{
'name': '<NAME>'
'hex': '706555'
}
{
'name': '<NAME>'
'hex': '708090'
}
{
'name': '<NAME>'
'hex': '711A00'
}
{
'name': '<NAME>'
'hex': '71291D'
}
{
'name': '<NAME>'
'hex': '714693'
}
{
'name': '<NAME>'
'hex': '714AB2'
}
{
'name': '<NAME>'
'hex': '715D47'
}
{
'name': '<NAME>'
'hex': '716338'
}
{
'name': '<NAME>'
'hex': '716B56'
}
{
'name': '<NAME>'
'hex': '716E10'
}
{
'name': '<NAME>'
'hex': '717486'
}
{
'name': '<NAME>'
'hex': '718080'
}
{
'name': '<NAME>'
'hex': '71D9E2'
}
{
'name': '<NAME>'
'hex': '72010F'
}
{
'name': '<NAME>'
'hex': '724A2F'
}
{
'name': '<NAME>'
'hex': '726D4E'
}
{
'name': '<NAME>'
'hex': '727B89'
}
{
'name': '<NAME>'
'hex': '731E8F'
}
{
'name': '<NAME>'
'hex': '734A12'
}
{
'name': '<NAME>'
'hex': '736C9F'
}
{
'name': '<NAME>'
'hex': '736D58'
}
{
'name': '<NAME>'
'hex': '737829'
}
{
'name': '<NAME>'
'hex': '738678'
}
{
'name': '<NAME>'
'hex': '74640D'
}
{
'name': '<NAME>'
'hex': '747D63'
}
{
'name': '<NAME>'
'hex': '747D83'
}
{
'name': '<NAME>'
'hex': '748881'
}
{
'name': '<NAME>'
'hex': '749378'
}
{
'name': '<NAME>'
'hex': '74C365'
}
{
'name': '<NAME>'
'hex': '755A57'
}
{
'name': '<NAME>'
'hex': '7563A8'
}
{
'name': '<NAME>'
'hex': '76395D'
}
{
'name': '<NAME>'
'hex': '7666C6'
}
{
'name': '<NAME>'
'hex': '76BD17'
}
{
'name': '<NAME>'
'hex': '76D7EA'
}
{
'name': '<NAME>'
'hex': '770F05'
}
{
'name': '<NAME>'
'hex': '771F1F'
}
{
'name': '<NAME>'
'hex': '773F1A'
}
{
'name': '<NAME>'
'hex': '776F61'
}
{
'name': '<NAME>'
'hex': '778120'
}
{
'name': '<NAME>'
'hex': '779E86'
}
{
'name': '<NAME>'
'hex': '77DD77'
}
{
'name': '<NAME>'
'hex': '780109'
}
{
'name': '<NAME>'
'hex': '782D19'
}
{
'name': '<NAME>'
'hex': '782F16'
}
{
'name': '<NAME>'
'hex': '78866B'
}
{
'name': '<NAME>'
'hex': '788A25'
}
{
'name': '<NAME>'
'hex': '788BBA'
}
{
'name': '<NAME>'
'hex': '78A39C'
}
{
'name': '<NAME>'
'hex': '795D4C'
}
{
'name': '<NAME>'
'hex': '796878'
}
{
'name': '<NAME>'
'hex': '796989'
}
{
'name': '<NAME>'
'hex': '796A78'
}
{
'name': '<NAME>'
'hex': '796D62'
}
{
'name': '<NAME>'
'hex': '79DEEC'
}
{
'name': '<NAME>'
'hex': '7A013A'
}
{
'name': '<NAME>'
'hex': '7A58C1'
}
{
'name': '<NAME>'
'hex': '7A7A7A'
}
{
'name': '<NAME>ild Blue <NAME>'
'hex': '7A89B8'
}
{
'name': '<NAME>'
'hex': '7AC488'
}
{
'name': '<NAME>'
'hex': '7B3801'
}
{
'name': '<NAME>'
'hex': '7B3F00'
}
{
'name': '<NAME>'
'hex': '7B6608'
}
{
'name': '<NAME>'
'hex': '7B7874'
}
{
'name': '<NAME> '
'hex': '7B7C94'
}
{
'name': '<NAME>'
'hex': '7B8265'
}
{
'name': '<NAME>'
'hex': '7B9F80'
}
{
'name': '<NAME>'
'hex': '7BA05B'
}
{
'name': '<NAME>'
'hex': '7C1C05'
}
{
'name': '<NAME>'
'hex': '7C7631'
}
{
'name': '<NAME>'
'hex': '7C778A'
}
{
'name': '<NAME>'
'hex': '7C7B7A'
}
{
'name': '<NAME>'
'hex': '7C7B82'
}
{
'name': '<NAME>'
'hex': '7C881A'
}
{
'name': '<NAME>'
'hex': '7CA1A6'
}
{
'name': '<NAME>'
'hex': '7CB0A1'
}
{
'name': '<NAME>'
'hex': '7CB7BB'
}
{
'name': '<NAME>'
'hex': '7D2C14'
}
{
'name': '<NAME>'
'hex': '7DA98D'
}
{
'name': '<NAME>'
'hex': '7DC8F7'
}
{
'name': '<NAME>'
'hex': '7DD8C6'
}
{
'name': '<NAME>'
'hex': '7E3A15'
}
{
'name': '<NAME>'
'hex': '7F1734'
}
{
'name': '<NAME>'
'hex': '7F3A02'
}
{
'name': '<NAME>'
'hex': '7F626D'
}
{
'name': '<NAME>'
'hex': '7F7589'
}
{
'name': '<NAME>'
'hex': '7F76D3'
}
{
'name': '<NAME>'
'hex': '7FFF00'
}
{
'name': '<NAME>'
'hex': '7FFFD4'
}
{
'name': '<NAME>'
'hex': '800000'
}
{
'name': '<NAME>'
'hex': '800B47'
}
{
'name': '<NAME>'
'hex': '801818'
}
{
'name': '<NAME>'
'hex': '80341F'
}
{
'name': '<NAME>'
'hex': '803790'
}
{
'name': '<NAME>'
'hex': '80461B'
}
{
'name': '<NAME>'
'hex': '807E79'
}
{
'name': '<NAME>'
'hex': '808000'
}
{
'name': '<NAME>'
'hex': '808080'
}
{
'name': '<NAME>'
'hex': '80B3AE'
}
{
'name': '<NAME>'
'hex': '80B3C4'
}
{
'name': '<NAME>'
'hex': '80CCEA'
}
{
'name': 'N<NAME>'
'hex': '81422C'
}
{
'name': '<NAME>'
'hex': '816E71'
}
{
'name': '<NAME>'
'hex': '817377'
}
{
'name': '<NAME>'
'hex': '819885'
}
{
'name': '<NAME>'
'hex': '826F65'
}
{
'name': '<NAME>'
'hex': '828685'
}
{
'name': '<NAME>'
'hex': '828F72'
}
{
'name': '<NAME>'
'hex': '831923'
}
{
'name': '<NAME>'
'hex': '837050'
}
{
'name': '<NAME>'
'hex': '83AA5D'
}
{
'name': '<NAME>'
'hex': '83D0C6'
}
{
'name': '<NAME>'
'hex': '843179'
}
{
'name': '<NAME>'
'hex': '84A0A0'
}
{
'name': '<NAME>'
'hex': '8581D9'
}
{
'name': '<NAME>'
'hex': '858470'
}
{
'name': '<NAME>'
'hex': '859FAF'
}
{
'name': '<NAME>'
'hex': '85C4CC'
}
{
'name': '<NAME>'
'hex': '860111'
}
{
'name': '<NAME>'
'hex': '863C3C'
}
{
'name': '<NAME>'
'hex': '86483C'
}
{
'name': '<NAME>'
'hex': '864D1E'
}
{
'name': '<NAME>'
'hex': '86560A'
}
{
'name': '<NAME>'
'hex': '868974'
}
{
'name': '<NAME>'
'hex': '86949F'
}
{
'name': '<NAME>'
'hex': '871550'
}
{
'name': '<NAME>'
'hex': '87756E'
}
{
'name': '<NAME>'
'hex': '877C7B'
}
{
'name': '<NAME>'
'hex': '878D91'
}
{
'name': '<NAME>'
'hex': '87AB39'
}
{
'name': '<NAME>'
'hex': '885342'
}
{
'name': '<NAME>'
'hex': '886221'
}
{
'name': '<NAME>'
'hex': '888387'
}
{
'name': '<NAME>'
'hex': '888D65'
}
{
'name': '<NAME>'
'hex': '893456'
}
{
'name': '<NAME>'
'hex': '893843'
}
{
'name': '<NAME>'
'hex': '894367'
}
{
'name': '<NAME>'
'hex': '897D6D'
}
{
'name': '<NAME>'
'hex': '8A3324'
}
{
'name': '<NAME>'
'hex': '8A73D6'
}
{
'name': '<NAME>'
'hex': '8A8360'
}
{
'name': '<NAME>'
'hex': '8A8389'
}
{
'name': '<NAME>'
'hex': '8A8F8A'
}
{
'name': '<NAME>'
'hex': '8AB9F1'
}
{
'name': '<NAME>'
'hex': '8B00FF'
}
{
'name': '<NAME>'
'hex': '8B0723'
}
{
'name': '<NAME>'
'hex': '8B6B0B'
}
{
'name': '<NAME>'
'hex': '8B8470'
}
{
'name': '<NAME>'
'hex': '8B847E'
}
{
'name': '<NAME>'
'hex': '8B8680'
}
{
'name': '<NAME>'
'hex': '8B9C90'
}
{
'name': '<NAME>'
'hex': '8B9FEE'
}
{
'name': '<NAME>'
'hex': '8BA690'
}
{
'name': '<NAME>'
'hex': '8BA9A5'
}
{
'name': '<NAME>'
'hex': '8BE6D8'
}
{
'name': '<NAME>'
'hex': '8C055E'
}
{
'name': '<NAME>'
'hex': '8C472F'
}
{
'name': '<NAME>'
'hex': '8C5738'
}
{
'name': '<NAME>'
'hex': '8C6495'
}
{
'name': '<NAME>'
'hex': '8D0226'
}
{
'name': '<NAME>'
'hex': '8D3D38'
}
{
'name': '<NAME>'
'hex': '8D3F3F'
}
{
'name': '<NAME>'
'hex': '8D7662'
}
{
'name': '<NAME>'
'hex': '8D8974'
}
{
'name': '<NAME>'
'hex': '8D90A1'
}
{
'name': '<NAME>'
'hex': '8DA8CC'
}
{
'name': '<NAME>'
'hex': '8E0000'
}
{
'name': '<NAME>'
'hex': '8E4D1E'
}
{
'name': '<NAME>'
'hex': '8E6F70'
}
{
'name': '<NAME>'
'hex': '8E775E'
}
{
'name': '<NAME>'
'hex': '8E8190'
}
{
'name': '<NAME>'
'hex': '8EABC1'
}
{
'name': '<NAME>'
'hex': '8F021C'
}
{
'name': '<NAME>'
'hex': '8F3E33'
}
{
'name': '<NAME>'
'hex': '8F4B0E'
}
{
'name': '<NAME>'
'hex': '8F8176'
}
{
'name': '<NAME>'
'hex': '8FD6B4'
}
{
'name': '<NAME>'
'hex': '900020'
}
{
'name': '<NAME>'
'hex': '901E1E'
}
{
'name': '<NAME>'
'hex': '907874'
}
{
'name': '<NAME>'
'hex': '907B71'
}
{
'name': '<NAME>'
'hex': '908D39'
}
{
'name': '<NAME>'
'hex': '92000A'
}
{
'name': '<NAME>'
'hex': '924321'
}
{
'name': '<NAME>'
'hex': '926F5B'
}
{
'name': '<NAME>'
'hex': '928573'
}
{
'name': '<NAME>'
'hex': '928590'
}
{
'name': '<NAME>'
'hex': '9370DB'
}
{
'name': '<NAME>'
'hex': '93CCEA'
}
{
'name': '<NAME>'
'hex': '93DFB8'
}
{
'name': '<NAME>'
'hex': '944747'
}
{
'name': '<NAME>'
'hex': '948771'
}
{
'name': '<NAME>'
'hex': '950015'
}
{
'name': '<NAME>'
'hex': '956387'
}
{
'name': '<NAME>'
'hex': '959396'
}
{
'name': '<NAME>'
'hex': '960018'
}
{
'name': '<NAME>'
'hex': '964B00'
}
{
'name': '<NAME>'
'hex': '967059'
}
{
'name': '<NAME>\'<NAME>'
'hex': '9678B6'
}
{
'name': '<NAME>'
'hex': '967BB6'
}
{
'name': '<NAME>'
'hex': '96A8A1'
}
{
'name': '<NAME>'
'hex': '96BBAB'
}
{
'name': '<NAME>'
'hex': '97605D'
}
{
'name': '<NAME>'
'hex': '9771B5'
}
{
'name': '<NAME>'
'hex': '97CD2D'
}
{
'name': '<NAME>'
'hex': '983D61'
}
{
'name': '<NAME>'
'hex': '9874D3'
}
{
'name': '<NAME>'
'hex': '98777B'
}
{
'name': '<NAME>'
'hex': '98811B'
}
{
'name': '<NAME>'
'hex': '988D77'
}
{
'name': '<NAME>'
'hex': '98FF98'
}
{
'name': '<NAME>'
'hex': '990066'
}
{
'name': '<NAME>'
'hex': '991199'
}
{
'name': '<NAME>'
'hex': '991613'
}
{
'name': '<NAME>'
'hex': '991B07'
}
{
'name': '<NAME>'
'hex': '996666'
}
{
'name': '<NAME>'
'hex': '9966CC'
}
{
'name': '<NAME>'
'hex': '997A8D'
}
{
'name': '<NAME>'
'hex': '9999CC'
}
{
'name': '<NAME>'
'hex': '9A3820'
}
{
'name': '<NAME>'
'hex': '9A6E61'
}
{
'name': '<NAME>'
'hex': '9A9577'
}
{
'name': '<NAME>'
'hex': '9AB973'
}
{
'name': '<NAME>'
'hex': '9AC2B8'
}
{
'name': '<NAME>'
'hex': '9B4703'
}
{
'name': '<NAME>'
'hex': '9B9E8F'
}
{
'name': '<NAME>'
'hex': '9C3336'
}
{
'name': '<NAME>'
'hex': '9D5616'
}
{
'name': '<NAME>'
'hex': '9DACB7'
}
{
'name': '<NAME>'
'hex': '9DC209'
}
{
'name': '<NAME>'
'hex': '9DE093'
}
{
'name': '<NAME>'
'hex': '9DE5FF'
}
{
'name': '<NAME>'
'hex': '9E5302'
}
{
'name': '<NAME>'
'hex': '9E5B40'
}
{
'name': '<NAME>'
'hex': '9EA587'
}
{
'name': '<NAME>'
'hex': '9EA91F'
}
{
'name': '<NAME>'
'hex': '9EB1CD'
}
{
'name': '<NAME>'
'hex': '9EDEE0'
}
{
'name': '<NAME>'
'hex': '9F381D'
}
{
'name': '<NAME>'
'hex': '9F821C'
}
{
'name': '<NAME>'
'hex': '9F9F9C'
}
{
'name': '<NAME>'
'hex': '9FA0B1'
}
{
'name': '<NAME>'
'hex': '9FD7D3'
}
{
'name': '<NAME>'
'hex': '9FDD8C'
}
{
'name': '<NAME>'
'hex': 'A02712'
}
{
'name': 'B<NAME>'
'hex': 'A1750D'
}
{
'name': 'Hit <NAME>'
'hex': 'A1ADB5'
}
{
'name': '<NAME>'
'hex': 'A1C50A'
}
{
'name': 'A<NAME> Island'
'hex': 'A1DAD7'
}
{
'name': 'Water <NAME>'
'hex': 'A1E9DE'
}
{
'name': '<NAME>'
'hex': 'A2006D'
}
{
'name': '<NAME>'
'hex': 'A23B6C'
}
{
'name': '<NAME>'
'hex': 'A26645'
}
{
'name': '<NAME>'
'hex': 'A2AAB3'
}
{
'name': '<NAME>'
'hex': 'A2AEAB'
}
{
'name': '<NAME>'
'hex': 'A3807B'
}
{
'name': 'Amethyst <NAME>moke'
'hex': 'A397B4'
}
{
'name': '<NAME>'
'hex': 'A3E3ED'
}
{
'name': '<NAME>'
'hex': 'A4A49D'
}
{
'name': '<NAME>'
'hex': 'A4A6D3'
}
{
'name': '<NAME>'
'hex': 'A4AF6E'
}
{
'name': '<NAME>'
'hex': 'A50B5E'
}
{
'name': '<NAME>'
'hex': 'A59B91'
}
{
'name': '<NAME>'
'hex': 'A5CB0C'
}
{
'name': '<NAME>'
'hex': 'A62F20'
}
{
'name': '<NAME>'
'hex': 'A65529'
}
{
'name': '<NAME>'
'hex': 'A68B5B'
}
{
'name': '<NAME>'
'hex': 'A69279'
}
{
'name': '<NAME>'
'hex': 'A6A29A'
}
{
'name': '<NAME>'
'hex': 'A72525'
}
{
'name': '<NAME>'
'hex': 'A7882C'
}
{
'name': '<NAME>'
'hex': 'A85307'
}
{
'name': '<NAME>'
'hex': 'A86515'
}
{
'name': '<NAME>'
'hex': 'A86B6B'
}
{
'name': '<NAME>'
'hex': 'A8989B'
}
{
'name': '<NAME>'
'hex': 'A899E6'
}
{
'name': '<NAME>'
'hex': 'A8A589'
}
{
'name': '<NAME>'
'hex': 'A8AE9C'
}
{
'name': '<NAME>'
'hex': 'A8AF8E'
}
{
'name': '<NAME>'
'hex': 'A8BD9F'
}
{
'name': '<NAME>'
'hex': 'A8E3BD'
}
{
'name': '<NAME>'
'hex': 'A9A491'
}
{
'name': '<NAME>'
'hex': 'A9ACB6'
}
{
'name': '<NAME>'
'hex': 'A9B2C3'
}
{
'name': '<NAME>'
'hex': 'A9B497'
}
{
'name': '<NAME>'
'hex': 'A9BDBF'
}
{
'name': '<NAME>'
'hex': 'A9BEF2'
}
{
'name': 'Opal'
'hex': 'A9C6C2'
}
{
'name': 'Night Sh<NAME>'
'hex': 'AA375A'
}
{
'name': 'Fire'
'hex': 'AA4203'
}
{
'name': '<NAME>'
'hex': 'AA8B5B'
}
{
'name': 'Sandal'
'hex': 'AA8D6F'
}
{
'name': 'Shady Lady'
'hex': 'AAA5A9'
}
{
'name': '<NAME>'
'hex': 'AAA9CD'
}
{
'name': '<NAME>'
'hex': 'AAABB7'
}
{
'name': '<NAME> St Blue'
'hex': 'AAD6E6'
}
{
'name': '<NAME>'
'hex': 'AAF0D1'
}
{
'name': '<NAME>'
'hex': 'AB0563'
}
{
'name': '<NAME>'
'hex': 'AB3472'
}
{
'name': '<NAME>'
'hex': 'AB917A'
}
{
'name': '<NAME>'
'hex': 'ABA0D9'
}
{
'name': '<NAME>'
'hex': 'ABA196'
}
{
'name': '<NAME>'
'hex': 'AC8A56'
}
{
'name': 'East <NAME>'
'hex': 'AC91CE'
}
{
'name': '<NAME>'
'hex': 'AC9E22'
}
{
'name': '<NAME>'
'hex': 'ACA494'
}
{
'name': '<NAME>'
'hex': 'ACA586'
}
{
'name': '<NAME>'
'hex': 'ACA59F'
}
{
'name': '<NAME>'
'hex': 'ACACAC'
}
{
'name': '<NAME>'
'hex': 'ACB78E'
}
{
'name': '<NAME>'
'hex': 'ACCBB1'
}
{
'name': '<NAME>'
'hex': 'ACDD4D'
}
{
'name': '<NAME>'
'hex': 'ACE1AF'
}
{
'name': '<NAME>'
'hex': 'AD781B'
}
{
'name': '<NAME>'
'hex': 'ADBED1'
}
{
'name': '<NAME>'
'hex': 'ADDFAD'
}
{
'name': '<NAME>'
'hex': 'ADE6C4'
}
{
'name': '<NAME>'
'hex': 'ADFF2F'
}
{
'name': '<NAME>'
'hex': 'AE4560'
}
{
'name': '<NAME>'
'hex': 'AE6020'
}
{
'name': '<NAME>'
'hex': 'AE809E'
}
{
'name': '<NAME>'
'hex': 'AF4035'
}
{
'name': '<NAME>'
'hex': 'AF4D43'
}
{
'name': '<NAME>'
'hex': 'AF593E'
}
{
'name': '<NAME>'
'hex': 'AF8751'
}
{
'name': '<NAME>'
'hex': 'AF8F2C'
}
{
'name': '<NAME>'
'hex': 'AF9F1C'
}
{
'name': '<NAME>'
'hex': 'AFA09E'
}
{
'name': '<NAME>'
'hex': 'AFB1B8'
}
{
'name': '<NAME>'
'hex': 'AFBDD9'
}
{
'name': '<NAME>'
'hex': 'B04C6A'
}
{
'name': '<NAME>'
'hex': 'B05D54'
}
{
'name': '<NAME>'
'hex': 'B05E81'
}
{
'name': '<NAME>'
'hex': 'B06608'
}
{
'name': '<NAME>'
'hex': 'B09A95'
}
{
'name': '<NAME>'
'hex': 'B0E0E6'
}
{
'name': '<NAME>'
'hex': 'B0E313'
}
{
'name': '<NAME>'
'hex': 'B10000'
}
{
'name': '<NAME>'
'hex': 'B14A0B'
}
{
'name': '<NAME>'
'hex': 'B1610B'
}
{
'name': '<NAME>'
'hex': 'B16D52'
}
{
'name': '<NAME>'
'hex': 'B19461'
}
{
'name': '<NAME>'
'hex': 'B1E2C1'
}
{
'name': '<NAME>'
'hex': 'B1F4E7'
}
{
'name': '<NAME>'
'hex': 'B20931'
}
{
'name': '<NAME>'
'hex': 'B2A1EA'
}
{
'name': '<NAME>'
'hex': 'B32D29'
}
{
'name': '<NAME>'
'hex': 'B35213'
}
{
'name': '<NAME>'
'hex': 'B38007'
}
{
'name': '<NAME>'
'hex': 'B3AF95'
}
{
'name': '<NAME>'
'hex': 'B3C110'
}
{
'name': '<NAME>'
'hex': 'B43332'
}
{
'name': '<NAME>'
'hex': 'B44668'
}
{
'name': '<NAME>'
'hex': 'B4CFD3'
}
{
'name': '<NAME>'
'hex': 'B57281'
}
{
'name': '<NAME>'
'hex': 'B57EDC'
}
{
'name': '<NAME>'
'hex': 'B5A27F'
}
{
'name': '<NAME>'
'hex': 'B5B35C'
}
{
'name': '<NAME>'
'hex': 'B5D2CE'
}
{
'name': '<NAME>'
'hex': 'B5ECDF'
}
{
'name': '<NAME>'
'hex': 'B6316C'
}
{
'name': '<NAME>'
'hex': 'B69D98'
}
{
'name': '<NAME>'
'hex': 'B6B095'
}
{
'name': '<NAME>'
'hex': 'B6BAA4'
}
{
'name': '<NAME>'
'hex': 'B6D1EA'
}
{
'name': '<NAME>'
'hex': 'B6D3BF'
}
{
'name': '<NAME>'
'hex': 'B7410E'
}
{
'name': '<NAME>'
'hex': 'B78E5C'
}
{
'name': '<NAME>'
'hex': 'B7A214'
}
{
'name': '<NAME>'
'hex': 'B7A458'
}
{
'name': '<NAME>'
'hex': 'B7B1B1'
}
{
'name': '<NAME>'
'hex': 'B7C3D0'
}
{
'name': '<NAME>'
'hex': 'B7F0BE'
}
{
'name': '<NAME>'
'hex': 'B81104'
}
{
'name': '<NAME>'
'hex': 'B87333'
}
{
'name': '<NAME>'
'hex': 'B8B56A'
}
{
'name': '<NAME>'
'hex': 'B8C1B1'
}
{
'name': '<NAME>'
'hex': 'B8C25D'
}
{
'name': '<NAME>'
'hex': 'B8E0F9'
}
{
'name': '<NAME>'
'hex': 'B94E48'
}
{
'name': '<NAME>'
'hex': 'B95140'
}
{
'name': '<NAME>'
'hex': 'B98D28'
}
{
'name': '<NAME>'
'hex': 'B9C46A'
}
{
'name': '<NAME>'
'hex': 'B9C8AC'
}
{
'name': '<NAME>'
'hex': 'BA0101'
}
{
'name': '<NAME>'
'hex': 'BA450C'
}
{
'name': '<NAME>'
'hex': 'BA6F1E'
}
{
'name': '<NAME>'
'hex': 'BA7F03'
}
{
'name': '<NAME>'
'hex': 'BAB1A2'
}
{
'name': '<NAME>'
'hex': 'BAC7C9'
}
{
'name': '<NAME>'
'hex': 'BAEEF9'
}
{
'name': '<NAME>'
'hex': 'BB3385'
}
{
'name': '<NAME>'
'hex': 'BB8983'
}
{
'name': '<NAME>'
'hex': 'BBD009'
}
{
'name': '<NAME>'
'hex': 'BBD7C1'
}
{
'name': '<NAME>'
'hex': 'BCC9C2'
}
{
'name': '<NAME>'
'hex': 'BD5E2E'
}
{
'name': '<NAME>'
'hex': 'BD978E'
}
{
'name': '<NAME>'
'hex': 'BDB1A8'
}
{
'name': '<NAME>'
'hex': 'BDB2A1'
}
{
'name': '<NAME>'
'hex': 'BDB3C7'
}
{
'name': '<NAME>'
'hex': 'BDBBD7'
}
{
'name': '<NAME>'
'hex': 'BDBDC6'
}
{
'name': '<NAME>'
'hex': 'BDC8B3'
}
{
'name': '<NAME>'
'hex': 'BDC9CE'
}
{
'name': '<NAME>'
'hex': 'BDEDFD'
}
{
'name': '<NAME>'
'hex': 'BEA6C3'
}
{
'name': '<NAME>'
'hex': 'BEB5B7'
}
{
'name': '<NAME>'
'hex': 'BEDE0D'
}
{
'name': '<NAME>'
'hex': 'BF5500'
}
{
'name': '<NAME>'
'hex': 'BFB8B0'
}
{
'name': '<NAME>'
'hex': 'BFBED8'
}
{
'name': '<NAME>'
'hex': 'BFC1C2'
}
{
'name': '<NAME>'
'hex': 'BFC921'
}
{
'name': '<NAME>'
'hex': 'BFDBE2'
}
{
'name': '<NAME>'
'hex': 'BFFF00'
}
{
'name': '<NAME>'
'hex': 'C02B18'
}
{
'name': '<NAME>'
'hex': 'C04737'
}
{
'name': '<NAME>'
'hex': 'C08081'
}
{
'name': '<NAME>'
'hex': 'C0C0C0'
}
{
'name': '<NAME>'
'hex': 'C0D3B9'
}
{
'name': '<NAME>'
'hex': 'C0D8B6'
}
{
'name': '<NAME>'
'hex': 'C1440E'
}
{
'name': '<NAME>'
'hex': 'C154C1'
}
{
'name': '<NAME>'
'hex': 'C1A004'
}
{
'name': '<NAME>'
'hex': 'C1B7A4'
}
{
'name': '<NAME>'
'hex': 'C1BAB0'
}
{
'name': '<NAME>'
'hex': 'C1BECD'
}
{
'name': '<NAME>'
'hex': 'C1D7B0'
}
{
'name': '<NAME>'
'hex': 'C1F07C'
}
{
'name': '<NAME>'
'hex': 'C26B03'
}
{
'name': '<NAME>'
'hex': 'C2955D'
}
{
'name': '<NAME>'
'hex': 'C2BDB6'
}
{
'name': '<NAME>'
'hex': 'C2CAC4'
}
{
'name': '<NAME>'
'hex': 'C2E8E5'
}
{
'name': '<NAME>'
'hex': 'C32148'
}
{
'name': '<NAME>'
'hex': 'C3B091'
}
{
'name': '<NAME>'
'hex': 'C3BFC1'
}
{
'name': '<NAME>'
'hex': 'C3C3BD'
}
{
'name': '<NAME>'
'hex': 'C3CDE6'
}
{
'name': '<NAME>'
'hex': 'C3D1D1'
}
{
'name': '<NAME>'
'hex': 'C3DDF9'
}
{
'name': '<NAME>'
'hex': 'C41E3A'
}
{
'name': '<NAME>'
'hex': 'C45655'
}
{
'name': '<NAME>'
'hex': 'C45719'
}
{
'name': '<NAME>'
'hex': 'C4C4BC'
}
{
'name': '<NAME>'
'hex': 'C4D0B0'
}
{
'name': '<NAME>'
'hex': 'C4F4EB'
}
{
'name': '<NAME>'
'hex': 'C54B8C'
}
{
'name': '<NAME>'
'hex': 'C59922'
}
{
'name': '<NAME>'
'hex': 'C5994B'
}
{
'name': '<NAME>'
'hex': 'C5DBCA'
}
{
'name': 'Yellow Green'
'hex': 'C5E17A'
}
{
'name': 'Brick Red'
'hex': 'C62D42'
}
{
'name': '<NAME>'
'hex': 'C6726B'
}
{
'name': '<NAME>'
'hex': 'C69191'
}
{
'name': '<NAME>'
'hex': 'C6A84B'
}
{
'name': '<NAME>'
'hex': 'C6C3B5'
}
{
'name': '<NAME>'
'hex': 'C6C8BD'
}
{
'name': '<NAME>'
'hex': 'C6E610'
}
{
'name': '<NAME>'
'hex': 'C7031E'
}
{
'name': '<NAME>'
'hex': 'C71585'
}
{
'name': '<NAME>'
'hex': 'C7BCA2'
}
{
'name': '<NAME>'
'hex': 'C7C1FF'
}
{
'name': '<NAME>'
'hex': 'C7C4BF'
}
{
'name': '<NAME>'
'hex': 'C7C9D5'
}
{
'name': '<NAME>'
'hex': 'C7CD90'
}
{
'name': '<NAME>'
'hex': 'C7DDE5'
}
{
'name': '<NAME>'
'hex': 'C88A65'
}
{
'name': '<NAME>'
'hex': 'C8A2C8'
}
{
'name': '<NAME>'
'hex': 'C8A528'
}
{
'name': '<NAME>'
'hex': 'C8AABF'
}
{
'name': '<NAME>'
'hex': 'C8B568'
}
{
'name': '<NAME>'
'hex': 'C8E3D7'
}
{
'name': '<NAME>'
'hex': 'C96323'
}
{
'name': '<NAME>'
'hex': 'C99415'
}
{
'name': '<NAME>'
'hex': 'C9A0DC'
}
{
'name': '<NAME>'
'hex': 'C9B29B'
}
{
'name': '<NAME>'
'hex': 'C9B35B'
}
{
'name': '<NAME>'
'hex': 'C9B93B'
}
{
'name': '<NAME>'
'hex': 'C9C0BB'
}
{
'name': '<NAME>'
'hex': 'C9D9D2'
}
{
'name': '<NAME>'
'hex': 'C9FFA2'
}
{
'name': '<NAME>'
'hex': 'C9FFE5'
}
{
'name': '<NAME>'
'hex': 'CA3435'
}
{
'name': '<NAME>'
'hex': 'CABB48'
}
{
'name': '<NAME>'
'hex': 'CADCD4'
}
{
'name': '<NAME>'
'hex': 'CAE00D'
}
{
'name': '<NAME>'
'hex': 'CAE6DA'
}
{
'name': '<NAME>'
'hex': 'CB8FA9'
}
{
'name': '<NAME>'
'hex': 'CBCAB6'
}
{
'name': '<NAME>'
'hex': 'CBD3B0'
}
{
'name': '<NAME>'
'hex': 'CBDBD6'
}
{
'name': '<NAME>'
'hex': 'CC3333'
}
{
'name': '<NAME>'
'hex': 'CC5500'
}
{
'name': '<NAME>'
'hex': 'CC7722'
}
{
'name': '<NAME>'
'hex': 'CC8899'
}
{
'name': '<NAME>'
'hex': 'CCCAA8'
}
{
'name': '<NAME>'
'hex': 'CCCCFF'
}
{
'name': '<NAME>'
'hex': 'CCFF00'
}
{
'name': '<NAME>'
'hex': 'CD5700'
}
{
'name': '<NAME>'
'hex': 'CD5C5C'
}
{
'name': '<NAME>'
'hex': 'CD8429'
}
{
'name': '<NAME>'
'hex': 'CDF4FF'
}
{
'name': '<NAME>'
'hex': 'CEB98F'
}
{
'name': '<NAME>'
'hex': 'CEBABA'
}
{
'name': '<NAME>'
'hex': 'CEC291'
}
{
'name': '<NAME>'
'hex': 'CEC7A7'
}
{
'name': '<NAME>'
'hex': 'CFA39D'
}
{
'name': '<NAME>'
'hex': 'CFB53B'
}
{
'name': '<NAME>'
'hex': 'CFDCCF'
}
{
'name': '<NAME>'
'hex': 'CFE5D2'
}
{
'name': '<NAME>'
'hex': 'CFF9F3'
}
{
'name': '<NAME>'
'hex': 'CFFAF4'
}
{
'name': '<NAME>'
'hex': 'D05F04'
}
{
'name': '<NAME>'
'hex': 'D06DA1'
}
{
'name': '<NAME>'
'hex': 'D07D12'
}
{
'name': '<NAME>'
'hex': 'D0BEF8'
}
{
'name': '<NAME>'
'hex': 'D0C0E5'
}
{
'name': '<NAME>'
'hex': 'D0F0C0'
}
{
'name': '<NAME>'
'hex': 'D18F1B'
}
{
'name': '<NAME>'
'hex': 'D1BEA8'
}
{
'name': '<NAME>'
'hex': 'D1C6B4'
}
{
'name': '<NAME>'
'hex': 'D1D2CA'
}
{
'name': '<NAME>'
'hex': 'D1D2DD'
}
{
'name': '<NAME>'
'hex': 'D1E231'
}
{
'name': '<NAME>'
'hex': 'D2691E'
}
{
'name': '<NAME>'
'hex': 'D27D46'
}
{
'name': '<NAME>'
'hex': 'D29EAA'
}
{
'name': '<NAME>'
'hex': 'D2B48C'
}
{
'name': '<NAME>'
'hex': 'D2DA97'
}
{
'name': '<NAME>'
'hex': 'D2F6DE'
}
{
'name': '<NAME>'
'hex': 'D2F8B0'
}
{
'name': '<NAME>'
'hex': 'D3CBBA'
}
{
'name': '<NAME>'
'hex': 'D3CDC5'
}
{
'name': '<NAME>'
'hex': 'D47494'
}
{
'name': '<NAME>'
'hex': 'D4B6AF'
}
{
'name': '<NAME>'
'hex': 'D4BF8D'
}
{
'name': '<NAME>'
'hex': 'D4C4A8'
}
{
'name': '<NAME>'
'hex': 'D4CD16'
}
{
'name': '<NAME>'
'hex': 'D4D7D9'
}
{
'name': '<NAME>'
'hex': 'D4DFE2'
}
{
'name': '<NAME>'
'hex': 'D4E2FC'
}
{
'name': '<NAME>'
'hex': 'D54600'
}
{
'name': '<NAME>'
'hex': 'D591A4'
}
{
'name': '<NAME>'
'hex': 'D59A6F'
}
{
'name': '<NAME>'
'hex': 'D5D195'
}
{
'name': '<NAME>'
'hex': 'D5F6E3'
}
{
'name': '<NAME>'
'hex': 'D69188'
}
{
'name': '<NAME>'
'hex': 'D6C562'
}
{
'name': '<NAME>'
'hex': 'D6CEF6'
}
{
'name': '<NAME>'
'hex': 'D6D6D1'
}
{
'name': '<NAME>'
'hex': 'D6FFDB'
}
{
'name': '<NAME>'
'hex': 'D7837F'
}
{
'name': '<NAME>'
'hex': 'D7C498'
}
{
'name': '<NAME>'
'hex': 'D7D0FF'
}
{
'name': '<NAME>'
'hex': 'D84437'
}
{
'name': '<NAME>'
'hex': 'D87C63'
}
{
'name': '<NAME>'
'hex': 'D8BFD8'
}
{
'name': '<NAME>'
'hex': 'D8C2D5'
}
{
'name': '<NAME>'
'hex': 'D8FCFA'
}
{
'name': '<NAME>'
'hex': 'D94972'
}
{
'name': '<NAME>'
'hex': 'D99376'
}
{
'name': '<NAME>'
'hex': 'D9B99B'
}
{
'name': '<NAME>'
'hex': 'D9D6CF'
}
{
'name': '<NAME>'
'hex': 'D9DCC1'
}
{
'name': '<NAME>'
'hex': 'D9E4F5'
}
{
'name': '<NAME>'
'hex': 'D9F7FF'
}
{
'name': '<NAME>'
'hex': 'DA3287'
}
{
'name': '<NAME>'
'hex': 'DA5B38'
}
{
'name': '<NAME>'
'hex': 'DA6304'
}
{
'name': '<NAME>'
'hex': 'DA6A41'
}
{
'name': '<NAME>'
'hex': 'DA70D6'
}
{
'name': '<NAME>'
'hex': 'DA8A67'
}
{
'name': '<NAME>'
'hex': 'DAA520'
}
{
'name': '<NAME>'
'hex': 'DAECD6'
}
{
'name': '<NAME>'
'hex': 'DAF4F0'
}
{
'name': '<NAME>'
'hex': 'DAFAFF'
}
{
'name': '<NAME>'
'hex': 'DB5079'
}
{
'name': '<NAME>'
'hex': 'DB9690'
}
{
'name': '<NAME>'
'hex': 'DB995E'
}
{
'name': '<NAME>'
'hex': 'DBDBDB'
}
{
'name': '<NAME>'
'hex': 'DBFFF8'
}
{
'name': '<NAME>'
'hex': 'DC143C'
}
{
'name': '<NAME>'
'hex': 'DC4333'
}
{
'name': '<NAME>'
'hex': 'DCB20C'
}
{
'name': '<NAME>'
'hex': 'DCB4BC'
}
{
'name': '<NAME>'
'hex': 'DCD747'
}
{
'name': '<NAME>'
'hex': 'DCD9D2'
}
{
'name': '<NAME>'
'hex': 'DCDDCC'
}
{
'name': '<NAME>'
'hex': 'DCEDB4'
}
{
'name': '<NAME>'
'hex': 'DCF0EA'
}
{
'name': '<NAME>'
'hex': 'DDD6D5'
}
{
'name': '<NAME>'
'hex': 'DDF9F1'
}
{
'name': '<NAME>'
'hex': 'DE3163'
}
{
'name': '<NAME>'
'hex': 'DE6360'
}
{
'name': '<NAME>'
'hex': 'DEA681'
}
{
'name': '<NAME>'
'hex': 'DEBA13'
}
{
'name': '<NAME>'
'hex': 'DEC196'
}
{
'name': '<NAME>'
'hex': 'DECBC6'
}
{
'name': '<NAME>'
'hex': 'DED4A4'
}
{
'name': '<NAME>'
'hex': 'DED717'
}
{
'name': '<NAME>'
'hex': 'DEE5C0'
}
{
'name': '<NAME>'
'hex': 'DEF5FF'
}
{
'name': '<NAME>'
'hex': 'DF73FF'
}
{
'name': '<NAME>'
'hex': 'DFBE6F'
}
{
'name': '<NAME>'
'hex': 'DFCD6F'
}
{
'name': '<NAME>'
'hex': 'DFCFDB'
}
{
'name': '<NAME>'
'hex': 'DFECDA'
}
{
'name': '<NAME>'
'hex': 'DFFF00'
}
{
'name': '<NAME>'
'hex': 'E0B0FF'
}
{
'name': '<NAME>'
'hex': 'E0B646'
}
{
'name': '<NAME>'
'hex': 'E0B974'
}
{
'name': '<NAME>'
'hex': 'E0C095'
}
{
'name': '<NAME>'
'hex': 'E0FFFF'
}
{
'name': '<NAME>'
'hex': 'E16865'
}
{
'name': '<NAME>'
'hex': 'E1BC64'
}
{
'name': '<NAME>'
'hex': 'E1C0C8'
}
{
'name': '<NAME>'
'hex': 'E1E6D6'
}
{
'name': '<NAME>'
'hex': 'E1EAD4'
}
{
'name': '<NAME>'
'hex': 'E1F6E8'
}
{
'name': '<NAME>'
'hex': 'E25465'
}
{
'name': '<NAME>'
'hex': 'E2725B'
}
{
'name': '<NAME>'
'hex': 'E28913'
}
{
'name': '<NAME>'
'hex': 'E292C0'
}
{
'name': '<NAME>'
'hex': 'E29418'
}
{
'name': '<NAME>'
'hex': 'E29CD2'
}
{
'name': '<NAME>'
'hex': 'E2D8ED'
}
{
'name': '<NAME>'
'hex': 'E2EBED'
}
{
'name': '<NAME>'
'hex': 'E2F3EC'
}
{
'name': '<NAME>'
'hex': 'E30B5C'
}
{
'name': '<NAME>'
'hex': 'E32636'
}
{
'name': '<NAME>'
'hex': 'E34234'
}
{
'name': '<NAME>'
'hex': 'E3BEBE'
}
{
'name': '<NAME>'
'hex': 'E3F5E1'
}
{
'name': '<NAME>'
'hex': 'E3F988'
}
{
'name': '<NAME>'
'hex': 'E47698'
}
{
'name': '<NAME>'
'hex': 'E49B0F'
}
{
'name': '<NAME>'
'hex': 'E4C2D5'
}
{
'name': '<NAME>'
'hex': 'E4CFDE'
}
{
'name': '<NAME>'
'hex': 'E4D1C0'
}
{
'name': '<NAME>'
'hex': 'E4D422'
}
{
'name': '<NAME>'
'hex': 'E4D5B7'
}
{
'name': '<NAME>'
'hex': 'E4D69B'
}
{
'name': '<NAME>'
'hex': 'E4F6E7'
}
{
'name': '<NAME>'
'hex': 'E4FFD1'
}
{
'name': '<NAME>'
'hex': 'E52B50'
}
{
'name': '<NAME>'
'hex': 'E5841B'
}
{
'name': '<NAME>'
'hex': 'E5CCC9'
}
{
'name': '<NAME>'
'hex': 'E5D7BD'
}
{
'name': '<NAME>'
'hex': 'E5D8AF'
}
{
'name': '<NAME>'
'hex': 'E5E0E1'
}
{
'name': '<NAME>'
'hex': 'E5E5E5'
}
{
'name': '<NAME>'
'hex': 'E5F9F6'
}
{
'name': '<NAME>'
'hex': 'E64E03'
}
{
'name': '<NAME>'
'hex': 'E6BE8A'
}
{
'name': '<NAME>'
'hex': 'E6BEA5'
}
{
'name': '<NAME>'
'hex': 'E6D7B9'
}
{
'name': '<NAME>'
'hex': 'E6E4D4'
}
{
'name': '<NAME>'
'hex': 'E6F2EA'
}
{
'name': '<NAME>'
'hex': 'E6F8F3'
}
{
'name': '<NAME>'
'hex': 'E6FFE9'
}
{
'name': '<NAME>'
'hex': 'E6FFFF'
}
{
'name': '<NAME>'
'hex': 'E77200'
}
{
'name': '<NAME>'
'hex': 'E7730A'
}
{
'name': '<NAME>'
'hex': 'E79F8C'
}
{
'name': '<NAME>'
'hex': 'E79FC4'
}
{
'name': '<NAME>'
'hex': 'E7BCB4'
}
{
'name': '<NAME>'
'hex': 'E7BF05'
}
{
'name': '<NAME>'
'hex': 'E7CD8C'
}
{
'name': '<NAME>'
'hex': 'E7ECE6'
}
{
'name': '<NAME>'
'hex': 'E7F8FF'
}
{
'name': '<NAME>'
'hex': 'E7FEFF'
}
{
'name': '<NAME>'
'hex': 'E89928'
}
{
'name': '<NAME>'
'hex': 'E8B9B3'
}
{
'name': '<NAME>'
'hex': 'E8E0D5'
}
{
'name': '<NAME>'
'hex': 'E8EBE0'
}
{
'name': '<NAME>'
'hex': 'E8F1D4'
}
{
'name': '<NAME>'
'hex': 'E8F2EB'
}
{
'name': '<NAME>'
'hex': 'E8F5F2'
}
{
'name': '<NAME>'
'hex': 'E96E00'
}
{
'name': '<NAME>'
'hex': 'E97451'
}
{
'name': '<NAME>'
'hex': 'E97C07'
}
{
'name': '<NAME>'
'hex': 'E9CECD'
}
{
'name': '<NAME>'
'hex': 'E9D75A'
}
{
'name': '<NAME>'
'hex': 'E9E3E3'
}
{
'name': '<NAME>'
'hex': 'E9F8ED'
}
{
'name': '<NAME>'
'hex': 'E9FFFD'
}
{
'name': '<NAME>'
'hex': 'EA88A8'
}
{
'name': '<NAME>'
'hex': 'EAAE69'
}
{
'name': '<NAME>'
'hex': 'EAB33B'
}
{
'name': '<NAME>'
'hex': 'EAC674'
}
{
'name': '<NAME>'
'hex': 'EADAB8'
}
{
'name': '<NAME>'
'hex': 'EAE8D4'
}
{
'name': '<NAME>'
'hex': 'EAF6EE'
}
{
'name': '<NAME>'
'hex': 'EAF6FF'
}
{
'name': '<NAME>'
'hex': 'EAF9F5'
}
{
'name': '<NAME>'
'hex': 'EAFFFE'
}
{
'name': '<NAME>'
'hex': 'EB9373'
}
{
'name': '<NAME>'
'hex': 'EBC2AF'
}
{
'name': '<NAME>'
'hex': 'ECA927'
}
{
'name': '<NAME>'
'hex': 'ECC54E'
}
{
'name': '<NAME>'
'hex': 'ECC7EE'
}
{
'name': '<NAME>'
'hex': 'ECCDB9'
}
{
'name': '<NAME>'
'hex': 'ECE090'
}
{
'name': '<NAME>'
'hex': 'ECEBBD'
}
{
'name': '<NAME>'
'hex': 'ECEBCE'
}
{
'name': '<NAME>'
'hex': 'ECF245'
}
{
'name': '<NAME>'
'hex': 'ED0A3F'
}
{
'name': '<NAME>'
'hex': 'ED7A1C'
}
{
'name': '<NAME>'
'hex': 'ED9121'
}
{
'name': '<NAME>'
'hex': 'ED989E'
}
{
'name': '<NAME>'
'hex': 'EDB381'
}
{
'name': '<NAME>'
'hex': 'EDC9AF'
}
{
'name': '<NAME>'
'hex': 'EDCDAB'
}
{
'name': '<NAME>'
'hex': 'EDDCB1'
}
{
'name': '<NAME>'
'hex': 'EDEA99'
}
{
'name': '<NAME>'
'hex': 'EDF5DD'
}
{
'name': '<NAME>'
'hex': 'EDF5F5'
}
{
'name': '<NAME>'
'hex': 'EDF6FF'
}
{
'name': '<NAME>'
'hex': 'EDF9F1'
}
{
'name': '<NAME>'
'hex': 'EDFC84'
}
{
'name': '<NAME>'
'hex': 'EE82EE'
}
{
'name': '<NAME>'
'hex': 'EEC1BE'
}
{
'name': '<NAME>'
'hex': 'EED794'
}
{
'name': '<NAME>'
'hex': 'EED9C4'
}
{
'name': '<NAME>'
'hex': 'EEDC82'
}
{
'name': '<NAME>'
'hex': 'EEDEDA'
}
{
'name': '<NAME>'
'hex': 'EEE3AD'
}
{
'name': '<NAME>'
'hex': 'EEEEE8'
}
{
'name': '<NAME>'
'hex': 'EEEF78'
}
{
'name': '<NAME>'
'hex': 'EEF0C8'
}
{
'name': '<NAME>'
'hex': 'EEF0F3'
}
{
'name': '<NAME>'
'hex': 'EEF3C3'
}
{
'name': '<NAME>'
'hex': 'EEF4DE'
}
{
'name': '<NAME>'
'hex': 'EEF6F7'
}
{
'name': '<NAME>'
'hex': 'EEFDFF'
}
{
'name': '<NAME>'
'hex': 'EEFF9A'
}
{
'name': '<NAME>'
'hex': 'EEFFE2'
}
{
'name': '<NAME>'
'hex': 'EF863F'
}
{
'name': '<NAME>'
'hex': 'EFEFEF'
}
{
'name': '<NAME>'
'hex': 'EFF2F3'
}
{
'name': '<NAME>'
'hex': 'F091A9'
}
{
'name': '<NAME>'
'hex': 'F0D52D'
}
{
'name': '<NAME>'
'hex': 'F0DB7D'
}
{
'name': '<NAME>'
'hex': 'F0DC82'
}
{
'name': '<NAME>'
'hex': 'F0E2EC'
}
{
'name': '<NAME>'
'hex': 'F0E68C'
}
{
'name': '<NAME>'
'hex': 'F0EEFD'
}
{
'name': '<NAME>'
'hex': 'F0EEFF'
}
{
'name': '<NAME>'
'hex': 'F0F8FF'
}
{
'name': '<NAME>'
'hex': 'F0FCEA'
}
{
'name': '<NAME>'
'hex': 'F18200'
}
{
'name': '<NAME>'
'hex': 'F19BAB'
}
{
'name': '<NAME>'
'hex': 'F1E788'
}
{
'name': '<NAME>'
'hex': 'F1E9D2'
}
{
'name': '<NAME>'
'hex': 'F1E9FF'
}
{
'name': '<NAME>'
'hex': 'F1EEC1'
}
{
'name': '<NAME>'
'hex': 'F1F1F1'
}
{
'name': '<NAME>'
'hex': 'F1F7F2'
}
{
'name': '<NAME>'
'hex': 'F1FFAD'
}
{
'name': '<NAME>'
'hex': 'F1FFC8'
}
{
'name': '<NAME>'
'hex': 'F2552A'
}
{
'name': '<NAME>'
'hex': 'F28500'
}
{
'name': '<NAME>'
'hex': 'F2C3B2'
}
{
'name': 'Concrete'
'hex': 'F2F2F2'
}
{
'name': '<NAME>'
'hex': 'F2FAFA'
}
{
'name': 'Pome<NAME>'
'hex': 'F34723'
}
{
'name': '<NAME>'
'hex': 'F3AD16'
}
{
'name': 'New <NAME>'
'hex': 'F3D69D'
}
{
'name': 'Vanilla <NAME>'
'hex': 'F3D9DF'
}
{
'name': '<NAME>'
'hex': 'F3E7BB'
}
{
'name': '<NAME>'
'hex': 'F3E9E5'
}
{
'name': '<NAME>'
'hex': 'F3EDCF'
}
{
'name': 'Can<NAME>'
'hex': 'F3FB62'
}
{
'name': '<NAME>'
'hex': 'F3FBD4'
}
{
'name': '<NAME>'
'hex': 'F3FFD8'
}
{
'name': '<NAME>'
'hex': 'F400A1'
}
{
'name': '<NAME>'
'hex': 'F4A460'
}
{
'name': '<NAME>'
'hex': 'F4C430'
}
{
'name': '<NAME>'
'hex': 'F4D81C'
}
{
'name': '<NAME>'
'hex': 'F4EBD3'
}
{
'name': '<NAME>'
'hex': 'F4F2EE'
}
{
'name': '<NAME>'
'hex': 'F4F4F4'
}
{
'name': '<NAME>'
'hex': 'F4F8FF'
}
{
'name': '<NAME>'
'hex': 'F57584'
}
{
'name': '<NAME>'
'hex': 'F5C85C'
}
{
'name': '<NAME>'
'hex': 'F5C999'
}
{
'name': '<NAME>'
'hex': 'F5D5A0'
}
{
'name': '<NAME>'
'hex': 'F5DEB3'
}
{
'name': '<NAME>'
'hex': 'F5E7A2'
}
{
'name': '<NAME>'
'hex': 'F5E7E2'
}
{
'name': '<NAME>'
'hex': 'F5E9D3'
}
{
'name': '<NAME>'
'hex': 'F5EDEF'
}
{
'name': '<NAME>'
'hex': 'F5F3E5'
}
{
'name': '<NAME>'
'hex': 'F5F5DC'
}
{
'name': '<NAME>'
'hex': 'F5FB3D'
}
{
'name': 'Australian M<NAME>'
'hex': 'F5FFBE'
}
{
'name': '<NAME>'
'hex': 'F64A8A'
}
{
'name': '<NAME>'
'hex': 'F653A6'
}
{
'name': '<NAME>'
'hex': 'F6A4C9'
}
{
'name': '<NAME>'
'hex': 'F6F0E6'
}
{
'name': 'Black <NAME>'
'hex': 'F6F7F7'
}
{
'name': 'Spring Sun'
'hex': 'F6FFDC'
}
{
'name': '<NAME>'
'hex': 'F7468A'
}
{
'name': '<NAME>'
'hex': 'F77703'
}
{
'name': '<NAME>'
'hex': 'F77FBE'
}
{
'name': '<NAME>'
'hex': 'F7B668'
}
{
'name': '<NAME>'
'hex': 'F7C8DA'
}
{
'name': '<NAME>'
'hex': 'F7DBE6'
}
{
'name': '<NAME> Spanish White'
'hex': 'F7F2E1'
}
{
'name': '<NAME>'
'hex': 'F7F5FA'
}
{
'name': '<NAME>'
'hex': 'F7FAF7'
}
{
'name': '<NAME>'
'hex': 'F8B853'
}
{
'name': '<NAME>'
'hex': 'F8C3DF'
}
{
'name': '<NAME>'
'hex': 'F8D9E9'
}
{
'name': '<NAME>'
'hex': 'F8DB9D'
}
{
'name': '<NAME>'
'hex': 'F8DD5C'
}
{
'name': '<NAME>'
'hex': 'F8E4BF'
}
{
'name': '<NAME>'
'hex': 'F8F0E8'
}
{
'name': '<NAME>'
'hex': 'F8F4FF'
}
{
'name': '<NAME>'
'hex': 'F8F6F1'
}
{
'name': '<NAME>'
'hex': 'F8F7DC'
}
{
'name': '<NAME>'
'hex': 'F8F7FC'
}
{
'name': '<NAME>'
'hex': 'F8F8F7'
}
{
'name': '<NAME>'
'hex': 'F8F99C'
}
{
'name': '<NAME>'
'hex': 'F8FACD'
}
{
'name': '<NAME>'
'hex': 'F8FDD3'
}
{
'name': '<NAME>'
'hex': 'F95A61'
}
{
'name': '<NAME>'
'hex': 'F9BF58'
}
{
'name': '<NAME>'
'hex': 'F9E0ED'
}
{
'name': '<NAME>'
'hex': 'F9E4BC'
}
{
'name': '<NAME>'
'hex': 'F9E663'
}
{
'name': '<NAME>'
'hex': 'F9EAF3'
}
{
'name': '<NAME>'
'hex': 'F9F8E4'
}
{
'name': '<NAME>'
'hex': 'F9FF8B'
}
{
'name': '<NAME>'
'hex': 'F9FFF6'
}
{
'name': '<NAME>'
'hex': 'FA7814'
}
{
'name': '<NAME>'
'hex': 'FA9D5A'
}
{
'name': '<NAME>'
'hex': 'FAD3A2'
}
{
'name': '<NAME>'
'hex': 'FADFAD'
}
{
'name': '<NAME>'
'hex': 'FAE600'
}
{
'name': '<NAME>'
'hex': 'FAEAB9'
}
{
'name': '<NAME>'
'hex': 'FAECCC'
}
{
'name': '<NAME>'
'hex': 'FAF0E6'
}
{
'name': '<NAME>'
'hex': 'FAF3F0'
}
{
'name': '<NAME>'
'hex': 'FAF7D6'
}
{
'name': '<NAME>'
'hex': 'FAFAFA'
}
{
'name': '<NAME>'
'hex': 'FAFDE4'
}
{
'name': '<NAME>'
'hex': 'FAFFA4'
}
{
'name': '<NAME>'
'hex': 'FB607F'
}
{
'name': '<NAME>'
'hex': 'FB8989'
}
{
'name': '<NAME>'
'hex': 'FBA0E3'
}
{
'name': '<NAME>thorn'
'hex': 'FBA129'
}
{
'name': 'Sun'
'hex': 'FBAC13'
}
{
'name': '<NAME>'
'hex': 'FBAED2'
}
{
'name': '<NAME>'
'hex': 'FBB2A3'
}
{
'name': '<NAME>'
'hex': 'FBBEDA'
}
{
'name': '<NAME> Rose'
'hex': 'FBCCE7'
}
{
'name': '<NAME>'
'hex': 'FBCEB1'
}
{
'name': '<NAME>'
'hex': 'FBE7B2'
}
{
'name': '<NAME>'
'hex': 'FBE870'
}
{
'name': '<NAME>'
'hex': 'FBE96C'
}
{
'name': '<NAME>'
'hex': 'FBEA8C'
}
{
'name': '<NAME>'
'hex': 'FBEC5D'
}
{
'name': '<NAME>'
'hex': 'FBF9F9'
}
{
'name': '<NAME>'
'hex': 'FBFFBA'
}
{
'name': '<NAME>'
'hex': 'FC0FC0'
}
{
'name': '<NAME>'
'hex': 'FC80A5'
}
{
'name': '<NAME>'
'hex': 'FC9C1D'
}
{
'name': '<NAME>'
'hex': 'FCC01E'
}
{
'name': '<NAME>'
'hex': 'FCD667'
}
{
'name': '<NAME>'
'hex': 'FCD917'
}
{
'name': '<NAME>'
'hex': 'FCDA98'
}
{
'name': '<NAME>'
'hex': 'FCF4D0'
}
{
'name': '<NAME>'
'hex': 'FCF4DC'
}
{
'name': '<NAME>'
'hex': 'FCF8F7'
}
{
'name': '<NAME>'
'hex': 'FCFBF3'
}
{
'name': '<NAME>'
'hex': 'FCFEDA'
}
{
'name': '<NAME>ory'
'hex': 'FCFFE7'
}
{
'name': '<NAME>'
'hex': 'FCFFF9'
}
{
'name': 'Torch Red'
'hex': 'FD0E35'
}
{
'name': 'Wild Watermelon'
'hex': 'FD5B78'
}
{
'name': '<NAME>'
'hex': 'FD7B33'
}
{
'name': '<NAME>'
'hex': 'FD7C07'
}
{
'name': '<NAME>'
'hex': 'FD9FA2'
}
{
'name': '<NAME>'
'hex': 'FDD5B1'
}
{
'name': '<NAME>'
'hex': 'FDD7E4'
}
{
'name': '<NAME>'
'hex': 'FDE1DC'
}
{
'name': '<NAME>'
'hex': 'FDE295'
}
{
'name': '<NAME>'
'hex': 'FDE910'
}
{
'name': '<NAME>'
'hex': 'FDF5E6'
}
{
'name': '<NAME> Colonial <NAME>'
'hex': 'FDF6D3'
}
{
'name': '<NAME>'
'hex': 'FDF7AD'
}
{
'name': '<NAME>'
'hex': 'FDFEB8'
}
{
'name': '<NAME>'
'hex': 'FDFFD5'
}
{
'name': '<NAME>'
'hex': 'FE28A2'
}
{
'name': '<NAME>'
'hex': 'FE4C40'
}
{
'name': '<NAME>'
'hex': 'FE6F5E'
}
{
'name': 'California'
'hex': 'FE9D04'
}
{
'name': '<NAME>'
'hex': 'FEA904'
}
{
'name': '<NAME>'
'hex': 'FEBAAD'
}
{
'name': '<NAME>'
'hex': 'FED33C'
}
{
'name': '<NAME>'
'hex': 'FED85D'
}
{
'name': '<NAME>'
'hex': 'FEDB8D'
}
{
'name': '<NAME>'
'hex': 'FEE5AC'
}
{
'name': '<NAME>'
'hex': 'FEEBF3'
}
{
'name': '<NAME>'
'hex': 'FEEFCE'
}
{
'name': '<NAME>'
'hex': 'FEF0EC'
}
{
'name': '<NAME>'
'hex': 'FEF2C7'
}
{
'name': '<NAME>'
'hex': 'FEF3D8'
}
{
'name': '<NAME>'
'hex': 'FEF4CC'
}
{
'name': '<NAME> Spanish <NAME>'
'hex': 'FEF4DB'
}
{
'name': '<NAME>'
'hex': 'FEF4F8'
}
{
'name': '<NAME>'
'hex': 'FEF5F1'
}
{
'name': '<NAME> D<NAME>'
'hex': 'FEF7DE'
}
{
'name': '<NAME>'
'hex': 'FEF8E2'
}
{
'name': '<NAME>'
'hex': 'FEF8FF'
}
{
'name': '<NAME>'
'hex': 'FEF9E3'
}
{
'name': 'Orange <NAME>'
'hex': 'FEFCED'
}
{
'name': '<NAME>'
'hex': 'FF0000'
}
{
'name': '<NAME>'
'hex': 'FF007F'
}
{
'name': '<NAME>'
'hex': 'FF00CC'
}
{
'name': 'Magenta / Fuchsia'
'hex': 'FF00FF'
}
{
'name': 'Scarlet'
'hex': 'FF2400'
}
{
'name': 'Wild Strawberry'
'hex': 'FF3399'
}
{
'name': 'Razzle Dazzle Rose'
'hex': 'FF33CC'
}
{
'name': 'Radical Red'
'hex': 'FF355E'
}
{
'name': 'Red Orange'
'hex': 'FF3F34'
}
{
'name': 'Coral Red'
'hex': 'FF4040'
}
{
'name': 'Vermilion'
'hex': 'FF4D00'
}
{
'name': 'International Orange'
'hex': 'FF4F00'
}
{
'name': 'Outrageous Orange'
'hex': 'FF6037'
}
{
'name': 'Blaze Orange'
'hex': 'FF6600'
}
{
'name': 'Pink Flamingo'
'hex': 'FF66FF'
}
{
'name': 'Orange'
'hex': 'FF681F'
}
{
'name': 'Hot Pink'
'hex': 'FF69B4'
}
{
'name': 'Persimmon'
'hex': 'FF6B53'
}
{
'name': 'Blush Pink'
'hex': 'FF6FFF'
}
{
'name': 'Burning Orange'
'hex': 'FF7034'
}
{
'name': 'Pumpkin'
'hex': 'FF7518'
}
{
'name': 'Flamenco'
'hex': 'FF7D07'
}
{
'name': 'Flush Orange'
'hex': 'FF7F00'
}
{
'name': 'Coral'
'hex': 'FF7F50'
}
{
'name': 'Salmon'
'hex': 'FF8C69'
}
{
'name': '<NAME>'
'hex': 'FF9000'
}
{
'name': 'West Side'
'hex': 'FF910F'
}
{
'name': 'Pink Salmon'
'hex': 'FF91A4'
}
{
'name': 'Neon Carrot'
'hex': 'FF9933'
}
{
'name': 'Atomic Tangerine'
'hex': 'FF9966'
}
{
'name': 'Vivid Tangerine'
'hex': 'FF9980'
}
{
'name': 'Sunshade'
'hex': 'FF9E2C'
}
{
'name': 'Orange Peel'
'hex': 'FFA000'
}
{
'name': '<NAME>'
'hex': 'FFA194'
}
{
'name': 'Web Orange'
'hex': 'FFA500'
}
{
'name': '<NAME>'
'hex': 'FFA6C9'
}
{
'name': 'Hit P<NAME>'
'hex': 'FFAB81'
}
{
'name': 'Yellow O<NAME>'
'hex': 'FFAE42'
}
{
'name': '<NAME>'
'hex': 'FFB0AC'
}
{
'name': '<NAME>'
'hex': 'FFB1B3'
}
{
'name': '<NAME>'
'hex': 'FFB31F'
}
{
'name': '<NAME>'
'hex': 'FFB555'
}
{
'name': '<NAME>'
'hex': 'FFB7D5'
}
{
'name': '<NAME>'
'hex': 'FFB97B'
}
{
'name': 'Selective Yellow'
'hex': 'FFBA00'
}
{
'name': '<NAME>'
'hex': 'FFBD5F'
}
{
'name': '<NAME>'
'hex': 'FFBF00'
}
{
'name': '<NAME>'
'hex': 'FFC0A8'
}
{
'name': '<NAME>'
'hex': 'FFC0CB'
}
{
'name': '<NAME>'
'hex': 'FFC3C0'
}
{
'name': '<NAME>'
'hex': 'FFC901'
}
{
'name': '<NAME>'
'hex': 'FFCBA4'
}
{
'name': '<NAME>'
'hex': 'FFCC33'
}
{
'name': '<NAME>'
'hex': 'FFCC5C'
}
{
'name': '<NAME>'
'hex': 'FFCC99'
}
{
'name': '<NAME>'
'hex': 'FFCD8C'
}
{
'name': '<NAME>'
'hex': 'FFD1DC'
}
{
'name': '<NAME>'
'hex': 'FFD2B7'
}
{
'name': '<NAME>'
'hex': 'FFD38C'
}
{
'name': '<NAME>'
'hex': 'FFD700'
}
{
'name': '<NAME> bus Yellow'
'hex': 'FFD800'
}
{
'name': '<NAME>'
'hex': 'FFD8D9'
}
{
'name': '<NAME>'
'hex': 'FFDB58'
}
{
'name': '<NAME>'
'hex': 'FFDCD6'
}
{
'name': '<NAME>'
'hex': 'FFDDAF'
}
{
'name': '<NAME>'
'hex': 'FFDDCD'
}
{
'name': '<NAME>'
'hex': 'FFDDCF'
}
{
'name': '<NAME>'
'hex': 'FFDDF4'
}
{
'name': '<NAME>'
'hex': 'FFDEAD'
}
{
'name': '<NAME>'
'hex': 'FFDEB3'
}
{
'name': '<NAME>'
'hex': 'FFE1DF'
}
{
'name': '<NAME>'
'hex': 'FFE1F2'
}
{
'name': '<NAME>'
'hex': 'FFE2C5'
}
{
'name': '<NAME>'
'hex': 'FFE5A0'
}
{
'name': '<NAME>'
'hex': 'FFE5B4'
}
{
'name': '<NAME>'
'hex': 'FFE6C7'
}
{
'name': '<NAME>'
'hex': 'FFE772'
}
{
'name': '<NAME>'
'hex': 'FFEAC8'
}
{
'name': '<NAME>'
'hex': 'FFEAD4'
}
{
'name': '<NAME>'
'hex': 'FFEC13'
}
{
'name': '<NAME>'
'hex': 'FFEDBC'
}
{
'name': '<NAME>'
'hex': 'FFEED8'
}
{
'name': '<NAME>'
'hex': 'FFEFA1'
}
{
'name': '<NAME>'
'hex': 'FFEFC1'
}
{
'name': '<NAME>'
'hex': 'FFEFD5'
}
{
'name': '<NAME>'
'hex': 'FFEFEC'
}
{
'name': '<NAME>'
'hex': 'FFF0DB'
}
{
'name': 'Lav<NAME>'
'hex': 'FFF0F5'
}
{
'name': '<NAME>'
'hex': 'FFF14F'
}
{
'name': '<NAME>'
'hex': 'FFF1B5'
}
{
'name': '<NAME>'
'hex': 'FFF1D8'
}
{
'name': '<NAME>'
'hex': 'FFF1EE'
}
{
'name': '<NAME>'
'hex': 'FFF1F9'
}
{
'name': '<NAME>'
'hex': 'FFF39D'
}
{
'name': '<NAME>'
'hex': 'FFF3F1'
}
{
'name': '<NAME>'
'hex': 'FFF46E'
}
{
'name': '<NAME>'
'hex': 'FFF4CE'
}
{
'name': '<NAME>'
'hex': 'FFF4DD'
}
{
'name': '<NAME>'
'hex': 'FFF4E0'
}
{
'name': '<NAME>'
'hex': 'FFF4E8'
}
{
'name': '<NAME>'
'hex': 'FFF4F3'
}
{
'name': '<NAME>'
'hex': 'FFF5EE'
}
{
'name': '<NAME>'
'hex': 'FFF5F3'
}
{
'name': '<NAME>'
'hex': 'FFF6D4'
}
{
'name': '<NAME>'
'hex': 'FFF6DF'
}
{
'name': '<NAME>'
'hex': 'FFF6F5'
}
{
'name': '<NAME>'
'hex': 'FFF8D1'
}
{
'name': '<NAME>'
'hex': 'FFF9E2'
}
{
'name': '<NAME>'
'hex': 'FFF9E6'
}
{
'name': '<NAME>'
'hex': 'FFFACD'
}
{
'name': '<NAME>'
'hex': 'FFFAF4'
}
{
'name': '<NAME>'
'hex': 'FFFBDC'
}
{
'name': 'Soapstone'
'hex': 'FFFBF9'
}
{
'name': 'Witch Haze'
'hex': 'FFFC99'
}
{
'name': 'B<NAME>y White'
'hex': 'FFFCEA'
}
{
'name': 'Island Spice'
'hex': 'FFFCEE'
}
{
'name': 'Cream'
'hex': 'FFFDD0'
}
{
'name': 'Chilean Heath'
'hex': 'FFFDE6'
}
{
'name': 'Travertine'
'hex': 'FFFDE8'
}
{
'name': 'Orchid White'
'hex': 'FFFDF3'
}
{
'name': 'Quarter Pearl Lusta'
'hex': 'FFFDF4'
}
{
'name': 'Half and Half'
'hex': 'FFFEE1'
}
{
'name': '<NAME>'
'hex': 'FFFEEC'
}
{
'name': 'Rice Cake'
'hex': 'FFFEF0'
}
{
'name': 'Black White'
'hex': 'FFFEF6'
}
{
'name': 'Romance'
'hex': 'FFFEFD'
}
{
'name': 'Yellow'
'hex': 'FFFF00'
}
{
'name': 'Laser Lemon'
'hex': 'FFFF66'
}
{
'name': 'Pale Canary'
'hex': 'FFFF99'
}
{
'name': 'Portafino'
'hex': 'FFFFB4'
}
{
'name': '<NAME>ory'
'hex': 'FFFFF0'
}
{
'name': 'White'
'hex': 'FFFFFF'
}
]
| true | module.exports = [
{
'name': 'Black'
'hex': '000000'
}
{
'name': 'Navy Blue'
'hex': '000080'
}
{
'name': 'Dark Blue'
'hex': '0000C8'
}
{
'name': 'Blue'
'hex': '0000FF'
}
{
'name': 'Stratos'
'hex': '000741'
}
{
'name': 'Swamp'
'hex': '001B1C'
}
{
'name': 'Resolution Blue'
'hex': '002387'
}
{
'name': 'Deep Fir'
'hex': '002900'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '002E20'
}
{
'name': 'International Klein Blue'
'hex': '002FA7'
}
{
'name': 'Prussian Blue'
'hex': '003153'
}
{
'name': 'Midnight Blue'
'hex': '003366'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '003399'
}
{
'name': 'Deep Teal'
'hex': '003532'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '003E40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '004620'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0047AB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '004816'
}
{
'name': 'Sherpa Blue'
'hex': '004950'
}
{
'name': 'Endeavour'
'hex': '0056A7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '00581A'
}
{
'name': 'Science Blue'
'hex': '0066CC'
}
{
'name': 'Blue Ribbon'
'hex': '0066FF'
}
{
'name': 'Tropical Rain Forest'
'hex': '00755E'
}
{
'name': 'Allports'
'hex': '0076A3'
}
{
'name': 'Deep Cerulean'
'hex': '007BA7'
}
{
'name': 'Lochmara'
'hex': '007EC7'
}
{
'name': 'Azure Radiance'
'hex': '007FFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '008080'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0095B6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '009DC4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '00A693'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '00A86B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '00CC99'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '00CCCC'
}
{
'name': 'Green'
'hex': '00FF00'
}
{
'name': 'Spring Green'
'hex': '00FF7F'
}
{
'name': 'Cyan / Aqua'
'hex': '00FFFF'
}
{
'name': 'Blue Charcoal'
'hex': '010D1A'
}
{
'name': 'Midnight'
'hex': '011635'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '011D13'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '012731'
}
{
'name': 'Cardin Green'
'hex': '01361C'
}
{
'name': 'County Green'
'hex': '01371A'
}
{
'name': 'Astronaut Blue'
'hex': '013E62'
}
{
'name': 'Regal Blue'
'hex': '013F6A'
}
{
'name': 'Aqua Deep'
'hex': '014B43'
}
{
'name': 'Orient'
'hex': '015E85'
}
{
'name': 'Blue Stone'
'hex': '016162'
}
{
'name': 'Fun Green'
'hex': '016D39'
}
{
'name': 'Pine Green'
'hex': '01796F'
}
{
'name': 'Blue Lagoon'
'hex': '017987'
}
{
'name': 'Deep Sea'
'hex': '01826B'
}
{
'name': 'Green Haze'
'hex': '01A368'
}
{
'name': 'English Holly'
'hex': '022D15'
}
{
'name': 'Sherwood Green'
'hex': '02402C'
}
{
'name': 'Congress Blue'
'hex': '02478E'
}
{
'name': 'Evening Sea'
'hex': '024E46'
}
{
'name': 'Bahama Blue'
'hex': '026395'
}
{
'name': 'Observatory'
'hex': '02866F'
}
{
'name': 'Cerulean'
'hex': '02A4D3'
}
{
'name': 'Tangaroa'
'hex': '03163C'
}
{
'name': 'Green VPI:NAME:<NAME>END_PIue'
'hex': '032B52'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '036A6E'
}
{
'name': 'Midnight MoPI:NAME:<NAME>END_PI'
'hex': '041004'
}
{
'name': 'Black Pearl'
'hex': '041322'
}
{
'name': 'Blue Whale'
'hex': '042E4C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '044022'
}
{
'name': 'TePI:NAME:<NAME>END_PI Blue'
'hex': '044259'
}
{
'name': 'Deep CPI:NAME:<NAME>END_PI'
'hex': '051040'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '051657'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '055989'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '056F57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '062A78'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '063537'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '069B81'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '06A189'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '073A50'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '080110'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '081910'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '082567'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '088370'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '08E8DE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '092256'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '09230F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '09255D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '093624'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '095859'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '097F4B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0A001C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0A480D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0A6906'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0A6F75'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0B0B0B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0B0F08'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0B1107'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0B1304'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0B6207'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0BDA51'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0C0B1D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0C0D0F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0C1911'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0C7A79'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0C8990'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0D0332'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0D1117'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0D1C19'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0D2E1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0E0E18'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0E2A30'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '0F2D9E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '10121D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '101405'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '105852'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '110C6C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '120A8F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '123447'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '126B40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '130000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '130A06'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '13264D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '134F19'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '140600'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1450AA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '151F4C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1560BD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '15736B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '161928'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '161D10'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '162A40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '163222'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '16322C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '163531'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '171F04'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '175579'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '182D09'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '18587A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '19330E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '193751'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1959A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1A1A68'
}
{
'name': 'Mountain Meadow'
'hex': '1AB385'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B0245'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B1035'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B127B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B1404'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B2F11'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B3162'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1B659D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1C1208'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1C1E13'
}
{
'name': 'Persian PI:NAME:<NAME>END_PI'
'hex': '1C39BB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1C402E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1C7C7D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1D6142'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1E0F04'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1E1609'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1E1708'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '1E385B'
}
{
'name': 'Te Papa Green'
'hex': '1E433C'
}
{
'name': 'Dodger Blue'
'hex': '1E90FF'
}
{
'name': 'Eastern Blue'
'hex': '1E9AB0'
}
{
'name': 'Night Rider'
'hex': '1F120F'
}
{
'name': 'Java'
'hex': '1FC2C2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '20208D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '202E54'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '204852'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '211A0E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '220878'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '228B22'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '233418'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '240A40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '240C02'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '242A1D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '242E16'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '24500F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '251607'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '251706'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '251F4F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '25272C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '25311C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2596D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '260368'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '26056A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '261105'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '261414'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '262335'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '26283B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '273A81'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '27504B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '278A5B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '281E15'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '283A77'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '286ACD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '290C5E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '292130'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '292319'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '292937'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '297B9A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '29AB87'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2A0359'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2A140E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2A2630'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2A380B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2A52BE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2B0202'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2B194F'
}
{
'name': 'Heavy Metal'
'hex': '2B3228'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2C0E8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2C1632'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2C2133'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2C8C84'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2D2510'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2D383A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2D569B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2E0329'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2E1905'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2E3222'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2E3F62'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2E8B57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2EBFD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2F270E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2F3CB3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2F519E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2F5A57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '2F6168'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '300529'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '301F1E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '302A0F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '304B6A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '30D5C8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '311C17'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '314459'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '315BA1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '31728D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '317D82'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '32127A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '32293A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '323232'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '325D52'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '327C14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '327DA0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '33036B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '33292F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '33CC99'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '341515'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '350036'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '350E42'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '350E57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '353542'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '354E8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '363050'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '363534'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '363C0D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '36747D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '368716'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '370202'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '371D09'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '37290E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '373021'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '377475'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '380474'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '381A51'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '383533'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '384555'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '384910'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '394851'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '396413'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3A0020'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3A2010'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3A2A6A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3A686C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3A6A47'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3AB09E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B000B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B0910'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B1F1F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B2820'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B7A57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3B91B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C0878'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C1206'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C1F76'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C2005'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C3910'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C4151'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C4443'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3C493A'
}
{
'name': 'PI:NAME:<NAME>END_PI '
'hex': '3D0C02'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3D2B1F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3D7D52'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3E0480'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3E1C14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3E2B23'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3E2C1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3E3A44'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3EABBF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F2109'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F2500'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F3002'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F307F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F4C3A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F583B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3F5D53'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3FC1AA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '3FFF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '401801'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '40291D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '403B38'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '403D19'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '405169'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '40826D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '40A860'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '410056'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '411F10'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '412010'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '413C37'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '414257'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '414C7D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4169E1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '41AA78'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '420303'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '423921'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '427977'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '431560'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '433120'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '433E37'
}
{
'name': 'RPI:NAME:<NAME>END_PI'
'hex': '434C59'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '436A0D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '44012D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '441D00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '444954'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '454936'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '456CAC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '45B1E8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '460B41'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '462425'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '465945'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4682B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '480404'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '480607'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '480656'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '481C1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '483131'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '483C32'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '49170C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '492615'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '49371B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '495400'
}
{
'name': 'PI:NAME:<NAME>END_PIouPI:NAME:<NAME>END_PI'
'hex': '496679'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '497183'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A2A04'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A3004'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A3C30'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A4244'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A444B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4A4E5A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4B0082'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4B5D52'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4C3024'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4C4F56'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D0135'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D0A18'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D1E01'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D282D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D282E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D3833'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D3D14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D400F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4D5328'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E0606'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E2A5A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E3B41'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E420C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E4562'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E6649'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4E7F9E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4EABD1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4F1C70'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4F2398'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4F69C6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4F7942'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4F9D5D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '4FA83D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '504351'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '507096'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '507672'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '50C878'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '514649'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '516E3D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '517C66'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '51808F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '52001F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '520C17'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '523C94'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '533455'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '534491'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '53824B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '541012'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '544333'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '54534D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '549019'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '55280C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '555B10'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '556D56'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5590D9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '56B4BE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '578363'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '583401'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '585562'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '587156'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '589AAF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '591D35'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '592804'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '593737'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '594433'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5A6E9C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5A87A0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5B3013'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5C0120'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5C0536'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5C2E01'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5C5D75'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5D1E0F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5D4C51'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5D5C58'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5D5E37'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5D7747'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5DA19F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5E483E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5E5D3B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5F3D26'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5F5F6E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5F6672'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5FA777'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '5FB3AC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '604913'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '605B73'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '606E68'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6093D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '612718'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '614051'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '615D30'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '61845F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '622F30'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '623F2D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '624E9A'
}
{
'name': 'West Coast'
'hex': '625119'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '626649'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '639A8F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '63B76C'
}
{
'name': 'Blue VPI:NAME:<NAME>END_PIlet'
'hex': '6456B7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '646077'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '646463'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '646A54'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '646E75'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6495ED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '64CCDB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '65000B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '651A14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '652DC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '657220'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '65745D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '65869F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '660045'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '660099'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '66023C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '661010'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '66B58F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '66FF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '66FF66'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '67032D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '675FA6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '676662'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '678975'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '67A712'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '683600'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '685558'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '685E6E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '692545'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '692D54'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '695F62'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '697E9A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6A442E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6A5D1B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6A6051'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B2A14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B3FA0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B4E31'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B5755'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B8BA2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6B8E23'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6C3082'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6CDAE7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6D0101'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6D5E54'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6D6C6C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6D9292'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6D92A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E0902'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E1D14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E4826'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E4B26'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E6D57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6E7783'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6F440C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6F6A61'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6F8E63'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6F9D02'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '6FD0C5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '701C1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '704214'
}
{
'name': 'PI:NAME:<NAME>END_PIronze'
'hex': '704A07'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '704F50'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '706555'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '708090'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '711A00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '71291D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '714693'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '714AB2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '715D47'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '716338'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '716B56'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '716E10'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '717486'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '718080'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '71D9E2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '72010F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '724A2F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '726D4E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '727B89'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '731E8F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '734A12'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '736C9F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '736D58'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '737829'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '738678'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '74640D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '747D63'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '747D83'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '748881'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '749378'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '74C365'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '755A57'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7563A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '76395D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7666C6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '76BD17'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '76D7EA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '770F05'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '771F1F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '773F1A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '776F61'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '778120'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '779E86'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '77DD77'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '780109'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '782D19'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '782F16'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '78866B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '788A25'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '788BBA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '78A39C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '795D4C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '796878'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '796989'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '796A78'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '796D62'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '79DEEC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7A013A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7A58C1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7A7A7A'
}
{
'name': 'PI:NAME:<NAME>END_PIild Blue PI:NAME:<NAME>END_PI'
'hex': '7A89B8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7AC488'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B3801'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B3F00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B6608'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B7874'
}
{
'name': 'PI:NAME:<NAME>END_PI '
'hex': '7B7C94'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B8265'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7B9F80'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7BA05B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C1C05'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C7631'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C778A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C7B7A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C7B82'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7C881A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7CA1A6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7CB0A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7CB7BB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7D2C14'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7DA98D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7DC8F7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7DD8C6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7E3A15'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7F1734'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7F3A02'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7F626D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7F7589'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7F76D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7FFF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '7FFFD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '800000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '800B47'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '801818'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '80341F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '803790'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '80461B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '807E79'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '808000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '808080'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '80B3AE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '80B3C4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '80CCEA'
}
{
'name': 'NPI:NAME:<NAME>END_PI'
'hex': '81422C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '816E71'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '817377'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '819885'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '826F65'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '828685'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '828F72'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '831923'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '837050'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '83AA5D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '83D0C6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '843179'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '84A0A0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8581D9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '858470'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '859FAF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '85C4CC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '860111'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '863C3C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '86483C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '864D1E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '86560A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '868974'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '86949F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '871550'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '87756E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '877C7B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '878D91'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '87AB39'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '885342'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '886221'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '888387'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '888D65'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '893456'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '893843'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '894367'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '897D6D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8A3324'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8A73D6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8A8360'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8A8389'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8A8F8A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8AB9F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B00FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B0723'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B6B0B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B8470'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B847E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B8680'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B9C90'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8B9FEE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8BA690'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8BA9A5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8BE6D8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8C055E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8C472F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8C5738'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8C6495'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D0226'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D3D38'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D3F3F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D7662'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D8974'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8D90A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8DA8CC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8E0000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8E4D1E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8E6F70'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8E775E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8E8190'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8EABC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8F021C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8F3E33'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8F4B0E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8F8176'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '8FD6B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '900020'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '901E1E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '907874'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '907B71'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '908D39'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '92000A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '924321'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '926F5B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '928573'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '928590'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9370DB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '93CCEA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '93DFB8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '944747'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '948771'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '950015'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '956387'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '959396'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '960018'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '964B00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '967059'
}
{
'name': 'PI:NAME:<NAME>END_PI\'PI:NAME:<NAME>END_PI'
'hex': '9678B6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '967BB6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '96A8A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '96BBAB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '97605D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9771B5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '97CD2D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '983D61'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9874D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '98777B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '98811B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '988D77'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '98FF98'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '990066'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '991199'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '991613'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '991B07'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '996666'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9966CC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '997A8D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9999CC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9A3820'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9A6E61'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9A9577'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9AB973'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9AC2B8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9B4703'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9B9E8F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9C3336'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9D5616'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9DACB7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9DC209'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9DE093'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9DE5FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9E5302'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9E5B40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9EA587'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9EA91F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9EB1CD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9EDEE0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9F381D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9F821C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9F9F9C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9FA0B1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9FD7D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': '9FDD8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A02712'
}
{
'name': 'BPI:NAME:<NAME>END_PI'
'hex': 'A1750D'
}
{
'name': 'Hit PI:NAME:<NAME>END_PI'
'hex': 'A1ADB5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A1C50A'
}
{
'name': 'API:NAME:<NAME>END_PI Island'
'hex': 'A1DAD7'
}
{
'name': 'Water PI:NAME:<NAME>END_PI'
'hex': 'A1E9DE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A2006D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A23B6C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A26645'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A2AAB3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A2AEAB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A3807B'
}
{
'name': 'Amethyst PI:NAME:<NAME>END_PImoke'
'hex': 'A397B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A3E3ED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A4A49D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A4A6D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A4AF6E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A50B5E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A59B91'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A5CB0C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A62F20'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A65529'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A68B5B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A69279'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A6A29A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A72525'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A7882C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A85307'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A86515'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A86B6B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8989B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A899E6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8A589'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8AE9C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8AF8E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8BD9F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A8E3BD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9A491'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9ACB6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9B2C3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9B497'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9BDBF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'A9BEF2'
}
{
'name': 'Opal'
'hex': 'A9C6C2'
}
{
'name': 'Night ShPI:NAME:<NAME>END_PI'
'hex': 'AA375A'
}
{
'name': 'Fire'
'hex': 'AA4203'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AA8B5B'
}
{
'name': 'Sandal'
'hex': 'AA8D6F'
}
{
'name': 'Shady Lady'
'hex': 'AAA5A9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AAA9CD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AAABB7'
}
{
'name': 'PI:NAME:<NAME>END_PI St Blue'
'hex': 'AAD6E6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AAF0D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AB0563'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AB3472'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AB917A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ABA0D9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ABA196'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AC8A56'
}
{
'name': 'East PI:NAME:<NAME>END_PI'
'hex': 'AC91CE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AC9E22'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACA494'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACA586'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACA59F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACACAC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACB78E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACCBB1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACDD4D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ACE1AF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AD781B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ADBED1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ADDFAD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ADE6C4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ADFF2F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AE4560'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AE6020'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AE809E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF4035'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF4D43'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF593E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF8751'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF8F2C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AF9F1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AFA09E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AFB1B8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'AFBDD9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B04C6A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B05D54'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B05E81'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B06608'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B09A95'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B0E0E6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B0E313'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B10000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B14A0B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B1610B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B16D52'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B19461'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B1E2C1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B1F4E7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B20931'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B2A1EA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B32D29'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B35213'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B38007'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B3AF95'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B3C110'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B43332'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B44668'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B4CFD3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B57281'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B57EDC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B5A27F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B5B35C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B5D2CE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B5ECDF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B6316C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B69D98'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B6B095'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B6BAA4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B6D1EA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B6D3BF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7410E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B78E5C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7A214'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7A458'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7B1B1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7C3D0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B7F0BE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B81104'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B87333'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B8B56A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B8C1B1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B8C25D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B8E0F9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B94E48'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B95140'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B98D28'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B9C46A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'B9C8AC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BA0101'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BA450C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BA6F1E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BA7F03'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BAB1A2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BAC7C9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BAEEF9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BB3385'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BB8983'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BBD009'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BBD7C1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BCC9C2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BD5E2E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BD978E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDB1A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDB2A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDB3C7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDBBD7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDBDC6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDC8B3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDC9CE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BDEDFD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BEA6C3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BEB5B7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BEDE0D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BF5500'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFB8B0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFBED8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFC1C2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFC921'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFDBE2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'BFFF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C02B18'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C04737'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C08081'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C0C0C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C0D3B9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C0D8B6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1440E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C154C1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1A004'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1B7A4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1BAB0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1BECD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1D7B0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C1F07C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C26B03'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C2955D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C2BDB6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C2CAC4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C2E8E5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C32148'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3B091'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3BFC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3C3BD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3CDE6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3D1D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C3DDF9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C41E3A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C45655'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C45719'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C4C4BC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C4D0B0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C4F4EB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C54B8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C59922'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C5994B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C5DBCA'
}
{
'name': 'Yellow Green'
'hex': 'C5E17A'
}
{
'name': 'Brick Red'
'hex': 'C62D42'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C6726B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C69191'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C6A84B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C6C3B5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C6C8BD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C6E610'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7031E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C71585'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7BCA2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7C1FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7C4BF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7C9D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7CD90'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C7DDE5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C88A65'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C8A2C8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C8A528'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C8AABF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C8B568'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C8E3D7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C96323'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C99415'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9A0DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9B29B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9B35B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9B93B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9C0BB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9D9D2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9FFA2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'C9FFE5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CA3435'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CABB48'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CADCD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CAE00D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CAE6DA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CB8FA9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CBCAB6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CBD3B0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CBDBD6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CC3333'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CC5500'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CC7722'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CC8899'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CCCAA8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CCCCFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CCFF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CD5700'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CD5C5C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CD8429'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CDF4FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CEB98F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CEBABA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CEC291'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CEC7A7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFA39D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFB53B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFDCCF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFE5D2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFF9F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'CFFAF4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D05F04'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D06DA1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D07D12'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D0BEF8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D0C0E5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D0F0C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D18F1B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D1BEA8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D1C6B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D1D2CA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D1D2DD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D1E231'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D2691E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D27D46'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D29EAA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D2B48C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D2DA97'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D2F6DE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D2F8B0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D3CBBA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D3CDC5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D47494'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4B6AF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4BF8D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4C4A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4CD16'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4D7D9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4DFE2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D4E2FC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D54600'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D591A4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D59A6F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D5D195'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D5F6E3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D69188'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D6C562'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D6CEF6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D6D6D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D6FFDB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D7837F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D7C498'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D7D0FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D84437'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D87C63'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D8BFD8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D8C2D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D8FCFA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D94972'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D99376'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D9B99B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D9D6CF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D9DCC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D9E4F5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'D9F7FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA3287'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA5B38'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA6304'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA6A41'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA70D6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DA8A67'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DAA520'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DAECD6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DAF4F0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DAFAFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DB5079'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DB9690'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DB995E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DBDBDB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DBFFF8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DC143C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DC4333'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCB20C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCB4BC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCD747'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCD9D2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCDDCC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCEDB4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DCF0EA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DDD6D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DDF9F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DE3163'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DE6360'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DEA681'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DEBA13'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DEC196'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DECBC6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DED4A4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DED717'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DEE5C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DEF5FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DF73FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DFBE6F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DFCD6F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DFCFDB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DFECDA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'DFFF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E0B0FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E0B646'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E0B974'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E0C095'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E0FFFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E16865'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E1BC64'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E1C0C8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E1E6D6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E1EAD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E1F6E8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E25465'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E2725B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E28913'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E292C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E29418'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E29CD2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E2D8ED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E2EBED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E2F3EC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E30B5C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E32636'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E34234'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E3BEBE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E3F5E1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E3F988'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E47698'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E49B0F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4C2D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4CFDE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4D1C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4D422'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4D5B7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4D69B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4F6E7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E4FFD1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E52B50'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5841B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5CCC9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5D7BD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5D8AF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5E0E1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5E5E5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E5F9F6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E64E03'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6BE8A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6BEA5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6D7B9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6E4D4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6F2EA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6F8F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6FFE9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E6FFFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E77200'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7730A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E79F8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E79FC4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7BCB4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7BF05'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7CD8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7ECE6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7F8FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E7FEFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E89928'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8B9B3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8E0D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8EBE0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8F1D4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8F2EB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E8F5F2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E96E00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E97451'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E97C07'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E9CECD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E9D75A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E9E3E3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E9F8ED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'E9FFFD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EA88A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAAE69'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAB33B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAC674'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EADAB8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAE8D4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAF6EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAF6FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAF9F5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EAFFFE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EB9373'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EBC2AF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECA927'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECC54E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECC7EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECCDB9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECE090'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECEBBD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECEBCE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ECF245'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ED0A3F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ED7A1C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ED9121'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'ED989E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDB381'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDC9AF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDCDAB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDDCB1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDEA99'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDF5DD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDF5F5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDF6FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDF9F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EDFC84'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EE82EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEC1BE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EED794'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EED9C4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEDC82'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEDEDA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEE3AD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEEEE8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEEF78'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEF0C8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEF0F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEF3C3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEF4DE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEF6F7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEFDFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEFF9A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EEFFE2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EF863F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EFEFEF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'EFF2F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F091A9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0D52D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0DB7D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0DC82'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0E2EC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0E68C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0EEFD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0EEFF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0F8FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F0FCEA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F18200'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F19BAB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1E788'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1E9D2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1E9FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1EEC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1F1F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1F7F2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1FFAD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F1FFC8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F2552A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F28500'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F2C3B2'
}
{
'name': 'Concrete'
'hex': 'F2F2F2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F2FAFA'
}
{
'name': 'PomePI:NAME:<NAME>END_PI'
'hex': 'F34723'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3AD16'
}
{
'name': 'New PI:NAME:<NAME>END_PI'
'hex': 'F3D69D'
}
{
'name': 'Vanilla PI:NAME:<NAME>END_PI'
'hex': 'F3D9DF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3E7BB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3E9E5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3EDCF'
}
{
'name': 'CanPI:NAME:<NAME>END_PI'
'hex': 'F3FB62'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3FBD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F3FFD8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F400A1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4A460'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4C430'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4D81C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4EBD3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4F2EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4F4F4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F4F8FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F57584'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5C85C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5C999'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5D5A0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5DEB3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5E7A2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5E7E2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5E9D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5EDEF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5F3E5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5F5DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F5FB3D'
}
{
'name': 'Australian MPI:NAME:<NAME>END_PI'
'hex': 'F5FFBE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F64A8A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F653A6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F6A4C9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F6F0E6'
}
{
'name': 'Black PI:NAME:<NAME>END_PI'
'hex': 'F6F7F7'
}
{
'name': 'Spring Sun'
'hex': 'F6FFDC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7468A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F77703'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F77FBE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7B668'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7C8DA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7DBE6'
}
{
'name': 'PI:NAME:<NAME>END_PI Spanish White'
'hex': 'F7F2E1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7F5FA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F7FAF7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8B853'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8C3DF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8D9E9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8DB9D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8DD5C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8E4BF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F0E8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F4FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F6F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F7DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F7FC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F8F7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8F99C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8FACD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F8FDD3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F95A61'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9BF58'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9E0ED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9E4BC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9E663'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9EAF3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9F8E4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9FF8B'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'F9FFF6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FA7814'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FA9D5A'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAD3A2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FADFAD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAE600'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAEAB9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAECCC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAF0E6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAF3F0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAF7D6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAFAFA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAFDE4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FAFFA4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FB607F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FB8989'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBA0E3'
}
{
'name': 'PI:NAME:<NAME>END_PIthorn'
'hex': 'FBA129'
}
{
'name': 'Sun'
'hex': 'FBAC13'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBAED2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBB2A3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBBEDA'
}
{
'name': 'PI:NAME:<NAME>END_PI Rose'
'hex': 'FBCCE7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBCEB1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBE7B2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBE870'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBE96C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBEA8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBEC5D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBF9F9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FBFFBA'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FC0FC0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FC80A5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FC9C1D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCC01E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCD667'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCD917'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCDA98'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCF4D0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCF4DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCF8F7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCFBF3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCFEDA'
}
{
'name': 'PI:NAME:<NAME>END_PIory'
'hex': 'FCFFE7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FCFFF9'
}
{
'name': 'Torch Red'
'hex': 'FD0E35'
}
{
'name': 'Wild Watermelon'
'hex': 'FD5B78'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FD7B33'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FD7C07'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FD9FA2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDD5B1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDD7E4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDE1DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDE295'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDE910'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDF5E6'
}
{
'name': 'PI:NAME:<NAME>END_PI Colonial PI:NAME:<NAME>END_PI'
'hex': 'FDF6D3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDF7AD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDFEB8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FDFFD5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FE28A2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FE4C40'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FE6F5E'
}
{
'name': 'California'
'hex': 'FE9D04'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEA904'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEBAAD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FED33C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FED85D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEDB8D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEE5AC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEEBF3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEEFCE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF0EC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF2C7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF3D8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF4CC'
}
{
'name': 'PI:NAME:<NAME>END_PI Spanish PI:NAME:<NAME>END_PI'
'hex': 'FEF4DB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF4F8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF5F1'
}
{
'name': 'PI:NAME:<NAME>END_PI DPI:NAME:<NAME>END_PI'
'hex': 'FEF7DE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF8E2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF8FF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FEF9E3'
}
{
'name': 'Orange PI:NAME:<NAME>END_PI'
'hex': 'FEFCED'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FF0000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FF007F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FF00CC'
}
{
'name': 'Magenta / Fuchsia'
'hex': 'FF00FF'
}
{
'name': 'Scarlet'
'hex': 'FF2400'
}
{
'name': 'Wild Strawberry'
'hex': 'FF3399'
}
{
'name': 'Razzle Dazzle Rose'
'hex': 'FF33CC'
}
{
'name': 'Radical Red'
'hex': 'FF355E'
}
{
'name': 'Red Orange'
'hex': 'FF3F34'
}
{
'name': 'Coral Red'
'hex': 'FF4040'
}
{
'name': 'Vermilion'
'hex': 'FF4D00'
}
{
'name': 'International Orange'
'hex': 'FF4F00'
}
{
'name': 'Outrageous Orange'
'hex': 'FF6037'
}
{
'name': 'Blaze Orange'
'hex': 'FF6600'
}
{
'name': 'Pink Flamingo'
'hex': 'FF66FF'
}
{
'name': 'Orange'
'hex': 'FF681F'
}
{
'name': 'Hot Pink'
'hex': 'FF69B4'
}
{
'name': 'Persimmon'
'hex': 'FF6B53'
}
{
'name': 'Blush Pink'
'hex': 'FF6FFF'
}
{
'name': 'Burning Orange'
'hex': 'FF7034'
}
{
'name': 'Pumpkin'
'hex': 'FF7518'
}
{
'name': 'Flamenco'
'hex': 'FF7D07'
}
{
'name': 'Flush Orange'
'hex': 'FF7F00'
}
{
'name': 'Coral'
'hex': 'FF7F50'
}
{
'name': 'Salmon'
'hex': 'FF8C69'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FF9000'
}
{
'name': 'West Side'
'hex': 'FF910F'
}
{
'name': 'Pink Salmon'
'hex': 'FF91A4'
}
{
'name': 'Neon Carrot'
'hex': 'FF9933'
}
{
'name': 'Atomic Tangerine'
'hex': 'FF9966'
}
{
'name': 'Vivid Tangerine'
'hex': 'FF9980'
}
{
'name': 'Sunshade'
'hex': 'FF9E2C'
}
{
'name': 'Orange Peel'
'hex': 'FFA000'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFA194'
}
{
'name': 'Web Orange'
'hex': 'FFA500'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFA6C9'
}
{
'name': 'Hit PPI:NAME:<NAME>END_PI'
'hex': 'FFAB81'
}
{
'name': 'Yellow OPI:NAME:<NAME>END_PI'
'hex': 'FFAE42'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB0AC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB1B3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB31F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB555'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB7D5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFB97B'
}
{
'name': 'Selective Yellow'
'hex': 'FFBA00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFBD5F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFBF00'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFC0A8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFC0CB'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFC3C0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFC901'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFCBA4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFCC33'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFCC5C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFCC99'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFCD8C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFD1DC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFD2B7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFD38C'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFD700'
}
{
'name': 'PI:NAME:<NAME>END_PI bus Yellow'
'hex': 'FFD800'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFD8D9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDB58'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDCD6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDDAF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDDCD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDDCF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDDF4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDEAD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFDEB3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE1DF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE1F2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE2C5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE5A0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE5B4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE6C7'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFE772'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEAC8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEAD4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEC13'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEDBC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEED8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEFA1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEFC1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEFD5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFEFEC'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF0DB'
}
{
'name': 'LavPI:NAME:<NAME>END_PI'
'hex': 'FFF0F5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF14F'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF1B5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF1D8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF1EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF1F9'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF39D'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF3F1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF46E'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF4CE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF4DD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF4E0'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF4E8'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF4F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF5EE'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF5F3'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF6D4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF6DF'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF6F5'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF8D1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF9E2'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFF9E6'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFFACD'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFFAF4'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFFBDC'
}
{
'name': 'Soapstone'
'hex': 'FFFBF9'
}
{
'name': 'Witch Haze'
'hex': 'FFFC99'
}
{
'name': 'BPI:NAME:<NAME>END_PIy White'
'hex': 'FFFCEA'
}
{
'name': 'Island Spice'
'hex': 'FFFCEE'
}
{
'name': 'Cream'
'hex': 'FFFDD0'
}
{
'name': 'Chilean Heath'
'hex': 'FFFDE6'
}
{
'name': 'Travertine'
'hex': 'FFFDE8'
}
{
'name': 'Orchid White'
'hex': 'FFFDF3'
}
{
'name': 'Quarter Pearl Lusta'
'hex': 'FFFDF4'
}
{
'name': 'Half and Half'
'hex': 'FFFEE1'
}
{
'name': 'PI:NAME:<NAME>END_PI'
'hex': 'FFFEEC'
}
{
'name': 'Rice Cake'
'hex': 'FFFEF0'
}
{
'name': 'Black White'
'hex': 'FFFEF6'
}
{
'name': 'Romance'
'hex': 'FFFEFD'
}
{
'name': 'Yellow'
'hex': 'FFFF00'
}
{
'name': 'Laser Lemon'
'hex': 'FFFF66'
}
{
'name': 'Pale Canary'
'hex': 'FFFF99'
}
{
'name': 'Portafino'
'hex': 'FFFFB4'
}
{
'name': 'PI:NAME:<NAME>END_PIory'
'hex': 'FFFFF0'
}
{
'name': 'White'
'hex': 'FFFFFF'
}
]
|
[
{
"context": "ject-talk-subject\" params={owner: ownerName, name: name, id: @props.subject.id} className=\"talk standard-",
"end": 5489,
"score": 0.9705287218093872,
"start": 5485,
"tag": "NAME",
"value": "name"
}
] | app/classifier/index.cjsx | camallen/Panoptes-Front-End | 0 | React = require 'react'
ChangeListener = require '../components/change-listener'
SubjectAnnotator = require './subject-annotator'
ClassificationSummary = require './classification-summary'
{Link} = require '@edpaget/react-router'
tasks = require './tasks'
{getSessionID} = require '../lib/session'
preloadSubject = require '../lib/preload-subject'
unless process.env.NODE_ENV is 'production'
mockData = require './mock-data'
Classifier = React.createClass
displayName: 'Classifier'
getDefaultProps: ->
user: null
if mockData?
{workflow, subject, classification} = mockData
workflow: workflow ? null
subject: subject ? null
classification: classification ? null
onLoad: Function.prototype
getInitialState: ->
subjectLoading: false
showingExpertClassification: false
selectedExpertAnnotation: -1
componentDidMount: ->
@loadSubject @props.subject
@prepareToClassify @props.classification
componentWillReceiveProps: (nextProps) ->
if nextProps.subject isnt @props.subject
@loadSubject subject
if nextProps.classification isnt @props.classification
@prepareToClassify nextProps.classification
loadSubject: (subject) ->
@setState subjectLoading: true
preloadSubject subject
.then =>
if @props.subject is subject # The subject could have changed while we were loading.
@setState subjectLoading: false
@props.onLoad?()
prepareToClassify: (classification) ->
classification.annotations ?= []
if classification.annotations.length is 0
@addAnnotationForTask classification, @props.workflow.first_task
render: ->
<ChangeListener target={@props.classification}>{=>
if @state.showingExpertClassification
currentClassification = @props.subject.expert_classification_data
else
currentClassification = @props.classification
unless @props.classification.completed
currentAnnotation = currentClassification.annotations[currentClassification.annotations.length - 1]
currentTask = @props.workflow.tasks[currentAnnotation?.task]
# This is just easy access for debugging.
window.classification = currentClassification
<div className="classifier">
<SubjectAnnotator
user={@props.user}
project={@props.project}
subject={@props.subject}
workflow={@props.workflow}
classification={currentClassification}
annotation={currentAnnotation}
onLoad={@handleSubjectImageLoad}
/>
<div className="task-area">
{if currentTask?
@renderTask currentClassification, currentAnnotation, currentTask
else # Classification is complete.
@renderSummary currentClassification}
</div>
</div>
}</ChangeListener>
renderTask: (classification, annotation, task) ->
TaskComponent = tasks[task.type]
# Should we disabled the "Back" button?
onFirstAnnotation = classification.annotations.indexOf(annotation) is 0
# Should we disable the "Next" or "Done" buttons?
if TaskComponent.isAnnotationComplete?
waitingForAnswer = not TaskComponent.isAnnotationComplete task, annotation
# Each answer of a single-answer task can have its own `next` key to override the task's.
if TaskComponent is tasks.single
currentAnswer = task.answers?[annotation.value]
nextTaskKey = currentAnswer?.next
else
nextTaskKey = task.next
unless @props.workflow.tasks[nextTaskKey]?
nextTaskKey = ''
# TODO: Actually disable things that should be.
# For now we'll just make them non-mousable.
disabledStyle =
opacity: 0.5
pointerEvents: 'none'
<div className="task-container" style={disabledStyle if @state.subjectLoading}>
<TaskComponent task={task} annotation={annotation} onChange={@updateAnnotations.bind this, classification} />
<hr />
<nav className="task-nav">
<button type="button" className="back minor-button" disabled={onFirstAnnotation} onClick={@destroyCurrentAnnotation}>Back</button>
{if nextTaskKey
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@addAnnotationForTask.bind this, classification, nextTaskKey}>Next</button>
else
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@completeClassification}>Done</button>}
</nav>
</div>
renderSummary: (classification) ->
<div>
Thanks!
{if @props.subject.expert_classification_data?
<div className="has-expert-classification">
Expert classification available.
{if @state.showingExpertClassification
<button type="button" onClick={@toggleExpertClassification.bind this, false}>Hide</button>
else
<button type="button" onClick={@toggleExpertClassification.bind this, true}>Show</button>}
</div>}
{if @state.showingExpertClassification
'Expert classification:'
else
'Your classification:'}
<ClassificationSummary workflow={@props.workflow} classification={classification} />
<hr />
<nav className="task-nav">
{if @props.owner? and @props.project?
[ownerName, name] = @props.project.slug.split('/')
<Link onClick={@props.onClickNext} to="project-talk-subject" params={owner: ownerName, name: name, id: @props.subject.id} className="talk standard-button">Talk</Link>}
<button type="button" className="continue major-button" onClick={@props.onClickNext}>Next</button>
</nav>
</div>
# Whenever a subject image is loaded in the annotator, record its size at that time.
handleSubjectImageLoad: (e, frameIndex) ->
{naturalWidth, naturalHeight, clientWidth, clientHeight} = e.target
changes = {}
changes["metadata.subject_dimensions.#{frameIndex}"] = {naturalWidth, naturalHeight, clientWidth, clientHeight}
@props.classification.update changes
# This is passed as a generic change handler to the tasks
updateAnnotations: ->
@props.classification.update 'annotations'
# Next (or start):
addAnnotationForTask: (classification, taskKey) ->
taskDescription = @props.workflow.tasks[taskKey]
annotation = tasks[taskDescription.type].getDefaultAnnotation()
annotation.task = taskKey
classification.annotations.push annotation
classification.update 'annotations'
# Back up:
destroyCurrentAnnotation: ->
@props.classification.annotations.pop()
@props.classification.update 'annotations'
completeClassification: ->
@props.classification.update
completed: true
'metadata.session': getSessionID().id
'metadata.finished_at': (new Date).toISOString()
'metadata.viewport':
width: innerWidth
height: innerHeight
@props.onComplete?()
toggleExpertClassification: (value) ->
@setState showingExpertClassification: value
module.exports = React.createClass
displayName: 'ClassifierWrapper'
getDefaultProps: ->
user: null
classification: mockData?.classification ? {}
onLoad: Function.prototype
onComplete: Function.prototype
onClickNext: Function.prototype
getInitialState: ->
workflow: null
subject: null
componentDidMount: ->
@loadClassification @props.classification
componentWillReceiveProps: (nextProps) ->
unless nextProps.classification is @props.classification
@loadClassification nextProps.classification
loadClassification: (classification) ->
@setState
workflow: null
subject: null
# TODO: These underscored references are temporary stopgaps.
Promise.resolve(classification._workflow ? classification.get 'workflow').then (workflow) =>
@setState {workflow}
Promise.resolve(classification._subjects ? classification.get 'subjects').then ([subject]) =>
# We'll only handle one subject per classification right now.
# TODO: Support multi-subject classifications in the future.
@setState {subject}
render: ->
if @state.workflow? and @state.subject?
<Classifier {...@props} workflow={@state.workflow} subject={@state.subject} />
else
<span>Loading classifier...</span>
| 24921 | React = require 'react'
ChangeListener = require '../components/change-listener'
SubjectAnnotator = require './subject-annotator'
ClassificationSummary = require './classification-summary'
{Link} = require '@edpaget/react-router'
tasks = require './tasks'
{getSessionID} = require '../lib/session'
preloadSubject = require '../lib/preload-subject'
unless process.env.NODE_ENV is 'production'
mockData = require './mock-data'
Classifier = React.createClass
displayName: 'Classifier'
getDefaultProps: ->
user: null
if mockData?
{workflow, subject, classification} = mockData
workflow: workflow ? null
subject: subject ? null
classification: classification ? null
onLoad: Function.prototype
getInitialState: ->
subjectLoading: false
showingExpertClassification: false
selectedExpertAnnotation: -1
componentDidMount: ->
@loadSubject @props.subject
@prepareToClassify @props.classification
componentWillReceiveProps: (nextProps) ->
if nextProps.subject isnt @props.subject
@loadSubject subject
if nextProps.classification isnt @props.classification
@prepareToClassify nextProps.classification
loadSubject: (subject) ->
@setState subjectLoading: true
preloadSubject subject
.then =>
if @props.subject is subject # The subject could have changed while we were loading.
@setState subjectLoading: false
@props.onLoad?()
prepareToClassify: (classification) ->
classification.annotations ?= []
if classification.annotations.length is 0
@addAnnotationForTask classification, @props.workflow.first_task
render: ->
<ChangeListener target={@props.classification}>{=>
if @state.showingExpertClassification
currentClassification = @props.subject.expert_classification_data
else
currentClassification = @props.classification
unless @props.classification.completed
currentAnnotation = currentClassification.annotations[currentClassification.annotations.length - 1]
currentTask = @props.workflow.tasks[currentAnnotation?.task]
# This is just easy access for debugging.
window.classification = currentClassification
<div className="classifier">
<SubjectAnnotator
user={@props.user}
project={@props.project}
subject={@props.subject}
workflow={@props.workflow}
classification={currentClassification}
annotation={currentAnnotation}
onLoad={@handleSubjectImageLoad}
/>
<div className="task-area">
{if currentTask?
@renderTask currentClassification, currentAnnotation, currentTask
else # Classification is complete.
@renderSummary currentClassification}
</div>
</div>
}</ChangeListener>
renderTask: (classification, annotation, task) ->
TaskComponent = tasks[task.type]
# Should we disabled the "Back" button?
onFirstAnnotation = classification.annotations.indexOf(annotation) is 0
# Should we disable the "Next" or "Done" buttons?
if TaskComponent.isAnnotationComplete?
waitingForAnswer = not TaskComponent.isAnnotationComplete task, annotation
# Each answer of a single-answer task can have its own `next` key to override the task's.
if TaskComponent is tasks.single
currentAnswer = task.answers?[annotation.value]
nextTaskKey = currentAnswer?.next
else
nextTaskKey = task.next
unless @props.workflow.tasks[nextTaskKey]?
nextTaskKey = ''
# TODO: Actually disable things that should be.
# For now we'll just make them non-mousable.
disabledStyle =
opacity: 0.5
pointerEvents: 'none'
<div className="task-container" style={disabledStyle if @state.subjectLoading}>
<TaskComponent task={task} annotation={annotation} onChange={@updateAnnotations.bind this, classification} />
<hr />
<nav className="task-nav">
<button type="button" className="back minor-button" disabled={onFirstAnnotation} onClick={@destroyCurrentAnnotation}>Back</button>
{if nextTaskKey
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@addAnnotationForTask.bind this, classification, nextTaskKey}>Next</button>
else
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@completeClassification}>Done</button>}
</nav>
</div>
renderSummary: (classification) ->
<div>
Thanks!
{if @props.subject.expert_classification_data?
<div className="has-expert-classification">
Expert classification available.
{if @state.showingExpertClassification
<button type="button" onClick={@toggleExpertClassification.bind this, false}>Hide</button>
else
<button type="button" onClick={@toggleExpertClassification.bind this, true}>Show</button>}
</div>}
{if @state.showingExpertClassification
'Expert classification:'
else
'Your classification:'}
<ClassificationSummary workflow={@props.workflow} classification={classification} />
<hr />
<nav className="task-nav">
{if @props.owner? and @props.project?
[ownerName, name] = @props.project.slug.split('/')
<Link onClick={@props.onClickNext} to="project-talk-subject" params={owner: ownerName, name: <NAME>, id: @props.subject.id} className="talk standard-button">Talk</Link>}
<button type="button" className="continue major-button" onClick={@props.onClickNext}>Next</button>
</nav>
</div>
# Whenever a subject image is loaded in the annotator, record its size at that time.
handleSubjectImageLoad: (e, frameIndex) ->
{naturalWidth, naturalHeight, clientWidth, clientHeight} = e.target
changes = {}
changes["metadata.subject_dimensions.#{frameIndex}"] = {naturalWidth, naturalHeight, clientWidth, clientHeight}
@props.classification.update changes
# This is passed as a generic change handler to the tasks
updateAnnotations: ->
@props.classification.update 'annotations'
# Next (or start):
addAnnotationForTask: (classification, taskKey) ->
taskDescription = @props.workflow.tasks[taskKey]
annotation = tasks[taskDescription.type].getDefaultAnnotation()
annotation.task = taskKey
classification.annotations.push annotation
classification.update 'annotations'
# Back up:
destroyCurrentAnnotation: ->
@props.classification.annotations.pop()
@props.classification.update 'annotations'
completeClassification: ->
@props.classification.update
completed: true
'metadata.session': getSessionID().id
'metadata.finished_at': (new Date).toISOString()
'metadata.viewport':
width: innerWidth
height: innerHeight
@props.onComplete?()
toggleExpertClassification: (value) ->
@setState showingExpertClassification: value
module.exports = React.createClass
displayName: 'ClassifierWrapper'
getDefaultProps: ->
user: null
classification: mockData?.classification ? {}
onLoad: Function.prototype
onComplete: Function.prototype
onClickNext: Function.prototype
getInitialState: ->
workflow: null
subject: null
componentDidMount: ->
@loadClassification @props.classification
componentWillReceiveProps: (nextProps) ->
unless nextProps.classification is @props.classification
@loadClassification nextProps.classification
loadClassification: (classification) ->
@setState
workflow: null
subject: null
# TODO: These underscored references are temporary stopgaps.
Promise.resolve(classification._workflow ? classification.get 'workflow').then (workflow) =>
@setState {workflow}
Promise.resolve(classification._subjects ? classification.get 'subjects').then ([subject]) =>
# We'll only handle one subject per classification right now.
# TODO: Support multi-subject classifications in the future.
@setState {subject}
render: ->
if @state.workflow? and @state.subject?
<Classifier {...@props} workflow={@state.workflow} subject={@state.subject} />
else
<span>Loading classifier...</span>
| true | React = require 'react'
ChangeListener = require '../components/change-listener'
SubjectAnnotator = require './subject-annotator'
ClassificationSummary = require './classification-summary'
{Link} = require '@edpaget/react-router'
tasks = require './tasks'
{getSessionID} = require '../lib/session'
preloadSubject = require '../lib/preload-subject'
unless process.env.NODE_ENV is 'production'
mockData = require './mock-data'
Classifier = React.createClass
displayName: 'Classifier'
getDefaultProps: ->
user: null
if mockData?
{workflow, subject, classification} = mockData
workflow: workflow ? null
subject: subject ? null
classification: classification ? null
onLoad: Function.prototype
getInitialState: ->
subjectLoading: false
showingExpertClassification: false
selectedExpertAnnotation: -1
componentDidMount: ->
@loadSubject @props.subject
@prepareToClassify @props.classification
componentWillReceiveProps: (nextProps) ->
if nextProps.subject isnt @props.subject
@loadSubject subject
if nextProps.classification isnt @props.classification
@prepareToClassify nextProps.classification
loadSubject: (subject) ->
@setState subjectLoading: true
preloadSubject subject
.then =>
if @props.subject is subject # The subject could have changed while we were loading.
@setState subjectLoading: false
@props.onLoad?()
prepareToClassify: (classification) ->
classification.annotations ?= []
if classification.annotations.length is 0
@addAnnotationForTask classification, @props.workflow.first_task
render: ->
<ChangeListener target={@props.classification}>{=>
if @state.showingExpertClassification
currentClassification = @props.subject.expert_classification_data
else
currentClassification = @props.classification
unless @props.classification.completed
currentAnnotation = currentClassification.annotations[currentClassification.annotations.length - 1]
currentTask = @props.workflow.tasks[currentAnnotation?.task]
# This is just easy access for debugging.
window.classification = currentClassification
<div className="classifier">
<SubjectAnnotator
user={@props.user}
project={@props.project}
subject={@props.subject}
workflow={@props.workflow}
classification={currentClassification}
annotation={currentAnnotation}
onLoad={@handleSubjectImageLoad}
/>
<div className="task-area">
{if currentTask?
@renderTask currentClassification, currentAnnotation, currentTask
else # Classification is complete.
@renderSummary currentClassification}
</div>
</div>
}</ChangeListener>
renderTask: (classification, annotation, task) ->
TaskComponent = tasks[task.type]
# Should we disabled the "Back" button?
onFirstAnnotation = classification.annotations.indexOf(annotation) is 0
# Should we disable the "Next" or "Done" buttons?
if TaskComponent.isAnnotationComplete?
waitingForAnswer = not TaskComponent.isAnnotationComplete task, annotation
# Each answer of a single-answer task can have its own `next` key to override the task's.
if TaskComponent is tasks.single
currentAnswer = task.answers?[annotation.value]
nextTaskKey = currentAnswer?.next
else
nextTaskKey = task.next
unless @props.workflow.tasks[nextTaskKey]?
nextTaskKey = ''
# TODO: Actually disable things that should be.
# For now we'll just make them non-mousable.
disabledStyle =
opacity: 0.5
pointerEvents: 'none'
<div className="task-container" style={disabledStyle if @state.subjectLoading}>
<TaskComponent task={task} annotation={annotation} onChange={@updateAnnotations.bind this, classification} />
<hr />
<nav className="task-nav">
<button type="button" className="back minor-button" disabled={onFirstAnnotation} onClick={@destroyCurrentAnnotation}>Back</button>
{if nextTaskKey
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@addAnnotationForTask.bind this, classification, nextTaskKey}>Next</button>
else
<button type="button" className="continue major-button" disabled={waitingForAnswer} onClick={@completeClassification}>Done</button>}
</nav>
</div>
renderSummary: (classification) ->
<div>
Thanks!
{if @props.subject.expert_classification_data?
<div className="has-expert-classification">
Expert classification available.
{if @state.showingExpertClassification
<button type="button" onClick={@toggleExpertClassification.bind this, false}>Hide</button>
else
<button type="button" onClick={@toggleExpertClassification.bind this, true}>Show</button>}
</div>}
{if @state.showingExpertClassification
'Expert classification:'
else
'Your classification:'}
<ClassificationSummary workflow={@props.workflow} classification={classification} />
<hr />
<nav className="task-nav">
{if @props.owner? and @props.project?
[ownerName, name] = @props.project.slug.split('/')
<Link onClick={@props.onClickNext} to="project-talk-subject" params={owner: ownerName, name: PI:NAME:<NAME>END_PI, id: @props.subject.id} className="talk standard-button">Talk</Link>}
<button type="button" className="continue major-button" onClick={@props.onClickNext}>Next</button>
</nav>
</div>
# Whenever a subject image is loaded in the annotator, record its size at that time.
handleSubjectImageLoad: (e, frameIndex) ->
{naturalWidth, naturalHeight, clientWidth, clientHeight} = e.target
changes = {}
changes["metadata.subject_dimensions.#{frameIndex}"] = {naturalWidth, naturalHeight, clientWidth, clientHeight}
@props.classification.update changes
# This is passed as a generic change handler to the tasks
updateAnnotations: ->
@props.classification.update 'annotations'
# Next (or start):
addAnnotationForTask: (classification, taskKey) ->
taskDescription = @props.workflow.tasks[taskKey]
annotation = tasks[taskDescription.type].getDefaultAnnotation()
annotation.task = taskKey
classification.annotations.push annotation
classification.update 'annotations'
# Back up:
destroyCurrentAnnotation: ->
@props.classification.annotations.pop()
@props.classification.update 'annotations'
completeClassification: ->
@props.classification.update
completed: true
'metadata.session': getSessionID().id
'metadata.finished_at': (new Date).toISOString()
'metadata.viewport':
width: innerWidth
height: innerHeight
@props.onComplete?()
toggleExpertClassification: (value) ->
@setState showingExpertClassification: value
module.exports = React.createClass
displayName: 'ClassifierWrapper'
getDefaultProps: ->
user: null
classification: mockData?.classification ? {}
onLoad: Function.prototype
onComplete: Function.prototype
onClickNext: Function.prototype
getInitialState: ->
workflow: null
subject: null
componentDidMount: ->
@loadClassification @props.classification
componentWillReceiveProps: (nextProps) ->
unless nextProps.classification is @props.classification
@loadClassification nextProps.classification
loadClassification: (classification) ->
@setState
workflow: null
subject: null
# TODO: These underscored references are temporary stopgaps.
Promise.resolve(classification._workflow ? classification.get 'workflow').then (workflow) =>
@setState {workflow}
Promise.resolve(classification._subjects ? classification.get 'subjects').then ([subject]) =>
# We'll only handle one subject per classification right now.
# TODO: Support multi-subject classifications in the future.
@setState {subject}
render: ->
if @state.workflow? and @state.subject?
<Classifier {...@props} workflow={@state.workflow} subject={@state.subject} />
else
<span>Loading classifier...</span>
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.998652994632721,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-set-cookies.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
nresponses = 0
server = http.createServer((req, res) ->
if req.url is "/one"
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"content-type"
"text/plain"
]
]
res.end "one\n"
else
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"set-cookie"
"B"
]
[
"content-type"
"text/plain"
]
]
res.end "two\n"
return
)
server.listen common.PORT
server.on "listening", ->
#
# one set-cookie header
#
http.get
port: common.PORT
path: "/one"
, (res) ->
# set-cookie headers are always return in an array.
# even if there is only one.
assert.deepEqual ["A"], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
# two set-cookie headers
http.get
port: common.PORT
path: "/two"
, (res) ->
assert.deepEqual [
"A"
"B"
], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
return
process.on "exit", ->
assert.equal 2, nresponses
return
| 105763 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
nresponses = 0
server = http.createServer((req, res) ->
if req.url is "/one"
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"content-type"
"text/plain"
]
]
res.end "one\n"
else
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"set-cookie"
"B"
]
[
"content-type"
"text/plain"
]
]
res.end "two\n"
return
)
server.listen common.PORT
server.on "listening", ->
#
# one set-cookie header
#
http.get
port: common.PORT
path: "/one"
, (res) ->
# set-cookie headers are always return in an array.
# even if there is only one.
assert.deepEqual ["A"], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
# two set-cookie headers
http.get
port: common.PORT
path: "/two"
, (res) ->
assert.deepEqual [
"A"
"B"
], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
return
process.on "exit", ->
assert.equal 2, nresponses
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
nresponses = 0
server = http.createServer((req, res) ->
if req.url is "/one"
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"content-type"
"text/plain"
]
]
res.end "one\n"
else
res.writeHead 200, [
[
"set-cookie"
"A"
]
[
"set-cookie"
"B"
]
[
"content-type"
"text/plain"
]
]
res.end "two\n"
return
)
server.listen common.PORT
server.on "listening", ->
#
# one set-cookie header
#
http.get
port: common.PORT
path: "/one"
, (res) ->
# set-cookie headers are always return in an array.
# even if there is only one.
assert.deepEqual ["A"], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
# two set-cookie headers
http.get
port: common.PORT
path: "/two"
, (res) ->
assert.deepEqual [
"A"
"B"
], res.headers["set-cookie"]
assert.equal "text/plain", res.headers["content-type"]
res.on "data", (chunk) ->
console.log chunk.toString()
return
res.on "end", ->
server.close() if ++nresponses is 2
return
return
return
process.on "exit", ->
assert.equal 2, nresponses
return
|
[
{
"context": "\t\t\tname: \"main.tex\"\n\t\t\t}]\n\t\t@members = [{\n\t\t\tuser: @owner = {\n\t\t\t\t_id: \"owner-id\"\n\t\t\t\tfirst_name : \"Ow",
"end": 1000,
"score": 0.7919891476631165,
"start": 1000,
"tag": "USERNAME",
"value": ""
},
{
"context": " @owner = {\n\t\t\t\t_id: \"own... | test/UnitTests/coffee/Project/ProjectEditorHandlerTests.coffee | watercrossing/web-sharelatex | 0 | chai = require('chai')
expect = chai.expect
should = chai.should()
modulePath = "../../../../app/js/Features/Project/ProjectEditorHandler"
SandboxedModule = require('sandboxed-module')
describe "ProjectEditorHandler", ->
beforeEach ->
@project =
_id : "project-id"
name : "Project Name"
rootDoc_id : "file-id"
publicAccesLevel : "private"
deletedByExternalDataSource: false
rootFolder : [{
_id : "root-folder-id"
name : ""
docs : []
fileRefs : []
folders : [{
_id : "sub-folder-id"
name : "folder"
docs : [{
_id : "doc-id"
name : "main.tex"
lines : @lines = [
"line 1"
"line 2"
"line 3"
]
}]
fileRefs : [{
_id : "file-id"
name : "image.png"
created : new Date()
size : 1234
}]
folders : []
}]
}]
deletedDocs: [{
_id: "deleted-doc-id"
name: "main.tex"
}]
@members = [{
user: @owner = {
_id: "owner-id"
first_name : "Owner"
last_name : "ShareLaTeX"
email : "owner@sharelatex.com"
},
privilegeLevel: "owner"
},{
user: {
_id: "read-only-id"
first_name : "Read"
last_name : "Only"
email : "read-only@sharelatex.com"
},
privilegeLevel: "readOnly"
},{
user: {
_id: "read-write-id"
first_name : "Read"
last_name : "Write"
email : "read-write@sharelatex.com"
},
privilegeLevel: "readAndWrite"
}]
@invites = [
{_id: "invite_one", email: "user-one@example.com", privileges: "readOnly", projectId: @project._id}
{_id: "invite_two", email: "user-two@example.com", privileges: "readOnly", projectId: @project._id}
]
@handler = SandboxedModule.require modulePath
describe "buildProjectModelView", ->
describe "with owner and members included", ->
beforeEach ->
@result = @handler.buildProjectModelView @project, @members, @invites
it "should include the id", ->
should.exist @result._id
@result._id.should.equal "project-id"
it "should include the name", ->
should.exist @result.name
@result.name.should.equal "Project Name"
it "should include the root doc id", ->
should.exist @result.rootDoc_id
@result.rootDoc_id.should.equal "file-id"
it "should include the public access level", ->
should.exist @result.publicAccesLevel
@result.publicAccesLevel.should.equal "private"
it "should include the owner", ->
should.exist @result.owner
@result.owner._id.should.equal "owner-id"
@result.owner.email.should.equal "owner@sharelatex.com"
@result.owner.first_name.should.equal "Owner"
@result.owner.last_name.should.equal "ShareLaTeX"
@result.owner.privileges.should.equal "owner"
it "should include the deletedDocs", ->
should.exist @result.deletedDocs
@result.deletedDocs.should.equal @project.deletedDocs
it "should gather readOnly_refs and collaberators_refs into a list of members", ->
findMember = (id) =>
for member in @result.members
return member if member._id == id
return null
@result.members.length.should.equal 2
should.exist findMember("read-only-id")
findMember("read-only-id").privileges.should.equal "readOnly"
findMember("read-only-id").first_name.should.equal "Read"
findMember("read-only-id").last_name.should.equal "Only"
findMember("read-only-id").email.should.equal "read-only@sharelatex.com"
should.exist findMember("read-write-id")
findMember("read-write-id").privileges.should.equal "readAndWrite"
findMember("read-write-id").first_name.should.equal "Read"
findMember("read-write-id").last_name.should.equal "Write"
findMember("read-write-id").email.should.equal "read-write@sharelatex.com"
it "should include folders in the project", ->
@result.rootFolder[0]._id.should.equal "root-folder-id"
@result.rootFolder[0].name.should.equal ""
@result.rootFolder[0].folders[0]._id.should.equal "sub-folder-id"
@result.rootFolder[0].folders[0].name.should.equal "folder"
it "should not duplicate folder contents", ->
@result.rootFolder[0].docs.length.should.equal 0
@result.rootFolder[0].fileRefs.length.should.equal 0
it "should include files in the project", ->
@result.rootFolder[0].folders[0].fileRefs[0]._id.should.equal "file-id"
@result.rootFolder[0].folders[0].fileRefs[0].name.should.equal "image.png"
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].created
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].size
it "should include docs in the project but not the lines", ->
@result.rootFolder[0].folders[0].docs[0]._id.should.equal "doc-id"
@result.rootFolder[0].folders[0].docs[0].name.should.equal "main.tex"
should.not.exist @result.rootFolder[0].folders[0].docs[0].lines
it 'should include invites', ->
should.exist @result.invites
@result.invites.should.deep.equal @invites
describe "deletedByExternalDataSource", ->
it "should set the deletedByExternalDataSource flag to false when it is not there", ->
delete @project.deletedByExternalDataSource
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to false when it is false", ->
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to true when it is true", ->
@project.deletedByExternalDataSource = true
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal true
describe "features", ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 96
@result = @handler.buildProjectModelView @project, @members
it "should copy the owner features to the project", ->
@result.features.versioning.should.equal @owner.features.versioning
@result.features.collaborators.should.equal @owner.features.collaborators
@result.features.compileGroup.should.equal @owner.features.compileGroup
@result.features.compileTimeout.should.equal @owner.features.compileTimeout
describe 'buildOwnerAndMembersViews', ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 22
@result = @handler.buildOwnerAndMembersViews @members
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should separate the owner from the members', ->
@result.members.length.should.equal(@members.length-1)
expect(@result.owner._id).to.equal @owner._id
expect(@result.owner.email).to.equal @owner.email
expect(@result.members.filter((m) => m._id == @owner._id).length).to.equal 0
it 'should extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.deep.equal @owner.features
describe 'when there is no owner', ->
beforeEach ->
# remove the owner from members list
@membersWithoutOwner = @members.filter((m) => m.user._id != @owner._id)
@result = @handler.buildOwnerAndMembersViews @membersWithoutOwner
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should not separate out an owner', ->
@result.members.length.should.equal @membersWithoutOwner.length
expect(@result.owner).to.equal null
it 'should not extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.equal null
| 221450 | chai = require('chai')
expect = chai.expect
should = chai.should()
modulePath = "../../../../app/js/Features/Project/ProjectEditorHandler"
SandboxedModule = require('sandboxed-module')
describe "ProjectEditorHandler", ->
beforeEach ->
@project =
_id : "project-id"
name : "Project Name"
rootDoc_id : "file-id"
publicAccesLevel : "private"
deletedByExternalDataSource: false
rootFolder : [{
_id : "root-folder-id"
name : ""
docs : []
fileRefs : []
folders : [{
_id : "sub-folder-id"
name : "folder"
docs : [{
_id : "doc-id"
name : "main.tex"
lines : @lines = [
"line 1"
"line 2"
"line 3"
]
}]
fileRefs : [{
_id : "file-id"
name : "image.png"
created : new Date()
size : 1234
}]
folders : []
}]
}]
deletedDocs: [{
_id: "deleted-doc-id"
name: "main.tex"
}]
@members = [{
user: @owner = {
_id: "owner-id"
first_name : "<NAME>"
last_name : "<NAME>"
email : "<EMAIL>"
},
privilegeLevel: "owner"
},{
user: {
_id: "read-only-id"
first_name : "<NAME>"
last_name : "<NAME>"
email : "<EMAIL>"
},
privilegeLevel: "readOnly"
},{
user: {
_id: "read-write-id"
first_name : "<NAME>"
last_name : "<NAME>"
email : "<EMAIL>"
},
privilegeLevel: "readAndWrite"
}]
@invites = [
{_id: "invite_one", email: "<EMAIL>", privileges: "readOnly", projectId: @project._id}
{_id: "invite_two", email: "<EMAIL>", privileges: "readOnly", projectId: @project._id}
]
@handler = SandboxedModule.require modulePath
describe "buildProjectModelView", ->
describe "with owner and members included", ->
beforeEach ->
@result = @handler.buildProjectModelView @project, @members, @invites
it "should include the id", ->
should.exist @result._id
@result._id.should.equal "project-id"
it "should include the name", ->
should.exist @result.name
@result.name.should.equal "Project Name"
it "should include the root doc id", ->
should.exist @result.rootDoc_id
@result.rootDoc_id.should.equal "file-id"
it "should include the public access level", ->
should.exist @result.publicAccesLevel
@result.publicAccesLevel.should.equal "private"
it "should include the owner", ->
should.exist @result.owner
@result.owner._id.should.equal "owner-id"
@result.owner.email.should.equal "<EMAIL>"
@result.owner.first_name.should.equal "Owner"
@result.owner.last_name.should.equal "ShareLaTeX"
@result.owner.privileges.should.equal "owner"
it "should include the deletedDocs", ->
should.exist @result.deletedDocs
@result.deletedDocs.should.equal @project.deletedDocs
it "should gather readOnly_refs and collaberators_refs into a list of members", ->
findMember = (id) =>
for member in @result.members
return member if member._id == id
return null
@result.members.length.should.equal 2
should.exist findMember("read-only-id")
findMember("read-only-id").privileges.should.equal "readOnly"
findMember("read-only-id").first_name.should.equal "<NAME>"
findMember("read-only-id").last_name.should.equal "<NAME>"
findMember("read-only-id").email.should.equal "<EMAIL>"
should.exist findMember("read-write-id")
findMember("read-write-id").privileges.should.equal "readAndWrite"
findMember("read-write-id").first_name.should.equal "<NAME>"
findMember("read-write-id").last_name.should.equal "<NAME>"
findMember("read-write-id").email.should.equal "<EMAIL>"
it "should include folders in the project", ->
@result.rootFolder[0]._id.should.equal "root-folder-id"
@result.rootFolder[0].name.should.equal ""
@result.rootFolder[0].folders[0]._id.should.equal "sub-folder-id"
@result.rootFolder[0].folders[0].name.should.equal "folder"
it "should not duplicate folder contents", ->
@result.rootFolder[0].docs.length.should.equal 0
@result.rootFolder[0].fileRefs.length.should.equal 0
it "should include files in the project", ->
@result.rootFolder[0].folders[0].fileRefs[0]._id.should.equal "file-id"
@result.rootFolder[0].folders[0].fileRefs[0].name.should.equal "image.png"
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].created
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].size
it "should include docs in the project but not the lines", ->
@result.rootFolder[0].folders[0].docs[0]._id.should.equal "doc-id"
@result.rootFolder[0].folders[0].docs[0].name.should.equal "main.tex"
should.not.exist @result.rootFolder[0].folders[0].docs[0].lines
it 'should include invites', ->
should.exist @result.invites
@result.invites.should.deep.equal @invites
describe "deletedByExternalDataSource", ->
it "should set the deletedByExternalDataSource flag to false when it is not there", ->
delete @project.deletedByExternalDataSource
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to false when it is false", ->
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to true when it is true", ->
@project.deletedByExternalDataSource = true
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal true
describe "features", ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 96
@result = @handler.buildProjectModelView @project, @members
it "should copy the owner features to the project", ->
@result.features.versioning.should.equal @owner.features.versioning
@result.features.collaborators.should.equal @owner.features.collaborators
@result.features.compileGroup.should.equal @owner.features.compileGroup
@result.features.compileTimeout.should.equal @owner.features.compileTimeout
describe 'buildOwnerAndMembersViews', ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 22
@result = @handler.buildOwnerAndMembersViews @members
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should separate the owner from the members', ->
@result.members.length.should.equal(@members.length-1)
expect(@result.owner._id).to.equal @owner._id
expect(@result.owner.email).to.equal @owner.email
expect(@result.members.filter((m) => m._id == @owner._id).length).to.equal 0
it 'should extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.deep.equal @owner.features
describe 'when there is no owner', ->
beforeEach ->
# remove the owner from members list
@membersWithoutOwner = @members.filter((m) => m.user._id != @owner._id)
@result = @handler.buildOwnerAndMembersViews @membersWithoutOwner
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should not separate out an owner', ->
@result.members.length.should.equal @membersWithoutOwner.length
expect(@result.owner).to.equal null
it 'should not extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.equal null
| true | chai = require('chai')
expect = chai.expect
should = chai.should()
modulePath = "../../../../app/js/Features/Project/ProjectEditorHandler"
SandboxedModule = require('sandboxed-module')
describe "ProjectEditorHandler", ->
beforeEach ->
@project =
_id : "project-id"
name : "Project Name"
rootDoc_id : "file-id"
publicAccesLevel : "private"
deletedByExternalDataSource: false
rootFolder : [{
_id : "root-folder-id"
name : ""
docs : []
fileRefs : []
folders : [{
_id : "sub-folder-id"
name : "folder"
docs : [{
_id : "doc-id"
name : "main.tex"
lines : @lines = [
"line 1"
"line 2"
"line 3"
]
}]
fileRefs : [{
_id : "file-id"
name : "image.png"
created : new Date()
size : 1234
}]
folders : []
}]
}]
deletedDocs: [{
_id: "deleted-doc-id"
name: "main.tex"
}]
@members = [{
user: @owner = {
_id: "owner-id"
first_name : "PI:NAME:<NAME>END_PI"
last_name : "PI:NAME:<NAME>END_PI"
email : "PI:EMAIL:<EMAIL>END_PI"
},
privilegeLevel: "owner"
},{
user: {
_id: "read-only-id"
first_name : "PI:NAME:<NAME>END_PI"
last_name : "PI:NAME:<NAME>END_PI"
email : "PI:EMAIL:<EMAIL>END_PI"
},
privilegeLevel: "readOnly"
},{
user: {
_id: "read-write-id"
first_name : "PI:NAME:<NAME>END_PI"
last_name : "PI:NAME:<NAME>END_PI"
email : "PI:EMAIL:<EMAIL>END_PI"
},
privilegeLevel: "readAndWrite"
}]
@invites = [
{_id: "invite_one", email: "PI:EMAIL:<EMAIL>END_PI", privileges: "readOnly", projectId: @project._id}
{_id: "invite_two", email: "PI:EMAIL:<EMAIL>END_PI", privileges: "readOnly", projectId: @project._id}
]
@handler = SandboxedModule.require modulePath
describe "buildProjectModelView", ->
describe "with owner and members included", ->
beforeEach ->
@result = @handler.buildProjectModelView @project, @members, @invites
it "should include the id", ->
should.exist @result._id
@result._id.should.equal "project-id"
it "should include the name", ->
should.exist @result.name
@result.name.should.equal "Project Name"
it "should include the root doc id", ->
should.exist @result.rootDoc_id
@result.rootDoc_id.should.equal "file-id"
it "should include the public access level", ->
should.exist @result.publicAccesLevel
@result.publicAccesLevel.should.equal "private"
it "should include the owner", ->
should.exist @result.owner
@result.owner._id.should.equal "owner-id"
@result.owner.email.should.equal "PI:EMAIL:<EMAIL>END_PI"
@result.owner.first_name.should.equal "Owner"
@result.owner.last_name.should.equal "ShareLaTeX"
@result.owner.privileges.should.equal "owner"
it "should include the deletedDocs", ->
should.exist @result.deletedDocs
@result.deletedDocs.should.equal @project.deletedDocs
it "should gather readOnly_refs and collaberators_refs into a list of members", ->
findMember = (id) =>
for member in @result.members
return member if member._id == id
return null
@result.members.length.should.equal 2
should.exist findMember("read-only-id")
findMember("read-only-id").privileges.should.equal "readOnly"
findMember("read-only-id").first_name.should.equal "PI:NAME:<NAME>END_PI"
findMember("read-only-id").last_name.should.equal "PI:NAME:<NAME>END_PI"
findMember("read-only-id").email.should.equal "PI:EMAIL:<EMAIL>END_PI"
should.exist findMember("read-write-id")
findMember("read-write-id").privileges.should.equal "readAndWrite"
findMember("read-write-id").first_name.should.equal "PI:NAME:<NAME>END_PI"
findMember("read-write-id").last_name.should.equal "PI:NAME:<NAME>END_PI"
findMember("read-write-id").email.should.equal "PI:EMAIL:<EMAIL>END_PI"
it "should include folders in the project", ->
@result.rootFolder[0]._id.should.equal "root-folder-id"
@result.rootFolder[0].name.should.equal ""
@result.rootFolder[0].folders[0]._id.should.equal "sub-folder-id"
@result.rootFolder[0].folders[0].name.should.equal "folder"
it "should not duplicate folder contents", ->
@result.rootFolder[0].docs.length.should.equal 0
@result.rootFolder[0].fileRefs.length.should.equal 0
it "should include files in the project", ->
@result.rootFolder[0].folders[0].fileRefs[0]._id.should.equal "file-id"
@result.rootFolder[0].folders[0].fileRefs[0].name.should.equal "image.png"
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].created
should.not.exist @result.rootFolder[0].folders[0].fileRefs[0].size
it "should include docs in the project but not the lines", ->
@result.rootFolder[0].folders[0].docs[0]._id.should.equal "doc-id"
@result.rootFolder[0].folders[0].docs[0].name.should.equal "main.tex"
should.not.exist @result.rootFolder[0].folders[0].docs[0].lines
it 'should include invites', ->
should.exist @result.invites
@result.invites.should.deep.equal @invites
describe "deletedByExternalDataSource", ->
it "should set the deletedByExternalDataSource flag to false when it is not there", ->
delete @project.deletedByExternalDataSource
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to false when it is false", ->
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal false
it "should set the deletedByExternalDataSource flag to true when it is true", ->
@project.deletedByExternalDataSource = true
result = @handler.buildProjectModelView @project, @members
result.deletedByExternalDataSource.should.equal true
describe "features", ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 96
@result = @handler.buildProjectModelView @project, @members
it "should copy the owner features to the project", ->
@result.features.versioning.should.equal @owner.features.versioning
@result.features.collaborators.should.equal @owner.features.collaborators
@result.features.compileGroup.should.equal @owner.features.compileGroup
@result.features.compileTimeout.should.equal @owner.features.compileTimeout
describe 'buildOwnerAndMembersViews', ->
beforeEach ->
@owner.features =
versioning: true
collaborators: 3
compileGroup:"priority"
compileTimeout: 22
@result = @handler.buildOwnerAndMembersViews @members
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should separate the owner from the members', ->
@result.members.length.should.equal(@members.length-1)
expect(@result.owner._id).to.equal @owner._id
expect(@result.owner.email).to.equal @owner.email
expect(@result.members.filter((m) => m._id == @owner._id).length).to.equal 0
it 'should extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.deep.equal @owner.features
describe 'when there is no owner', ->
beforeEach ->
# remove the owner from members list
@membersWithoutOwner = @members.filter((m) => m.user._id != @owner._id)
@result = @handler.buildOwnerAndMembersViews @membersWithoutOwner
it 'should produce an object with owner, ownerFeatures and members keys', ->
expect(@result).to.have.all.keys ['owner', 'ownerFeatures', 'members']
it 'should not separate out an owner', ->
@result.members.length.should.equal @membersWithoutOwner.length
expect(@result.owner).to.equal null
it 'should not extract the ownerFeatures from the owner object', ->
expect(@result.ownerFeatures).to.equal null
|
[
{
"context": "goDb = mongoose.createConnection 'mongodb://tests:tests@staff.mongohq.com:10083/tests'\nmiddleware = lox mongoDb\n\ndescribe '",
"end": 159,
"score": 0.9999249577522278,
"start": 136,
"tag": "EMAIL",
"value": "tests@staff.mongohq.com"
},
{
"context": "ibe 'Lox', ->\n\n ... | test/user_test.coffee | reaktivo/lox | 0 | assert = require 'assert'
lox = require '../lib/lox'
mongoose = require 'mongoose'
mongoDb = mongoose.createConnection 'mongodb://tests:tests@staff.mongohq.com:10083/tests'
middleware = lox mongoDb
describe 'Lox', ->
# Mock user
form =
email: 'some@email.com'
password: 'somepassword'
# Mock request
res =
locals: (locals) ->
# Set locals
req =
session:
destroy: -> # session destroyed
describe 'lox.create', ->
it 'should create without error', (done) ->
lox.create form.email, form.password, done
describe 'req.login', ->
it 'should login without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.login form.user, form.password, (err, user) ->
assert(user.email == form.email, "User logged in")
done(err)
describe 'req.logout', ->
it 'should logout without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.logout done
describe 'lox.getUser', ->
it 'should find the created user', (done) ->
lox.getUser form.email, (err, user) ->
assert user.email == form.email, "Found user"
do done
describe 'lox.destroy', ->
it 'should destroy without error', (done) ->
lox.destroy form.email, done
| 38532 | assert = require 'assert'
lox = require '../lib/lox'
mongoose = require 'mongoose'
mongoDb = mongoose.createConnection 'mongodb://tests:<EMAIL>:10083/tests'
middleware = lox mongoDb
describe 'Lox', ->
# Mock user
form =
email: '<EMAIL>'
password: '<PASSWORD>'
# Mock request
res =
locals: (locals) ->
# Set locals
req =
session:
destroy: -> # session destroyed
describe 'lox.create', ->
it 'should create without error', (done) ->
lox.create form.email, form.password, done
describe 'req.login', ->
it 'should login without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.login form.user, form.password, (err, user) ->
assert(user.email == form.email, "User logged in")
done(err)
describe 'req.logout', ->
it 'should logout without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.logout done
describe 'lox.getUser', ->
it 'should find the created user', (done) ->
lox.getUser form.email, (err, user) ->
assert user.email == form.email, "Found user"
do done
describe 'lox.destroy', ->
it 'should destroy without error', (done) ->
lox.destroy form.email, done
| true | assert = require 'assert'
lox = require '../lib/lox'
mongoose = require 'mongoose'
mongoDb = mongoose.createConnection 'mongodb://tests:PI:EMAIL:<EMAIL>END_PI:10083/tests'
middleware = lox mongoDb
describe 'Lox', ->
# Mock user
form =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
# Mock request
res =
locals: (locals) ->
# Set locals
req =
session:
destroy: -> # session destroyed
describe 'lox.create', ->
it 'should create without error', (done) ->
lox.create form.email, form.password, done
describe 'req.login', ->
it 'should login without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.login form.user, form.password, (err, user) ->
assert(user.email == form.email, "User logged in")
done(err)
describe 'req.logout', ->
it 'should logout without error', (done) ->
# Simulate request flow with req, res, next
middleware req, res, (err) ->
done err if err
req.logout done
describe 'lox.getUser', ->
it 'should find the created user', (done) ->
lox.getUser form.email, (err, user) ->
assert user.email == form.email, "Found user"
do done
describe 'lox.destroy', ->
it 'should destroy without error', (done) ->
lox.destroy form.email, done
|
[
{
"context": "n 1.0.0\n@file Datatable.js\n@author Welington Sampaio (http://welington.zaez.net/)\n@contact http://",
"end": 150,
"score": 0.9999021291732788,
"start": 133,
"tag": "NAME",
"value": "Welington Sampaio"
},
{
"context": "n.zaez.net/site/contato\n\n@co... | vendor/assets/javascripts/lol_framework/Datatable.coffee | welingtonsampaio/lol-framework | 1 | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Datatable.js
@author Welington Sampaio (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 Welington Sampaio, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Datatable.
@classDescription This class creates a new Datatable.
@param {Object} Receives configuration to create the Datatable, @see Lol.datatable.defaults
@return {Datatable} Returns a new Datatable.
@type {Object}
@example
*-* Auto configuration *-*
<table id="lol-datatable" data-lol-datatable="true" data-datatable-model-name="User">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr
data-datatable-link="http://welington.zaez.net/"
data-datatable-edit-link="#edit_my_page_ws"
data-datatable-view-link="#view_my_page_ws"
data-datatable-delete-link="#delete_my_page_ws"
data-datatable-model-id="1">
<td>1</td>
<td>Welington</td>
<td>Sampaio</td>
</tr>
<tr
data-datatable-link="http://fabricio.zaez.net/"
data-datatable-edit-link="#edit_my_page_fm"
data-datatable-view-link="#view_my_page_fm"
data-datatable-delete-link="#delete_my_page_fm"
data-datatable-model-id="2">
<td>2</td>
<td>Fabricio</td>
<td>Monte</td>
</tr>
</tbody>
</table>
*-* Setting manually configuration *-*
var datatable = new Lol.Datatable({
debug: false,
selectable: true,
target: null,
delayDblclick: 0,
classes: {
activeRow: 'active_row'
},
contextMenu: {
"delete": function(row, object) {
//see documentation
},
edit: function(row, object) {
//see documentation
},
view: function(row, object) {
//see documentation
},
iconView: 'icon-eye-open',
iconEdit: 'icon-edit',
iconDelete: 'icon-remove',
useIcons: true,
model: null
},
configuration: {
aaSortingFixed: null,
aoColumnDefs: null,
aoColumns: null,
asStripeClasses: null,
bAutoWidth: true,
bDeferRender: false,
bDestroy: false,
bFilter: false,
bInfo: false,
bJQueryUI: false,
bLengthChange: false,
bPaginate: false,
bProcessing: false,
bRetrieve: false,
bScrollAutoCss: true,
bScrollCollapse: false,
bScrollInfinite: false,
bServerSide: false,
bSort: true,
bSortCellsTop: false,
bSortClasses: true,
bStateSave: false,
iCookieDuration: 7200,
iDeferLoading: null,
iDisplayLength: 20,
iDisplayStart: 0,
iScrollLoadGap: 100,
iTabIndex: 0,
sAjaxDataProp: "aaData",
sAjaxSource: null,
sCookiePrefix: "SpryMedia_DataTables_",
sDom: "lfrtip",
sPaginationType: "two_button",
sScrollX: "",
sScrollXInner: "",
sScrollY: "",
sServerMethod: "GET"
}
});
###
class Lol.Datatable extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Datatable'
namespace : '.datatable'
table : null
# the methods
constructor: (args={})->
throw 'Required jQuery library' if jQuery == undefined
@settings = jQuery.extend true, {}, Lol.datatable.defaults, args
@id = Lol.Utils.uniqid()
Lol.Utils.addObject @
@dataset = Lol.datatable.private.dataset
@setTable()
@setConfigTable()
@setModel()
@setTranslation()
@setAjax()
@generate()
@setEvents()
@
createMenuContext: (row, event)->
if row.data(@dataset.deleteLink) or row.data(@dataset.editLink) or row.data(@dataset.viewLink)
_this = @
context = jQuery "<div class='dropdown context-menu' id='context-menu-#{@id}'></div>"
context.css
left : event.pageX - 15
top : event.pageY - 15
context.bind
mouseleave: (event)->
jQuery(@).stop().delay(_this.settings.delayDblclick).animate {opacity: 0}, ->
jQuery(@).remove()
mouseenter: (event)->
jQuery(@).stop(true).animate {opacity: 1}
ul = jQuery '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">'
if ( row.data(@dataset.viewLink) )
view = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.viewLink)}'>#{Lol.t('datatable_view')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconView}'></i>").prependTo view.find('a') if @settings.contextMenu.useIcons
view.bind
click: ->
_this.settings.contextMenu.view row, _this
view.appendTo ul
if ( row.data(@dataset.editLink) )
edit = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.editLink)}'>#{Lol.t('datatable_edit')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconEdit}'></i>").prependTo edit.find('a') if @settings.contextMenu.useIcons
edit.bind
click: ->
_this.debug 'aki'
_this.settings.contextMenu.edit row, _this
edit.appendTo ul
if ( row.data(@dataset.deleteLink) )
remove = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.deleteLink)}'>#{Lol.t('datatable_delete')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconDelete}'></i>").prependTo remove.find('a') if @settings.contextMenu.useIcons
remove.bind
click: ->
_this.settings.contextMenu.delete row, _this
remove.appendTo ul
ul.appendTo context
context.appendTo 'body'
generate: ->
@table.dataTable @settings.configuration
jQuery('.dataTables_filter input').attr('placeholder', Lol.t('datatable_search'))
$("<em class='arrow'></em>").appendTo @table.find('th')
getDt: ->
@table.dataTable()
goLink: (row)->
link = jQuery(row).data(@dataset.link)
Lol.Utils.redirector link if link
isRowActive: (row)->
row.hasClass @settings.classes.activeRow
setActiveRow: (row)->
@unsetActiveRow()
row.addClass @settings.classes.activeRow
row.data( @dataset.timeClicked, new Date().getTime() + @settings.delayDblclick )
setAjax: ->
if @table.data( @dataset.ajaxResource )
@settings.configuration.sAjaxSource = @table.data( @dataset.ajaxResource )
@settings.configuration.bProcessing = true
@settings.configuration.sServerMethod = @table.data( @dataset.ajaxMethod ) if @table.data( @dataset.ajaxMethod )
@settings.configuration.sAjaxDataProp = @table.data( @dataset.ajaxRoot ) if @table.data( @dataset.ajaxRoot )
setConfigTable: ->
@table.addClass 'lol-datatable'
setEvents: ->
_this = @
rows = "tbody tr"
@table.delegate rows, "click#{@namespace}", (e)->
row = jQuery @
if _this.isRowActive(row)
if row.data(_this.dataset.timeClicked) > new Date().getTime()
_this.goLink row
else
_this.unsetActiveRow(row)
else
_this.setActiveRow(row)
@table.delegate rows, "contextmenu#{@namespace}", (e)->
row = jQuery @
_this.setActiveRow(row)
_this.createMenuContext(row, event)
false
setModel: ->
@settings.contextMenu.model = @table.data(Lol.datatable["private"].dataset.modelName)
setTable: ->
@table = @settings.target
setTranslation: ->
jQuery.extend(
true,
@settings.configuration,
{
oLanguage:
oAria:
sSortAscending : Lol.t 'datatable_oAria_sSortAscending'
sSortDescending: Lol.t 'datatable_oAria_sSortDescending'
oPaginate:
sFirst : Lol.t 'datatable_oPaginate_sFirst'
sLast : Lol.t 'datatable_oPaginate_sLast'
sNext : Lol.t 'datatable_oPaginate_sNext'
sPrevious: Lol.t 'datatable_oPaginate_sPrevious'
sEmptyTable : Lol.t 'datatable_sEmptyTable'
sInfo : Lol.t 'datatable_sInfo'
sInfoEmpty : Lol.t 'datatable_sInfoEmpty'
sInfoFiltered : Lol.t 'datatable_sInfoFiltered'
sInfoPostFix : Lol.t 'datatable_sInfoPostFix'
sInfoThousands : Lol.t 'datatable_sInfoThousands'
sLengthMenu : Lol.t 'datatable_sLengthMenu'
sLoadingRecords: Lol.t 'datatable_sLoadingRecords'
sProcessing : Lol.t 'datatable_sProcessing'
sSearch : Lol.t 'datatable_sSearch'
sUrl : Lol.t 'datatable_sUrl'
sZeroRecords : Lol.t 'datatable_sZeroRecords'
}
)
unsetActiveRow: ()->
jQuery("tr.#{@settings.classes.activeRow}", @table).removeClass @settings.classes.activeRow
Lol.datatable =
## private configs
private:
dataset:
autoGenerate: 'lolDatatable'
link : 'datatableLink'
deleteLink : 'datatableDeleteLink'
editLink : 'datatableEditLink'
viewLink : 'datatableViewLink'
timeClicked : 'datatableClicked'
modelName : 'datatableModelName'
modelId : 'datatableModelId'
defaults:
###
Sets whether to print debug messages, such as sequences
of plays and creations, to facilitate the extension of
the code and bug fixes.
@type {Boolean}
###
debug : false
###
Sets up the "Datatable" must set the click event
on the table rows. This action adds a control class
to the table row.
@type {Boolean}
###
selectable : true
###
jQuery selector element to the table setting
@type {jQuery Selector}
###
target : null
###
Time delay the contextMenu is visible after the
mouse-hover event on the object
@type {Integer}
###
delayDblclick : 0
###
Object that stores the control classes of objects
of styles
@type {Object}
###
classes:
###
Class added after the event triggering
the selection line
@type {String}
###
activeRow : 'active_row'
###
Contains information generation contextMenu
and events, icons and other data
@type {Object}
###
contextMenu:
###
Every time the button is clicked the delete is
triggered a call to this method. What is done
in the process of exclusion in the database
through the model
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
delete: (row, object)->
window.lol_temp_fn_model_destroy = [row,object]
attrs =
"data-datatable-model-name": object.settings.contextMenu.model
"data-datatable-model-id" : row.data(Lol.datatable.private.dataset.modelId)
new Lol.Modal
buttons : 'OK_CANCEL'
content : Lol.t('datatable_confirm_delete')
title : Lol.t('datatable_confirm_delete_title')
callbacks:
buttonClick: (button, obj)->
obj.destroy()
buttonParams:
attributes:
OK: attrs
fn:
OK_CLICK: (event, obj)->
model = new Lol.model.reference[obj.button.data(Lol.datatable.private.dataset.modelName)]
model.set 'id', obj.button.data(Lol.datatable.private.dataset.modelId)
model.destroy Lol.model.destroy
false
###
Every time the button is clicked the
edit is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
edit: (row, object)->
object.debug row.data(object.dataset.editLink)
window.location = row.data(object.dataset.editLink)
false
###
Every time the button is clicked the
view is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
view: (row, object)->
window.location = row.data(object.dataset.viewLink)
false
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon button to view.
@type {String}
###
iconView : 'icon-eye-open'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button editing.
@type {String}
###
iconEdit : 'icon-edit'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button removal.
@type {String}
###
iconDelete : 'icon-remove'
###
Sets up the "Datatable" should use the icons for
better identification contextMenu or not.
@type {Boolean}
###
useIcons : true
###
Defines "String" from the class name of the model
of communication with the backend. It can be
configured by the attribute "given" by the syntax:
"datatable-data-model-name". See the example above.
@type {String}
###
model : null
###
Settings element DataTables. For further details
and functions of each element see official
documentation plugin
@see http://datatables.net/
@type {Object}
###
configuration:
aaSortingFixed : null
aoColumnDefs : null
aoColumns : null
asStripeClasses: null
bAutoWidth : true
bDeferRender : false
bDestroy : false
bFilter : false
bInfo : false
bJQueryUI : false
bLengthChange : false
bPaginate : false
bProcessing : false
bRetrieve : false
bScrollAutoCss : true
bScrollCollapse: false
bScrollInfinite: false
bServerSide : false
bSort : true
bSortCellsTop : false
bSortClasses : true
bStateSave : false
iCookieDuration: 7200
iDeferLoading : null
iDisplayLength : 20
iDisplayStart : 0
iScrollLoadGap : 100
iTabIndex : 0
sAjaxDataProp : "aaData"
sAjaxSource : null
sCookiePrefix : "SpryMedia_DataTables_"
sDom : "lfrtip"
sPaginationType: "two_button"
sScrollX : ""
sScrollXInner : ""
sScrollY : ""
sServerMethod : "GET"
jQuery ->
jQuery('[data-lol-datatable]').each ->
new Lol.Datatable
target: jQuery(@) | 5404 | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Datatable.js
@author <NAME> (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 <NAME>, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Datatable.
@classDescription This class creates a new Datatable.
@param {Object} Receives configuration to create the Datatable, @see Lol.datatable.defaults
@return {Datatable} Returns a new Datatable.
@type {Object}
@example
*-* Auto configuration *-*
<table id="lol-datatable" data-lol-datatable="true" data-datatable-model-name="User">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr
data-datatable-link="http://welington.zaez.net/"
data-datatable-edit-link="#edit_my_page_ws"
data-datatable-view-link="#view_my_page_ws"
data-datatable-delete-link="#delete_my_page_ws"
data-datatable-model-id="1">
<td>1</td>
<td><NAME></td>
<td>Sampaio</td>
</tr>
<tr
data-datatable-link="http://fabricio.zaez.net/"
data-datatable-edit-link="#edit_my_page_fm"
data-datatable-view-link="#view_my_page_fm"
data-datatable-delete-link="#delete_my_page_fm"
data-datatable-model-id="2">
<td>2</td>
<td><NAME></td>
<td><NAME></td>
</tr>
</tbody>
</table>
*-* Setting manually configuration *-*
var datatable = new Lol.Datatable({
debug: false,
selectable: true,
target: null,
delayDblclick: 0,
classes: {
activeRow: 'active_row'
},
contextMenu: {
"delete": function(row, object) {
//see documentation
},
edit: function(row, object) {
//see documentation
},
view: function(row, object) {
//see documentation
},
iconView: 'icon-eye-open',
iconEdit: 'icon-edit',
iconDelete: 'icon-remove',
useIcons: true,
model: null
},
configuration: {
aaSortingFixed: null,
aoColumnDefs: null,
aoColumns: null,
asStripeClasses: null,
bAutoWidth: true,
bDeferRender: false,
bDestroy: false,
bFilter: false,
bInfo: false,
bJQueryUI: false,
bLengthChange: false,
bPaginate: false,
bProcessing: false,
bRetrieve: false,
bScrollAutoCss: true,
bScrollCollapse: false,
bScrollInfinite: false,
bServerSide: false,
bSort: true,
bSortCellsTop: false,
bSortClasses: true,
bStateSave: false,
iCookieDuration: 7200,
iDeferLoading: null,
iDisplayLength: 20,
iDisplayStart: 0,
iScrollLoadGap: 100,
iTabIndex: 0,
sAjaxDataProp: "aaData",
sAjaxSource: null,
sCookiePrefix: "SpryMedia_DataTables_",
sDom: "lfrtip",
sPaginationType: "two_button",
sScrollX: "",
sScrollXInner: "",
sScrollY: "",
sServerMethod: "GET"
}
});
###
class Lol.Datatable extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Datatable'
namespace : '.datatable'
table : null
# the methods
constructor: (args={})->
throw 'Required jQuery library' if jQuery == undefined
@settings = jQuery.extend true, {}, Lol.datatable.defaults, args
@id = Lol.Utils.uniqid()
Lol.Utils.addObject @
@dataset = Lol.datatable.private.dataset
@setTable()
@setConfigTable()
@setModel()
@setTranslation()
@setAjax()
@generate()
@setEvents()
@
createMenuContext: (row, event)->
if row.data(@dataset.deleteLink) or row.data(@dataset.editLink) or row.data(@dataset.viewLink)
_this = @
context = jQuery "<div class='dropdown context-menu' id='context-menu-#{@id}'></div>"
context.css
left : event.pageX - 15
top : event.pageY - 15
context.bind
mouseleave: (event)->
jQuery(@).stop().delay(_this.settings.delayDblclick).animate {opacity: 0}, ->
jQuery(@).remove()
mouseenter: (event)->
jQuery(@).stop(true).animate {opacity: 1}
ul = jQuery '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">'
if ( row.data(@dataset.viewLink) )
view = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.viewLink)}'>#{Lol.t('datatable_view')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconView}'></i>").prependTo view.find('a') if @settings.contextMenu.useIcons
view.bind
click: ->
_this.settings.contextMenu.view row, _this
view.appendTo ul
if ( row.data(@dataset.editLink) )
edit = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.editLink)}'>#{Lol.t('datatable_edit')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconEdit}'></i>").prependTo edit.find('a') if @settings.contextMenu.useIcons
edit.bind
click: ->
_this.debug 'aki'
_this.settings.contextMenu.edit row, _this
edit.appendTo ul
if ( row.data(@dataset.deleteLink) )
remove = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.deleteLink)}'>#{Lol.t('datatable_delete')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconDelete}'></i>").prependTo remove.find('a') if @settings.contextMenu.useIcons
remove.bind
click: ->
_this.settings.contextMenu.delete row, _this
remove.appendTo ul
ul.appendTo context
context.appendTo 'body'
generate: ->
@table.dataTable @settings.configuration
jQuery('.dataTables_filter input').attr('placeholder', Lol.t('datatable_search'))
$("<em class='arrow'></em>").appendTo @table.find('th')
getDt: ->
@table.dataTable()
goLink: (row)->
link = jQuery(row).data(@dataset.link)
Lol.Utils.redirector link if link
isRowActive: (row)->
row.hasClass @settings.classes.activeRow
setActiveRow: (row)->
@unsetActiveRow()
row.addClass @settings.classes.activeRow
row.data( @dataset.timeClicked, new Date().getTime() + @settings.delayDblclick )
setAjax: ->
if @table.data( @dataset.ajaxResource )
@settings.configuration.sAjaxSource = @table.data( @dataset.ajaxResource )
@settings.configuration.bProcessing = true
@settings.configuration.sServerMethod = @table.data( @dataset.ajaxMethod ) if @table.data( @dataset.ajaxMethod )
@settings.configuration.sAjaxDataProp = @table.data( @dataset.ajaxRoot ) if @table.data( @dataset.ajaxRoot )
setConfigTable: ->
@table.addClass 'lol-datatable'
setEvents: ->
_this = @
rows = "tbody tr"
@table.delegate rows, "click#{@namespace}", (e)->
row = jQuery @
if _this.isRowActive(row)
if row.data(_this.dataset.timeClicked) > new Date().getTime()
_this.goLink row
else
_this.unsetActiveRow(row)
else
_this.setActiveRow(row)
@table.delegate rows, "contextmenu#{@namespace}", (e)->
row = jQuery @
_this.setActiveRow(row)
_this.createMenuContext(row, event)
false
setModel: ->
@settings.contextMenu.model = @table.data(Lol.datatable["private"].dataset.modelName)
setTable: ->
@table = @settings.target
setTranslation: ->
jQuery.extend(
true,
@settings.configuration,
{
oLanguage:
oAria:
sSortAscending : Lol.t 'datatable_oAria_sSortAscending'
sSortDescending: Lol.t 'datatable_oAria_sSortDescending'
oPaginate:
sFirst : Lol.t 'datatable_oPaginate_sFirst'
sLast : Lol.t 'datatable_oPaginate_sLast'
sNext : Lol.t 'datatable_oPaginate_sNext'
sPrevious: Lol.t 'datatable_oPaginate_sPrevious'
sEmptyTable : Lol.t 'datatable_sEmptyTable'
sInfo : Lol.t 'datatable_sInfo'
sInfoEmpty : Lol.t 'datatable_sInfoEmpty'
sInfoFiltered : Lol.t 'datatable_sInfoFiltered'
sInfoPostFix : Lol.t 'datatable_sInfoPostFix'
sInfoThousands : Lol.t 'datatable_sInfoThousands'
sLengthMenu : Lol.t 'datatable_sLengthMenu'
sLoadingRecords: Lol.t 'datatable_sLoadingRecords'
sProcessing : Lol.t 'datatable_sProcessing'
sSearch : Lol.t 'datatable_sSearch'
sUrl : Lol.t 'datatable_sUrl'
sZeroRecords : Lol.t 'datatable_sZeroRecords'
}
)
unsetActiveRow: ()->
jQuery("tr.#{@settings.classes.activeRow}", @table).removeClass @settings.classes.activeRow
Lol.datatable =
## private configs
private:
dataset:
autoGenerate: 'lolDatatable'
link : 'datatableLink'
deleteLink : 'datatableDeleteLink'
editLink : 'datatableEditLink'
viewLink : 'datatableViewLink'
timeClicked : 'datatableClicked'
modelName : 'datatableModelName'
modelId : 'datatableModelId'
defaults:
###
Sets whether to print debug messages, such as sequences
of plays and creations, to facilitate the extension of
the code and bug fixes.
@type {Boolean}
###
debug : false
###
Sets up the "Datatable" must set the click event
on the table rows. This action adds a control class
to the table row.
@type {Boolean}
###
selectable : true
###
jQuery selector element to the table setting
@type {jQuery Selector}
###
target : null
###
Time delay the contextMenu is visible after the
mouse-hover event on the object
@type {Integer}
###
delayDblclick : 0
###
Object that stores the control classes of objects
of styles
@type {Object}
###
classes:
###
Class added after the event triggering
the selection line
@type {String}
###
activeRow : 'active_row'
###
Contains information generation contextMenu
and events, icons and other data
@type {Object}
###
contextMenu:
###
Every time the button is clicked the delete is
triggered a call to this method. What is done
in the process of exclusion in the database
through the model
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
delete: (row, object)->
window.lol_temp_fn_model_destroy = [row,object]
attrs =
"data-datatable-model-name": object.settings.contextMenu.model
"data-datatable-model-id" : row.data(Lol.datatable.private.dataset.modelId)
new Lol.Modal
buttons : 'OK_CANCEL'
content : Lol.t('datatable_confirm_delete')
title : Lol.t('datatable_confirm_delete_title')
callbacks:
buttonClick: (button, obj)->
obj.destroy()
buttonParams:
attributes:
OK: attrs
fn:
OK_CLICK: (event, obj)->
model = new Lol.model.reference[obj.button.data(Lol.datatable.private.dataset.modelName)]
model.set 'id', obj.button.data(Lol.datatable.private.dataset.modelId)
model.destroy Lol.model.destroy
false
###
Every time the button is clicked the
edit is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
edit: (row, object)->
object.debug row.data(object.dataset.editLink)
window.location = row.data(object.dataset.editLink)
false
###
Every time the button is clicked the
view is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
view: (row, object)->
window.location = row.data(object.dataset.viewLink)
false
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon button to view.
@type {String}
###
iconView : 'icon-eye-open'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button editing.
@type {String}
###
iconEdit : 'icon-edit'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button removal.
@type {String}
###
iconDelete : 'icon-remove'
###
Sets up the "Datatable" should use the icons for
better identification contextMenu or not.
@type {Boolean}
###
useIcons : true
###
Defines "String" from the class name of the model
of communication with the backend. It can be
configured by the attribute "given" by the syntax:
"datatable-data-model-name". See the example above.
@type {String}
###
model : null
###
Settings element DataTables. For further details
and functions of each element see official
documentation plugin
@see http://datatables.net/
@type {Object}
###
configuration:
aaSortingFixed : null
aoColumnDefs : null
aoColumns : null
asStripeClasses: null
bAutoWidth : true
bDeferRender : false
bDestroy : false
bFilter : false
bInfo : false
bJQueryUI : false
bLengthChange : false
bPaginate : false
bProcessing : false
bRetrieve : false
bScrollAutoCss : true
bScrollCollapse: false
bScrollInfinite: false
bServerSide : false
bSort : true
bSortCellsTop : false
bSortClasses : true
bStateSave : false
iCookieDuration: 7200
iDeferLoading : null
iDisplayLength : 20
iDisplayStart : 0
iScrollLoadGap : 100
iTabIndex : 0
sAjaxDataProp : "aaData"
sAjaxSource : null
sCookiePrefix : "SpryMedia_DataTables_"
sDom : "lfrtip"
sPaginationType: "two_button"
sScrollX : ""
sScrollXInner : ""
sScrollY : ""
sServerMethod : "GET"
jQuery ->
jQuery('[data-lol-datatable]').each ->
new Lol.Datatable
target: jQuery(@) | true | ###
@summary Lol Framework
@description Framework of RIAs applications
@version 1.0.0
@file Datatable.js
@author PI:NAME:<NAME>END_PI (http://welington.zaez.net/)
@contact http://welington.zaez.net/site/contato
@copyright Copyright 2012 PI:NAME:<NAME>END_PI, all rights reserved.
This source file is free software, under the license MIT, available at:
http://lolframework.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://welington.zaez.net
###
###
Create a new instance of Datatable.
@classDescription This class creates a new Datatable.
@param {Object} Receives configuration to create the Datatable, @see Lol.datatable.defaults
@return {Datatable} Returns a new Datatable.
@type {Object}
@example
*-* Auto configuration *-*
<table id="lol-datatable" data-lol-datatable="true" data-datatable-model-name="User">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr
data-datatable-link="http://welington.zaez.net/"
data-datatable-edit-link="#edit_my_page_ws"
data-datatable-view-link="#view_my_page_ws"
data-datatable-delete-link="#delete_my_page_ws"
data-datatable-model-id="1">
<td>1</td>
<td>PI:NAME:<NAME>END_PI</td>
<td>Sampaio</td>
</tr>
<tr
data-datatable-link="http://fabricio.zaez.net/"
data-datatable-edit-link="#edit_my_page_fm"
data-datatable-view-link="#view_my_page_fm"
data-datatable-delete-link="#delete_my_page_fm"
data-datatable-model-id="2">
<td>2</td>
<td>PI:NAME:<NAME>END_PI</td>
<td>PI:NAME:<NAME>END_PI</td>
</tr>
</tbody>
</table>
*-* Setting manually configuration *-*
var datatable = new Lol.Datatable({
debug: false,
selectable: true,
target: null,
delayDblclick: 0,
classes: {
activeRow: 'active_row'
},
contextMenu: {
"delete": function(row, object) {
//see documentation
},
edit: function(row, object) {
//see documentation
},
view: function(row, object) {
//see documentation
},
iconView: 'icon-eye-open',
iconEdit: 'icon-edit',
iconDelete: 'icon-remove',
useIcons: true,
model: null
},
configuration: {
aaSortingFixed: null,
aoColumnDefs: null,
aoColumns: null,
asStripeClasses: null,
bAutoWidth: true,
bDeferRender: false,
bDestroy: false,
bFilter: false,
bInfo: false,
bJQueryUI: false,
bLengthChange: false,
bPaginate: false,
bProcessing: false,
bRetrieve: false,
bScrollAutoCss: true,
bScrollCollapse: false,
bScrollInfinite: false,
bServerSide: false,
bSort: true,
bSortCellsTop: false,
bSortClasses: true,
bStateSave: false,
iCookieDuration: 7200,
iDeferLoading: null,
iDisplayLength: 20,
iDisplayStart: 0,
iScrollLoadGap: 100,
iTabIndex: 0,
sAjaxDataProp: "aaData",
sAjaxSource: null,
sCookiePrefix: "SpryMedia_DataTables_",
sDom: "lfrtip",
sPaginationType: "two_button",
sScrollX: "",
sScrollXInner: "",
sScrollY: "",
sServerMethod: "GET"
}
});
###
class Lol.Datatable extends Lol.Core
# declaration of variables
debugPrefix : 'Lol_Datatable'
namespace : '.datatable'
table : null
# the methods
constructor: (args={})->
throw 'Required jQuery library' if jQuery == undefined
@settings = jQuery.extend true, {}, Lol.datatable.defaults, args
@id = Lol.Utils.uniqid()
Lol.Utils.addObject @
@dataset = Lol.datatable.private.dataset
@setTable()
@setConfigTable()
@setModel()
@setTranslation()
@setAjax()
@generate()
@setEvents()
@
createMenuContext: (row, event)->
if row.data(@dataset.deleteLink) or row.data(@dataset.editLink) or row.data(@dataset.viewLink)
_this = @
context = jQuery "<div class='dropdown context-menu' id='context-menu-#{@id}'></div>"
context.css
left : event.pageX - 15
top : event.pageY - 15
context.bind
mouseleave: (event)->
jQuery(@).stop().delay(_this.settings.delayDblclick).animate {opacity: 0}, ->
jQuery(@).remove()
mouseenter: (event)->
jQuery(@).stop(true).animate {opacity: 1}
ul = jQuery '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">'
if ( row.data(@dataset.viewLink) )
view = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.viewLink)}'>#{Lol.t('datatable_view')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconView}'></i>").prependTo view.find('a') if @settings.contextMenu.useIcons
view.bind
click: ->
_this.settings.contextMenu.view row, _this
view.appendTo ul
if ( row.data(@dataset.editLink) )
edit = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.editLink)}'>#{Lol.t('datatable_edit')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconEdit}'></i>").prependTo edit.find('a') if @settings.contextMenu.useIcons
edit.bind
click: ->
_this.debug 'aki'
_this.settings.contextMenu.edit row, _this
edit.appendTo ul
if ( row.data(@dataset.deleteLink) )
remove = jQuery "<li><a tabindex='-1' href='#{row.data(@dataset.deleteLink)}'>#{Lol.t('datatable_delete')}</a></li>"
jQuery("<i class='#{@settings.contextMenu.iconDelete}'></i>").prependTo remove.find('a') if @settings.contextMenu.useIcons
remove.bind
click: ->
_this.settings.contextMenu.delete row, _this
remove.appendTo ul
ul.appendTo context
context.appendTo 'body'
generate: ->
@table.dataTable @settings.configuration
jQuery('.dataTables_filter input').attr('placeholder', Lol.t('datatable_search'))
$("<em class='arrow'></em>").appendTo @table.find('th')
getDt: ->
@table.dataTable()
goLink: (row)->
link = jQuery(row).data(@dataset.link)
Lol.Utils.redirector link if link
isRowActive: (row)->
row.hasClass @settings.classes.activeRow
setActiveRow: (row)->
@unsetActiveRow()
row.addClass @settings.classes.activeRow
row.data( @dataset.timeClicked, new Date().getTime() + @settings.delayDblclick )
setAjax: ->
if @table.data( @dataset.ajaxResource )
@settings.configuration.sAjaxSource = @table.data( @dataset.ajaxResource )
@settings.configuration.bProcessing = true
@settings.configuration.sServerMethod = @table.data( @dataset.ajaxMethod ) if @table.data( @dataset.ajaxMethod )
@settings.configuration.sAjaxDataProp = @table.data( @dataset.ajaxRoot ) if @table.data( @dataset.ajaxRoot )
setConfigTable: ->
@table.addClass 'lol-datatable'
setEvents: ->
_this = @
rows = "tbody tr"
@table.delegate rows, "click#{@namespace}", (e)->
row = jQuery @
if _this.isRowActive(row)
if row.data(_this.dataset.timeClicked) > new Date().getTime()
_this.goLink row
else
_this.unsetActiveRow(row)
else
_this.setActiveRow(row)
@table.delegate rows, "contextmenu#{@namespace}", (e)->
row = jQuery @
_this.setActiveRow(row)
_this.createMenuContext(row, event)
false
setModel: ->
@settings.contextMenu.model = @table.data(Lol.datatable["private"].dataset.modelName)
setTable: ->
@table = @settings.target
setTranslation: ->
jQuery.extend(
true,
@settings.configuration,
{
oLanguage:
oAria:
sSortAscending : Lol.t 'datatable_oAria_sSortAscending'
sSortDescending: Lol.t 'datatable_oAria_sSortDescending'
oPaginate:
sFirst : Lol.t 'datatable_oPaginate_sFirst'
sLast : Lol.t 'datatable_oPaginate_sLast'
sNext : Lol.t 'datatable_oPaginate_sNext'
sPrevious: Lol.t 'datatable_oPaginate_sPrevious'
sEmptyTable : Lol.t 'datatable_sEmptyTable'
sInfo : Lol.t 'datatable_sInfo'
sInfoEmpty : Lol.t 'datatable_sInfoEmpty'
sInfoFiltered : Lol.t 'datatable_sInfoFiltered'
sInfoPostFix : Lol.t 'datatable_sInfoPostFix'
sInfoThousands : Lol.t 'datatable_sInfoThousands'
sLengthMenu : Lol.t 'datatable_sLengthMenu'
sLoadingRecords: Lol.t 'datatable_sLoadingRecords'
sProcessing : Lol.t 'datatable_sProcessing'
sSearch : Lol.t 'datatable_sSearch'
sUrl : Lol.t 'datatable_sUrl'
sZeroRecords : Lol.t 'datatable_sZeroRecords'
}
)
unsetActiveRow: ()->
jQuery("tr.#{@settings.classes.activeRow}", @table).removeClass @settings.classes.activeRow
Lol.datatable =
## private configs
private:
dataset:
autoGenerate: 'lolDatatable'
link : 'datatableLink'
deleteLink : 'datatableDeleteLink'
editLink : 'datatableEditLink'
viewLink : 'datatableViewLink'
timeClicked : 'datatableClicked'
modelName : 'datatableModelName'
modelId : 'datatableModelId'
defaults:
###
Sets whether to print debug messages, such as sequences
of plays and creations, to facilitate the extension of
the code and bug fixes.
@type {Boolean}
###
debug : false
###
Sets up the "Datatable" must set the click event
on the table rows. This action adds a control class
to the table row.
@type {Boolean}
###
selectable : true
###
jQuery selector element to the table setting
@type {jQuery Selector}
###
target : null
###
Time delay the contextMenu is visible after the
mouse-hover event on the object
@type {Integer}
###
delayDblclick : 0
###
Object that stores the control classes of objects
of styles
@type {Object}
###
classes:
###
Class added after the event triggering
the selection line
@type {String}
###
activeRow : 'active_row'
###
Contains information generation contextMenu
and events, icons and other data
@type {Object}
###
contextMenu:
###
Every time the button is clicked the delete is
triggered a call to this method. What is done
in the process of exclusion in the database
through the model
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
delete: (row, object)->
window.lol_temp_fn_model_destroy = [row,object]
attrs =
"data-datatable-model-name": object.settings.contextMenu.model
"data-datatable-model-id" : row.data(Lol.datatable.private.dataset.modelId)
new Lol.Modal
buttons : 'OK_CANCEL'
content : Lol.t('datatable_confirm_delete')
title : Lol.t('datatable_confirm_delete_title')
callbacks:
buttonClick: (button, obj)->
obj.destroy()
buttonParams:
attributes:
OK: attrs
fn:
OK_CLICK: (event, obj)->
model = new Lol.model.reference[obj.button.data(Lol.datatable.private.dataset.modelName)]
model.set 'id', obj.button.data(Lol.datatable.private.dataset.modelId)
model.destroy Lol.model.destroy
false
###
Every time the button is clicked the
edit is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
edit: (row, object)->
object.debug row.data(object.dataset.editLink)
window.location = row.data(object.dataset.editLink)
false
###
Every time the button is clicked the
view is triggered a call to this method
@param {jQuery Selector} row
@param {Datatable} object
@type {Function}
###
view: (row, object)->
window.location = row.data(object.dataset.viewLink)
false
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon button to view.
@type {String}
###
iconView : 'icon-eye-open'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button editing.
@type {String}
###
iconEdit : 'icon-edit'
###
If enabled the use of icons in the contextMenu
is added an element "i" with the style class
for the configuration icon. This relates to the
icon of the button removal.
@type {String}
###
iconDelete : 'icon-remove'
###
Sets up the "Datatable" should use the icons for
better identification contextMenu or not.
@type {Boolean}
###
useIcons : true
###
Defines "String" from the class name of the model
of communication with the backend. It can be
configured by the attribute "given" by the syntax:
"datatable-data-model-name". See the example above.
@type {String}
###
model : null
###
Settings element DataTables. For further details
and functions of each element see official
documentation plugin
@see http://datatables.net/
@type {Object}
###
configuration:
aaSortingFixed : null
aoColumnDefs : null
aoColumns : null
asStripeClasses: null
bAutoWidth : true
bDeferRender : false
bDestroy : false
bFilter : false
bInfo : false
bJQueryUI : false
bLengthChange : false
bPaginate : false
bProcessing : false
bRetrieve : false
bScrollAutoCss : true
bScrollCollapse: false
bScrollInfinite: false
bServerSide : false
bSort : true
bSortCellsTop : false
bSortClasses : true
bStateSave : false
iCookieDuration: 7200
iDeferLoading : null
iDisplayLength : 20
iDisplayStart : 0
iScrollLoadGap : 100
iTabIndex : 0
sAjaxDataProp : "aaData"
sAjaxSource : null
sCookiePrefix : "SpryMedia_DataTables_"
sDom : "lfrtip"
sPaginationType: "two_button"
sScrollX : ""
sScrollXInner : ""
sScrollY : ""
sServerMethod : "GET"
jQuery ->
jQuery('[data-lol-datatable]').each ->
new Lol.Datatable
target: jQuery(@) |
[
{
"context": "s', ->\n expect(@subject.buildUrl('message', 'asd@asd.com')).to.eq('/messages/asd%40asd.com')\n \n ",
"end": 1408,
"score": 0.9999173283576965,
"start": 1397,
"tag": "EMAIL",
"value": "asd@asd.com"
}
] | test/rest/adapter.coffee | travisperson/coalesce | 18 | `import {postWithComments} from '../support/configs'`
`import Context from 'coalesce/rest/context'`
describe "RestAdapter", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
lazy 'session', -> @context.newSession()
subject -> @context.configFor('post').get('adapter')
describe '.mergePayload', ->
lazy 'data', ->
post: {id: 1, title: 'ma post', comments: [2, 3]}
comments: [{id: 2, body: 'yo'}, {id: 3, body: 'sup'}]
it 'should merge with typeKey as context', ->
post = @subject.mergePayload(@data, 'post', @session)[0]
expect(post.title).to.eq('ma post')
expect(post).to.eq(@session.getModel(post))
it 'should merge with no context', ->
models = @subject.mergePayload(@data, null, @session)
expect(models.size).to.eq(3)
describe '.ajaxOptions', ->
beforeEach ->
@subject.headers = {'X-HEY': 'ohai'}
it 'picks up headers from .headers', ->
hash = @subject.ajaxOptions('/api/test', 'GET', {})
expect(hash.beforeSend).to.not.be.null
xhr =
setRequestHeader: (key, value) -> @[key] = value
hash.beforeSend(xhr)
expect(xhr['X-HEY']).to.eq('ohai')
describe '.buildUrl', ->
it 'encodes ids', ->
expect(@subject.buildUrl('message', 'asd@asd.com')).to.eq('/messages/asd%40asd.com')
| 70517 | `import {postWithComments} from '../support/configs'`
`import Context from 'coalesce/rest/context'`
describe "RestAdapter", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
lazy 'session', -> @context.newSession()
subject -> @context.configFor('post').get('adapter')
describe '.mergePayload', ->
lazy 'data', ->
post: {id: 1, title: 'ma post', comments: [2, 3]}
comments: [{id: 2, body: 'yo'}, {id: 3, body: 'sup'}]
it 'should merge with typeKey as context', ->
post = @subject.mergePayload(@data, 'post', @session)[0]
expect(post.title).to.eq('ma post')
expect(post).to.eq(@session.getModel(post))
it 'should merge with no context', ->
models = @subject.mergePayload(@data, null, @session)
expect(models.size).to.eq(3)
describe '.ajaxOptions', ->
beforeEach ->
@subject.headers = {'X-HEY': 'ohai'}
it 'picks up headers from .headers', ->
hash = @subject.ajaxOptions('/api/test', 'GET', {})
expect(hash.beforeSend).to.not.be.null
xhr =
setRequestHeader: (key, value) -> @[key] = value
hash.beforeSend(xhr)
expect(xhr['X-HEY']).to.eq('ohai')
describe '.buildUrl', ->
it 'encodes ids', ->
expect(@subject.buildUrl('message', '<EMAIL>')).to.eq('/messages/asd%40asd.com')
| true | `import {postWithComments} from '../support/configs'`
`import Context from 'coalesce/rest/context'`
describe "RestAdapter", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
lazy 'session', -> @context.newSession()
subject -> @context.configFor('post').get('adapter')
describe '.mergePayload', ->
lazy 'data', ->
post: {id: 1, title: 'ma post', comments: [2, 3]}
comments: [{id: 2, body: 'yo'}, {id: 3, body: 'sup'}]
it 'should merge with typeKey as context', ->
post = @subject.mergePayload(@data, 'post', @session)[0]
expect(post.title).to.eq('ma post')
expect(post).to.eq(@session.getModel(post))
it 'should merge with no context', ->
models = @subject.mergePayload(@data, null, @session)
expect(models.size).to.eq(3)
describe '.ajaxOptions', ->
beforeEach ->
@subject.headers = {'X-HEY': 'ohai'}
it 'picks up headers from .headers', ->
hash = @subject.ajaxOptions('/api/test', 'GET', {})
expect(hash.beforeSend).to.not.be.null
xhr =
setRequestHeader: (key, value) -> @[key] = value
hash.beforeSend(xhr)
expect(xhr['X-HEY']).to.eq('ohai')
describe '.buildUrl', ->
it 'encodes ids', ->
expect(@subject.buildUrl('message', 'PI:EMAIL:<EMAIL>END_PI')).to.eq('/messages/asd%40asd.com')
|
[
{
"context": "ng categories\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hype",
"end": 97,
"score": 0.9992474317550659,
"start": 91,
"tag": "USERNAME",
"value": "nodize"
},
{
"context": "://github.com/nodize/nodizecms\n#\n# Copyright 2... | modules/ionize/helpers/helper_category.coffee | nodize/nodizecms | 32 | # Category helper, used to display existing categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#*****
#* Displaying categories,
#* use @category.title, .description, .subtitle... in nested views (fields from category_lang table)
#*
#**
@helpers['ion_categories'] = (args...) ->
tagName = 'ion_categories'
#
# We are launching an asynchronous request,
# we need to register it, to be able to wait for it to be finished
# and insert the content in the response sent to browser
#
requestId = @registerRequest( tagName )
#
# Finished callback
#
finished = (response) =>
@requestCompleted requestId, response
Category_lang.findAll({where:{lang:'en'}})
.on 'success', (categories) =>
#
# Content that will be built and sent
#
htmlResponse = ""
for category in categories
@category = category
#console.log @article.title
# Render nested tags
if args.length>=1
htmlResponse += cede args[args.length-1] # Compile the nested content to html
args[args.length-1]()
finished( htmlResponse )
.on 'failure', (err) ->
console.log "category request failed : ", err
finished()
#
# Inserting placeholder in the html for replacement once async request are finished
#
text "{**#{requestId.name}**}"
| 85131 | # Category helper, used to display existing categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#*****
#* Displaying categories,
#* use @category.title, .description, .subtitle... in nested views (fields from category_lang table)
#*
#**
@helpers['ion_categories'] = (args...) ->
tagName = 'ion_categories'
#
# We are launching an asynchronous request,
# we need to register it, to be able to wait for it to be finished
# and insert the content in the response sent to browser
#
requestId = @registerRequest( tagName )
#
# Finished callback
#
finished = (response) =>
@requestCompleted requestId, response
Category_lang.findAll({where:{lang:'en'}})
.on 'success', (categories) =>
#
# Content that will be built and sent
#
htmlResponse = ""
for category in categories
@category = category
#console.log @article.title
# Render nested tags
if args.length>=1
htmlResponse += cede args[args.length-1] # Compile the nested content to html
args[args.length-1]()
finished( htmlResponse )
.on 'failure', (err) ->
console.log "category request failed : ", err
finished()
#
# Inserting placeholder in the html for replacement once async request are finished
#
text "{**#{requestId.name}**}"
| true | # Category helper, used to display existing categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#*****
#* Displaying categories,
#* use @category.title, .description, .subtitle... in nested views (fields from category_lang table)
#*
#**
@helpers['ion_categories'] = (args...) ->
tagName = 'ion_categories'
#
# We are launching an asynchronous request,
# we need to register it, to be able to wait for it to be finished
# and insert the content in the response sent to browser
#
requestId = @registerRequest( tagName )
#
# Finished callback
#
finished = (response) =>
@requestCompleted requestId, response
Category_lang.findAll({where:{lang:'en'}})
.on 'success', (categories) =>
#
# Content that will be built and sent
#
htmlResponse = ""
for category in categories
@category = category
#console.log @article.title
# Render nested tags
if args.length>=1
htmlResponse += cede args[args.length-1] # Compile the nested content to html
args[args.length-1]()
finished( htmlResponse )
.on 'failure', (err) ->
console.log "category request failed : ", err
finished()
#
# Inserting placeholder in the html for replacement once async request are finished
#
text "{**#{requestId.name}**}"
|
[
{
"context": "lotMap: interactive plot of a genetic marker map\n# Karl W Broman\n\niplotMap = (data, chartOpts) ->\n\n # chartOpts",
"end": 68,
"score": 0.9998825192451477,
"start": 55,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/charts/iplotMap.coffee | FourchettesDeInterActive/qtlcharts | 0 | # iplotMap: interactive plot of a genetic marker map
# Karl W Broman
iplotMap = (data, chartOpts) ->
# chartOpts start
width = chartOpts?.width ? 1000 # width of chart in pixels
height = chartOpts?.height ? 600 # height of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:10} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? 5 # no. ticks on y-axis
yticks = chartOpts?.yticks ? null # vector of tick positions on y-axis
tickwidth = chartOpts?.tickwidth ? 10 # width of tick marks at markers, in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
linecolor = chartOpts?.linecolor ? "slateblue" # color of lines
linecolorhilit = chartOpts?.linecolorhilit ? "Orchid" # color of lines, when highlighted
linewidth = chartOpts?.linewidth ? 3 # width of lines
title = chartOpts?.title ? "" # title for chart
xlab = chartOpts?.xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? "Position (cM)" # y-axis label
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
mychart = mapchart().height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.yticks(yticks)
.nyticks(nyticks)
.tickwidth(tickwidth)
.rectcolor(rectcolor)
.linecolor(linecolor)
.linecolorhilit(linecolorhilit)
.linewidth(linewidth)
.title(title)
.xlab(xlab)
.ylab(ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mychart)
##############################
# code for marker search box for iplotMap
##############################
# reorganize map information by marker
markerpos = {}
for chr in data.chr
for marker of data.map[chr]
markerpos[marker] = {chr:chr, pos:data.map[chr][marker]}
# create marker tip
martip = d3.tip()
.attr('class', 'd3-tip')
.html((d) ->
pos = d3.format(".1f")(markerpos[d].pos)
"#{d} (#{pos})")
.direction('e')
.offset([0,10])
d3.select("div##{chartdivid} svg").call(martip)
clean_marker_name = (markername) ->
markername.replace(".", "\\.")
.replace("#", "\\#")
.replace("/", "\\/")
# grab selected marker from the search box
selectedMarker = ""
$("#markerinput").submit () ->
newSelection = document.getElementById("marker").value
event.preventDefault()
unless selectedMarker == ""
d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolor)
martip.hide()
if newSelection != ""
if data.markernames.indexOf(newSelection) >= 0
selectedMarker = newSelection
line = d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolorhilit)
martip.show(line.datum(), line.node())
d3.select("a#currentmarker")
.text("")
return true
else
d3.select("a#currentmarker")
.text("Marker \"#{newSelection}\" not found")
return false
# autocomplete
$('input#marker').autocomplete({
autoFocus: true,
source: (request, response) ->
matches = $.map(data.markernames, (tag) ->
tag if tag.toUpperCase().indexOf(request.term.toUpperCase()) is 0)
response(matches)
,
select: (event, ui) ->
$('input#marker').val(ui.item.label)
$('input#submit').submit()})
# grayed out "Marker name"
$('input#marker').each(() ->
$(this)
.data('default', $(this).val())
.addClass('inactive')
.focus(() ->
$(this).removeClass('inactive')
$(this).val('') if($(this).val() is $(this).data('default') or $(this).val() is '')
)
.blur(() ->
if($(this).val() is '')
$(this).addClass('inactive').val($(this).data('default'))
)
)
# on hover, remove tool tip from marker search
markerSelect = mychart.markerSelect()
markerSelect.on("mouseover", martip.hide)
| 167227 | # iplotMap: interactive plot of a genetic marker map
# <NAME>
iplotMap = (data, chartOpts) ->
# chartOpts start
width = chartOpts?.width ? 1000 # width of chart in pixels
height = chartOpts?.height ? 600 # height of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:10} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? 5 # no. ticks on y-axis
yticks = chartOpts?.yticks ? null # vector of tick positions on y-axis
tickwidth = chartOpts?.tickwidth ? 10 # width of tick marks at markers, in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
linecolor = chartOpts?.linecolor ? "slateblue" # color of lines
linecolorhilit = chartOpts?.linecolorhilit ? "Orchid" # color of lines, when highlighted
linewidth = chartOpts?.linewidth ? 3 # width of lines
title = chartOpts?.title ? "" # title for chart
xlab = chartOpts?.xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? "Position (cM)" # y-axis label
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
mychart = mapchart().height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.yticks(yticks)
.nyticks(nyticks)
.tickwidth(tickwidth)
.rectcolor(rectcolor)
.linecolor(linecolor)
.linecolorhilit(linecolorhilit)
.linewidth(linewidth)
.title(title)
.xlab(xlab)
.ylab(ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mychart)
##############################
# code for marker search box for iplotMap
##############################
# reorganize map information by marker
markerpos = {}
for chr in data.chr
for marker of data.map[chr]
markerpos[marker] = {chr:chr, pos:data.map[chr][marker]}
# create marker tip
martip = d3.tip()
.attr('class', 'd3-tip')
.html((d) ->
pos = d3.format(".1f")(markerpos[d].pos)
"#{d} (#{pos})")
.direction('e')
.offset([0,10])
d3.select("div##{chartdivid} svg").call(martip)
clean_marker_name = (markername) ->
markername.replace(".", "\\.")
.replace("#", "\\#")
.replace("/", "\\/")
# grab selected marker from the search box
selectedMarker = ""
$("#markerinput").submit () ->
newSelection = document.getElementById("marker").value
event.preventDefault()
unless selectedMarker == ""
d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolor)
martip.hide()
if newSelection != ""
if data.markernames.indexOf(newSelection) >= 0
selectedMarker = newSelection
line = d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolorhilit)
martip.show(line.datum(), line.node())
d3.select("a#currentmarker")
.text("")
return true
else
d3.select("a#currentmarker")
.text("Marker \"#{newSelection}\" not found")
return false
# autocomplete
$('input#marker').autocomplete({
autoFocus: true,
source: (request, response) ->
matches = $.map(data.markernames, (tag) ->
tag if tag.toUpperCase().indexOf(request.term.toUpperCase()) is 0)
response(matches)
,
select: (event, ui) ->
$('input#marker').val(ui.item.label)
$('input#submit').submit()})
# grayed out "Marker name"
$('input#marker').each(() ->
$(this)
.data('default', $(this).val())
.addClass('inactive')
.focus(() ->
$(this).removeClass('inactive')
$(this).val('') if($(this).val() is $(this).data('default') or $(this).val() is '')
)
.blur(() ->
if($(this).val() is '')
$(this).addClass('inactive').val($(this).data('default'))
)
)
# on hover, remove tool tip from marker search
markerSelect = mychart.markerSelect()
markerSelect.on("mouseover", martip.hide)
| true | # iplotMap: interactive plot of a genetic marker map
# PI:NAME:<NAME>END_PI
iplotMap = (data, chartOpts) ->
# chartOpts start
width = chartOpts?.width ? 1000 # width of chart in pixels
height = chartOpts?.height ? 600 # height of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:10} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? 5 # no. ticks on y-axis
yticks = chartOpts?.yticks ? null # vector of tick positions on y-axis
tickwidth = chartOpts?.tickwidth ? 10 # width of tick marks at markers, in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
linecolor = chartOpts?.linecolor ? "slateblue" # color of lines
linecolorhilit = chartOpts?.linecolorhilit ? "Orchid" # color of lines, when highlighted
linewidth = chartOpts?.linewidth ? 3 # width of lines
title = chartOpts?.title ? "" # title for chart
xlab = chartOpts?.xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? "Position (cM)" # y-axis label
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
mychart = mapchart().height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.yticks(yticks)
.nyticks(nyticks)
.tickwidth(tickwidth)
.rectcolor(rectcolor)
.linecolor(linecolor)
.linecolorhilit(linecolorhilit)
.linewidth(linewidth)
.title(title)
.xlab(xlab)
.ylab(ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mychart)
##############################
# code for marker search box for iplotMap
##############################
# reorganize map information by marker
markerpos = {}
for chr in data.chr
for marker of data.map[chr]
markerpos[marker] = {chr:chr, pos:data.map[chr][marker]}
# create marker tip
martip = d3.tip()
.attr('class', 'd3-tip')
.html((d) ->
pos = d3.format(".1f")(markerpos[d].pos)
"#{d} (#{pos})")
.direction('e')
.offset([0,10])
d3.select("div##{chartdivid} svg").call(martip)
clean_marker_name = (markername) ->
markername.replace(".", "\\.")
.replace("#", "\\#")
.replace("/", "\\/")
# grab selected marker from the search box
selectedMarker = ""
$("#markerinput").submit () ->
newSelection = document.getElementById("marker").value
event.preventDefault()
unless selectedMarker == ""
d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolor)
martip.hide()
if newSelection != ""
if data.markernames.indexOf(newSelection) >= 0
selectedMarker = newSelection
line = d3.select("line##{clean_marker_name(selectedMarker)}")
.attr("stroke", linecolorhilit)
martip.show(line.datum(), line.node())
d3.select("a#currentmarker")
.text("")
return true
else
d3.select("a#currentmarker")
.text("Marker \"#{newSelection}\" not found")
return false
# autocomplete
$('input#marker').autocomplete({
autoFocus: true,
source: (request, response) ->
matches = $.map(data.markernames, (tag) ->
tag if tag.toUpperCase().indexOf(request.term.toUpperCase()) is 0)
response(matches)
,
select: (event, ui) ->
$('input#marker').val(ui.item.label)
$('input#submit').submit()})
# grayed out "Marker name"
$('input#marker').each(() ->
$(this)
.data('default', $(this).val())
.addClass('inactive')
.focus(() ->
$(this).removeClass('inactive')
$(this).val('') if($(this).val() is $(this).data('default') or $(this).val() is '')
)
.blur(() ->
if($(this).val() is '')
$(this).addClass('inactive').val($(this).data('default'))
)
)
# on hover, remove tool tip from marker search
markerSelect = mychart.markerSelect()
markerSelect.on("mouseover", martip.hide)
|
[
{
"context": "###\nCoffeeLint\n\nCopyright (c) 2011 Matthew Perpick.\nCoffeeLint is freely distributable under the MIT",
"end": 50,
"score": 0.9998656511306763,
"start": 35,
"tag": "NAME",
"value": "Matthew Perpick"
}
] | node_modules/coffeelint/src/commandline.coffee | Xeodee/absorbCSS | 2,761 | ###
CoffeeLint
Copyright (c) 2011 Matthew Perpick.
CoffeeLint is freely distributable under the MIT license.
###
resolve = require('resolve').sync
path = require('path')
fs = require('fs')
os = require('os')
glob = require('glob')
optimist = require('optimist')
ignore = require('ignore')
stripComments = require('strip-json-comments')
thisdir = path.dirname(fs.realpathSync(__filename))
coffeelint = require(path.join(thisdir, 'coffeelint'))
configfinder = require(path.join(thisdir, 'configfinder'))
ruleLoader = require(path.join(thisdir, 'ruleLoader'))
Cache = require(path.join(thisdir, 'cache'))
CoffeeScript = require 'coffee-script'
CoffeeScript.register()
log = ->
# coffeelint: disable=no_debugger
console.log(arguments...)
# coffeelint: enable=no_debugger
jsonIndentation = 2
logConfig = (config) ->
filter = (k, v) -> v unless k in ['message', 'description', 'name']
log(JSON.stringify(config, filter, jsonIndentation))
# Return the contents of the given file synchronously.
read = (path) ->
realPath = fs.realpathSync(path)
return fs.readFileSync(realPath).toString()
# build all extentions to search
getAllExtention = (extension) ->
if extension?
extension = ['coffee'].concat(extension?.split(','))
"@(#{extension.join('|')})"
else
'coffee'
# Return a list of CoffeeScript's in the given paths.
findCoffeeScripts = (paths, extension) ->
files = []
allExtention = getAllExtention(extension)
for p in paths
if fs.statSync(p).isDirectory()
# The glob library only uses forward slashes.
files = files.concat(glob.sync("#{p}/**/*.#{allExtention}"))
else
files.push(p)
return files
# Return an error report from linting the given paths.
lintFiles = (files, config) ->
errorReport = new coffeelint.getErrorReport()
for file in files
source = read(file)
literate = CoffeeScript.helpers.isLiterate file
fileConfig = if config then config else getFallbackConfig(file)
errorReport.lint(file, source, fileConfig, literate)
return errorReport
# Return an error report from linting the given coffeescript source.
lintSource = (source, config, literate = false) ->
errorReport = new coffeelint.getErrorReport()
config or= getFallbackConfig()
errorReport.lint('stdin', source, config, literate)
return errorReport
# Load a config file given a path/filename
readConfigFile = (path) ->
text = read(path)
try
jsonIndentation = text.split('\n')[1].match(/^\s+/)[0].length
JSON.parse(stripComments(text))
loadConfig = (options) ->
config = null
unless options.argv.noconfig
if options.argv.f
config = readConfigFile(options.argv.f)
# If -f was specifying a package.json, extract the config
if config.coffeelintConfig
config = config.coffeelintConfig
config
# Get fallback configuration. With the -F flag found configs in standard places
# will be used for each file being linted. Standard places are package.json or
# coffeelint.json in a project's root folder or the user's home folder.
getFallbackConfig = (filename = null) ->
unless options.argv.noconfig
configfinder.getConfig(filename)
# These reporters are usually parsed by other software, so I can't just echo a
# warning. Creating a fake file is my best attempt.
deprecatedReporter = (errorReport, reporter) ->
errorReport.paths['coffeelint_fake_file.coffee'] ?= []
errorReport.paths['coffeelint_fake_file.coffee'].push {
'level': 'warn'
'rule': 'commandline'
'message': "parameter --#{reporter} is deprecated.
Use --reporter #{reporter} instead"
'lineNumber': 0
}
return reporter
coreReporters =
default: require(path.join(thisdir, 'reporters', 'default'))
csv: require(path.join(thisdir, 'reporters', 'csv'))
jslint: require(path.join(thisdir, 'reporters', 'jslint'))
checkstyle: require(path.join(thisdir, 'reporters', 'checkstyle'))
raw: require(path.join(thisdir, 'reporters', 'raw'))
# Publish the error report and exit with the appropriate status.
reportAndExit = (errorReport, options) ->
strReporter = if options.argv.jslint
deprecatedReporter(errorReport, 'jslint')
else if options.argv.csv
deprecatedReporter(errorReport, 'csv')
else if options.argv.checkstyle
deprecatedReporter(errorReport, 'checkstyle')
else
options.argv.reporter
strReporter ?= 'default'
SelectedReporter = coreReporters[strReporter] ? do ->
try
reporterPath = resolve strReporter, {
basedir: process.cwd()
}
catch
reporterPath = strReporter
require reporterPath
options.argv.color ?= if options.argv.nocolor then 'never' else 'auto'
colorize = switch options.argv.color
when 'always' then true
when 'never' then false
else process.stdout.isTTY
reporter = new SelectedReporter errorReport, {
colorize: colorize
quiet: options.argv.q
}
reporter.publish()
process.on 'exit', () ->
process.exit errorReport.getExitCode()
# Declare command line options.
options = optimist
.usage('Usage: coffeelint [options] source [...]')
.alias('f', 'file')
.alias('h', 'help')
.alias('v', 'version')
.alias('s', 'stdin')
.alias('q', 'quiet')
.alias('c', 'cache')
.describe('f', 'Specify a custom configuration file.')
.describe('rules', 'Specify a custom rule or directory of rules.')
.describe('makeconfig', 'Prints a default config file')
.describe('trimconfig', 'Compares your config with the default and
prints a minimal configuration')
.describe('noconfig', 'Ignores any config file.')
.describe('h', 'Print help information.')
.describe('v', 'Print current version number.')
.describe('r', '(not used, but left for backward compatibility)')
.describe('reporter', 'built in reporter (default, csv, jslint,
checkstyle, raw), or module, or path to reporter file.')
.describe('csv', '[deprecated] use --reporter csv')
.describe('jslint', '[deprecated] use --reporter jslint')
.describe('nocolor', '[deprecated] use --color=never')
.describe('checkstyle', '[deprecated] use --reporter checkstyle')
.describe('color=<when>',
'When to colorize the output. <when> can be one of always, never \
, or auto.')
.describe('s', 'Lint the source from stdin')
.describe('q', 'Only print errors.')
.describe('literate',
'Used with --stdin to process as Literate CoffeeScript')
.describe('c', 'Cache linting results')
.describe('ext',
'Specify an additional file extension, separated by comma.')
.boolean('csv')
.boolean('jslint')
.boolean('checkstyle')
.boolean('nocolor')
.boolean('noconfig')
.boolean('makeconfig')
.boolean('trimconfig')
.boolean('literate')
.boolean('r')
.boolean('s')
.boolean('q', 'Print errors only.')
.boolean('c')
if options.argv.v
log coffeelint.VERSION
process.exit(0)
else if options.argv.h
options.showHelp()
process.exit(0)
else if options.argv.trimconfig
userConfig = loadConfig(options) ? getFallbackConfig()
logConfig(coffeelint.trimConfig(userConfig))
else if options.argv.makeconfig
logConfig(coffeelint.getRules())
else if options.argv._.length < 1 and not options.argv.s
options.showHelp()
process.exit(1)
else
# Initialize cache, if enabled
if options.argv.cache
coffeelint.setCache new Cache(path.join(os.tmpdir(), 'coffeelint'))
# Load configuration.
config = loadConfig(options)
ruleLoader.loadRule(coffeelint, options.argv.rules) if options.argv.rules
if options.argv.s
# Lint from stdin
data = ''
stdin = process.openStdin()
stdin.on 'data', (buffer) ->
data += buffer.toString() if buffer
stdin.on 'end', ->
errorReport = lintSource(data, config, options.argv.literate)
reportAndExit errorReport, options
else
# Find scripts to lint.
paths = options.argv._
scripts = findCoffeeScripts(paths, options.argv.ext)
scripts = ignore().addIgnoreFile('.coffeelintignore').filter(scripts)
# Lint the code.
errorReport = lintFiles(scripts, config, options.argv.literate)
reportAndExit errorReport, options
| 28388 | ###
CoffeeLint
Copyright (c) 2011 <NAME>.
CoffeeLint is freely distributable under the MIT license.
###
resolve = require('resolve').sync
path = require('path')
fs = require('fs')
os = require('os')
glob = require('glob')
optimist = require('optimist')
ignore = require('ignore')
stripComments = require('strip-json-comments')
thisdir = path.dirname(fs.realpathSync(__filename))
coffeelint = require(path.join(thisdir, 'coffeelint'))
configfinder = require(path.join(thisdir, 'configfinder'))
ruleLoader = require(path.join(thisdir, 'ruleLoader'))
Cache = require(path.join(thisdir, 'cache'))
CoffeeScript = require 'coffee-script'
CoffeeScript.register()
log = ->
# coffeelint: disable=no_debugger
console.log(arguments...)
# coffeelint: enable=no_debugger
jsonIndentation = 2
logConfig = (config) ->
filter = (k, v) -> v unless k in ['message', 'description', 'name']
log(JSON.stringify(config, filter, jsonIndentation))
# Return the contents of the given file synchronously.
read = (path) ->
realPath = fs.realpathSync(path)
return fs.readFileSync(realPath).toString()
# build all extentions to search
getAllExtention = (extension) ->
if extension?
extension = ['coffee'].concat(extension?.split(','))
"@(#{extension.join('|')})"
else
'coffee'
# Return a list of CoffeeScript's in the given paths.
findCoffeeScripts = (paths, extension) ->
files = []
allExtention = getAllExtention(extension)
for p in paths
if fs.statSync(p).isDirectory()
# The glob library only uses forward slashes.
files = files.concat(glob.sync("#{p}/**/*.#{allExtention}"))
else
files.push(p)
return files
# Return an error report from linting the given paths.
lintFiles = (files, config) ->
errorReport = new coffeelint.getErrorReport()
for file in files
source = read(file)
literate = CoffeeScript.helpers.isLiterate file
fileConfig = if config then config else getFallbackConfig(file)
errorReport.lint(file, source, fileConfig, literate)
return errorReport
# Return an error report from linting the given coffeescript source.
lintSource = (source, config, literate = false) ->
errorReport = new coffeelint.getErrorReport()
config or= getFallbackConfig()
errorReport.lint('stdin', source, config, literate)
return errorReport
# Load a config file given a path/filename
readConfigFile = (path) ->
text = read(path)
try
jsonIndentation = text.split('\n')[1].match(/^\s+/)[0].length
JSON.parse(stripComments(text))
loadConfig = (options) ->
config = null
unless options.argv.noconfig
if options.argv.f
config = readConfigFile(options.argv.f)
# If -f was specifying a package.json, extract the config
if config.coffeelintConfig
config = config.coffeelintConfig
config
# Get fallback configuration. With the -F flag found configs in standard places
# will be used for each file being linted. Standard places are package.json or
# coffeelint.json in a project's root folder or the user's home folder.
getFallbackConfig = (filename = null) ->
unless options.argv.noconfig
configfinder.getConfig(filename)
# These reporters are usually parsed by other software, so I can't just echo a
# warning. Creating a fake file is my best attempt.
deprecatedReporter = (errorReport, reporter) ->
errorReport.paths['coffeelint_fake_file.coffee'] ?= []
errorReport.paths['coffeelint_fake_file.coffee'].push {
'level': 'warn'
'rule': 'commandline'
'message': "parameter --#{reporter} is deprecated.
Use --reporter #{reporter} instead"
'lineNumber': 0
}
return reporter
coreReporters =
default: require(path.join(thisdir, 'reporters', 'default'))
csv: require(path.join(thisdir, 'reporters', 'csv'))
jslint: require(path.join(thisdir, 'reporters', 'jslint'))
checkstyle: require(path.join(thisdir, 'reporters', 'checkstyle'))
raw: require(path.join(thisdir, 'reporters', 'raw'))
# Publish the error report and exit with the appropriate status.
reportAndExit = (errorReport, options) ->
strReporter = if options.argv.jslint
deprecatedReporter(errorReport, 'jslint')
else if options.argv.csv
deprecatedReporter(errorReport, 'csv')
else if options.argv.checkstyle
deprecatedReporter(errorReport, 'checkstyle')
else
options.argv.reporter
strReporter ?= 'default'
SelectedReporter = coreReporters[strReporter] ? do ->
try
reporterPath = resolve strReporter, {
basedir: process.cwd()
}
catch
reporterPath = strReporter
require reporterPath
options.argv.color ?= if options.argv.nocolor then 'never' else 'auto'
colorize = switch options.argv.color
when 'always' then true
when 'never' then false
else process.stdout.isTTY
reporter = new SelectedReporter errorReport, {
colorize: colorize
quiet: options.argv.q
}
reporter.publish()
process.on 'exit', () ->
process.exit errorReport.getExitCode()
# Declare command line options.
options = optimist
.usage('Usage: coffeelint [options] source [...]')
.alias('f', 'file')
.alias('h', 'help')
.alias('v', 'version')
.alias('s', 'stdin')
.alias('q', 'quiet')
.alias('c', 'cache')
.describe('f', 'Specify a custom configuration file.')
.describe('rules', 'Specify a custom rule or directory of rules.')
.describe('makeconfig', 'Prints a default config file')
.describe('trimconfig', 'Compares your config with the default and
prints a minimal configuration')
.describe('noconfig', 'Ignores any config file.')
.describe('h', 'Print help information.')
.describe('v', 'Print current version number.')
.describe('r', '(not used, but left for backward compatibility)')
.describe('reporter', 'built in reporter (default, csv, jslint,
checkstyle, raw), or module, or path to reporter file.')
.describe('csv', '[deprecated] use --reporter csv')
.describe('jslint', '[deprecated] use --reporter jslint')
.describe('nocolor', '[deprecated] use --color=never')
.describe('checkstyle', '[deprecated] use --reporter checkstyle')
.describe('color=<when>',
'When to colorize the output. <when> can be one of always, never \
, or auto.')
.describe('s', 'Lint the source from stdin')
.describe('q', 'Only print errors.')
.describe('literate',
'Used with --stdin to process as Literate CoffeeScript')
.describe('c', 'Cache linting results')
.describe('ext',
'Specify an additional file extension, separated by comma.')
.boolean('csv')
.boolean('jslint')
.boolean('checkstyle')
.boolean('nocolor')
.boolean('noconfig')
.boolean('makeconfig')
.boolean('trimconfig')
.boolean('literate')
.boolean('r')
.boolean('s')
.boolean('q', 'Print errors only.')
.boolean('c')
if options.argv.v
log coffeelint.VERSION
process.exit(0)
else if options.argv.h
options.showHelp()
process.exit(0)
else if options.argv.trimconfig
userConfig = loadConfig(options) ? getFallbackConfig()
logConfig(coffeelint.trimConfig(userConfig))
else if options.argv.makeconfig
logConfig(coffeelint.getRules())
else if options.argv._.length < 1 and not options.argv.s
options.showHelp()
process.exit(1)
else
# Initialize cache, if enabled
if options.argv.cache
coffeelint.setCache new Cache(path.join(os.tmpdir(), 'coffeelint'))
# Load configuration.
config = loadConfig(options)
ruleLoader.loadRule(coffeelint, options.argv.rules) if options.argv.rules
if options.argv.s
# Lint from stdin
data = ''
stdin = process.openStdin()
stdin.on 'data', (buffer) ->
data += buffer.toString() if buffer
stdin.on 'end', ->
errorReport = lintSource(data, config, options.argv.literate)
reportAndExit errorReport, options
else
# Find scripts to lint.
paths = options.argv._
scripts = findCoffeeScripts(paths, options.argv.ext)
scripts = ignore().addIgnoreFile('.coffeelintignore').filter(scripts)
# Lint the code.
errorReport = lintFiles(scripts, config, options.argv.literate)
reportAndExit errorReport, options
| true | ###
CoffeeLint
Copyright (c) 2011 PI:NAME:<NAME>END_PI.
CoffeeLint is freely distributable under the MIT license.
###
resolve = require('resolve').sync
path = require('path')
fs = require('fs')
os = require('os')
glob = require('glob')
optimist = require('optimist')
ignore = require('ignore')
stripComments = require('strip-json-comments')
thisdir = path.dirname(fs.realpathSync(__filename))
coffeelint = require(path.join(thisdir, 'coffeelint'))
configfinder = require(path.join(thisdir, 'configfinder'))
ruleLoader = require(path.join(thisdir, 'ruleLoader'))
Cache = require(path.join(thisdir, 'cache'))
CoffeeScript = require 'coffee-script'
CoffeeScript.register()
log = ->
# coffeelint: disable=no_debugger
console.log(arguments...)
# coffeelint: enable=no_debugger
jsonIndentation = 2
logConfig = (config) ->
filter = (k, v) -> v unless k in ['message', 'description', 'name']
log(JSON.stringify(config, filter, jsonIndentation))
# Return the contents of the given file synchronously.
read = (path) ->
realPath = fs.realpathSync(path)
return fs.readFileSync(realPath).toString()
# build all extentions to search
getAllExtention = (extension) ->
if extension?
extension = ['coffee'].concat(extension?.split(','))
"@(#{extension.join('|')})"
else
'coffee'
# Return a list of CoffeeScript's in the given paths.
findCoffeeScripts = (paths, extension) ->
files = []
allExtention = getAllExtention(extension)
for p in paths
if fs.statSync(p).isDirectory()
# The glob library only uses forward slashes.
files = files.concat(glob.sync("#{p}/**/*.#{allExtention}"))
else
files.push(p)
return files
# Return an error report from linting the given paths.
lintFiles = (files, config) ->
errorReport = new coffeelint.getErrorReport()
for file in files
source = read(file)
literate = CoffeeScript.helpers.isLiterate file
fileConfig = if config then config else getFallbackConfig(file)
errorReport.lint(file, source, fileConfig, literate)
return errorReport
# Return an error report from linting the given coffeescript source.
lintSource = (source, config, literate = false) ->
errorReport = new coffeelint.getErrorReport()
config or= getFallbackConfig()
errorReport.lint('stdin', source, config, literate)
return errorReport
# Load a config file given a path/filename
readConfigFile = (path) ->
text = read(path)
try
jsonIndentation = text.split('\n')[1].match(/^\s+/)[0].length
JSON.parse(stripComments(text))
loadConfig = (options) ->
config = null
unless options.argv.noconfig
if options.argv.f
config = readConfigFile(options.argv.f)
# If -f was specifying a package.json, extract the config
if config.coffeelintConfig
config = config.coffeelintConfig
config
# Get fallback configuration. With the -F flag found configs in standard places
# will be used for each file being linted. Standard places are package.json or
# coffeelint.json in a project's root folder or the user's home folder.
getFallbackConfig = (filename = null) ->
unless options.argv.noconfig
configfinder.getConfig(filename)
# These reporters are usually parsed by other software, so I can't just echo a
# warning. Creating a fake file is my best attempt.
deprecatedReporter = (errorReport, reporter) ->
errorReport.paths['coffeelint_fake_file.coffee'] ?= []
errorReport.paths['coffeelint_fake_file.coffee'].push {
'level': 'warn'
'rule': 'commandline'
'message': "parameter --#{reporter} is deprecated.
Use --reporter #{reporter} instead"
'lineNumber': 0
}
return reporter
coreReporters =
default: require(path.join(thisdir, 'reporters', 'default'))
csv: require(path.join(thisdir, 'reporters', 'csv'))
jslint: require(path.join(thisdir, 'reporters', 'jslint'))
checkstyle: require(path.join(thisdir, 'reporters', 'checkstyle'))
raw: require(path.join(thisdir, 'reporters', 'raw'))
# Publish the error report and exit with the appropriate status.
reportAndExit = (errorReport, options) ->
strReporter = if options.argv.jslint
deprecatedReporter(errorReport, 'jslint')
else if options.argv.csv
deprecatedReporter(errorReport, 'csv')
else if options.argv.checkstyle
deprecatedReporter(errorReport, 'checkstyle')
else
options.argv.reporter
strReporter ?= 'default'
SelectedReporter = coreReporters[strReporter] ? do ->
try
reporterPath = resolve strReporter, {
basedir: process.cwd()
}
catch
reporterPath = strReporter
require reporterPath
options.argv.color ?= if options.argv.nocolor then 'never' else 'auto'
colorize = switch options.argv.color
when 'always' then true
when 'never' then false
else process.stdout.isTTY
reporter = new SelectedReporter errorReport, {
colorize: colorize
quiet: options.argv.q
}
reporter.publish()
process.on 'exit', () ->
process.exit errorReport.getExitCode()
# Declare command line options.
options = optimist
.usage('Usage: coffeelint [options] source [...]')
.alias('f', 'file')
.alias('h', 'help')
.alias('v', 'version')
.alias('s', 'stdin')
.alias('q', 'quiet')
.alias('c', 'cache')
.describe('f', 'Specify a custom configuration file.')
.describe('rules', 'Specify a custom rule or directory of rules.')
.describe('makeconfig', 'Prints a default config file')
.describe('trimconfig', 'Compares your config with the default and
prints a minimal configuration')
.describe('noconfig', 'Ignores any config file.')
.describe('h', 'Print help information.')
.describe('v', 'Print current version number.')
.describe('r', '(not used, but left for backward compatibility)')
.describe('reporter', 'built in reporter (default, csv, jslint,
checkstyle, raw), or module, or path to reporter file.')
.describe('csv', '[deprecated] use --reporter csv')
.describe('jslint', '[deprecated] use --reporter jslint')
.describe('nocolor', '[deprecated] use --color=never')
.describe('checkstyle', '[deprecated] use --reporter checkstyle')
.describe('color=<when>',
'When to colorize the output. <when> can be one of always, never \
, or auto.')
.describe('s', 'Lint the source from stdin')
.describe('q', 'Only print errors.')
.describe('literate',
'Used with --stdin to process as Literate CoffeeScript')
.describe('c', 'Cache linting results')
.describe('ext',
'Specify an additional file extension, separated by comma.')
.boolean('csv')
.boolean('jslint')
.boolean('checkstyle')
.boolean('nocolor')
.boolean('noconfig')
.boolean('makeconfig')
.boolean('trimconfig')
.boolean('literate')
.boolean('r')
.boolean('s')
.boolean('q', 'Print errors only.')
.boolean('c')
if options.argv.v
log coffeelint.VERSION
process.exit(0)
else if options.argv.h
options.showHelp()
process.exit(0)
else if options.argv.trimconfig
userConfig = loadConfig(options) ? getFallbackConfig()
logConfig(coffeelint.trimConfig(userConfig))
else if options.argv.makeconfig
logConfig(coffeelint.getRules())
else if options.argv._.length < 1 and not options.argv.s
options.showHelp()
process.exit(1)
else
# Initialize cache, if enabled
if options.argv.cache
coffeelint.setCache new Cache(path.join(os.tmpdir(), 'coffeelint'))
# Load configuration.
config = loadConfig(options)
ruleLoader.loadRule(coffeelint, options.argv.rules) if options.argv.rules
if options.argv.s
# Lint from stdin
data = ''
stdin = process.openStdin()
stdin.on 'data', (buffer) ->
data += buffer.toString() if buffer
stdin.on 'end', ->
errorReport = lintSource(data, config, options.argv.literate)
reportAndExit errorReport, options
else
# Find scripts to lint.
paths = options.argv._
scripts = findCoffeeScripts(paths, options.argv.ext)
scripts = ignore().addIgnoreFile('.coffeelintignore').filter(scripts)
# Lint the code.
errorReport = lintFiles(scripts, config, options.argv.literate)
reportAndExit errorReport, options
|
[
{
"context": "require('../Set')\n\n#names = new Set()\n#names.add(\"David\")\n#names.add(\"Jennifer\")\n#names.add(\"Cynthia\")\n#n",
"end": 61,
"score": 0.9998612999916077,
"start": 56,
"tag": "NAME",
"value": "David"
},
{
"context": "names = new Set()\n#names.add(\"David\")\n#names... | set/test/method.coffee | youqingkui/DataStructure | 0 | Set = require('../Set')
#names = new Set()
#names.add("David")
#names.add("Jennifer")
#names.add("Cynthia")
#names.add("Mike")
#names.add("Raymond")
#if names.add "Mike"
# console.log "Mike added"
#else
# console.log "Can't add Mike, must already be in set"
#
#
#console.log names.show()
#
#removed = "Mike"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
#
#
#names.add "Clayton"
#console.log names.show()
#
#removed = "Alisa"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
cis = new Set()
cis.add("Mike")
cis.add("Clayton")
cis.add("Jennifer")
cis.add("Raymond")
console.log "cis =>", cis.show()
dmp = new Set()
dmp.add("Raymond")
dmp.add("Cynthia")
dmp.add("Jonathan")
console.log "dmp =>", dmp.show()
it = new Set()
it = cis.intersect(dmp)
console.log (it.show())
| 190383 | Set = require('../Set')
#names = new Set()
#names.add("<NAME>")
#names.add("<NAME>")
#names.add("<NAME>")
#names.add("<NAME>")
#names.add("<NAME>")
#if names.add "<NAME>"
# console.log "<NAME> added"
#else
# console.log "Can't add <NAME>, must already be in set"
#
#
#console.log names.show()
#
#removed = "<NAME>"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
#
#
#names.add "<NAME>"
#console.log names.show()
#
#removed = "<NAME>"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
cis = new Set()
cis.add("<NAME>")
cis.add("<NAME>")
cis.add("<NAME>")
cis.add("<NAME>")
console.log "cis =>", cis.show()
dmp = new Set()
dmp.add("<NAME>")
dmp.add("<NAME>")
dmp.add("<NAME>")
console.log "dmp =>", dmp.show()
it = new Set()
it = cis.intersect(dmp)
console.log (it.show())
| true | Set = require('../Set')
#names = new Set()
#names.add("PI:NAME:<NAME>END_PI")
#names.add("PI:NAME:<NAME>END_PI")
#names.add("PI:NAME:<NAME>END_PI")
#names.add("PI:NAME:<NAME>END_PI")
#names.add("PI:NAME:<NAME>END_PI")
#if names.add "PI:NAME:<NAME>END_PI"
# console.log "PI:NAME:<NAME>END_PI added"
#else
# console.log "Can't add PI:NAME:<NAME>END_PI, must already be in set"
#
#
#console.log names.show()
#
#removed = "PI:NAME:<NAME>END_PI"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
#
#
#names.add "PI:NAME:<NAME>END_PI"
#console.log names.show()
#
#removed = "PI:NAME:<NAME>END_PI"
#if names.remove(removed)
# console.log removed + " removed."
#
#else
# console.log removed + " not removed."
cis = new Set()
cis.add("PI:NAME:<NAME>END_PI")
cis.add("PI:NAME:<NAME>END_PI")
cis.add("PI:NAME:<NAME>END_PI")
cis.add("PI:NAME:<NAME>END_PI")
console.log "cis =>", cis.show()
dmp = new Set()
dmp.add("PI:NAME:<NAME>END_PI")
dmp.add("PI:NAME:<NAME>END_PI")
dmp.add("PI:NAME:<NAME>END_PI")
console.log "dmp =>", dmp.show()
it = new Set()
it = cis.intersect(dmp)
console.log (it.show())
|
[
{
"context": "et et sw=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i@binux.me>\n# http://binux.me\n# Created o",
"end": 64,
"score": 0.956264853477478,
"start": 59,
"tag": "USERNAME",
"value": "Binux"
},
{
"context": "w=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i@... | web/static/har/entry_editor.coffee | js882829/qiandao-1 | 9 | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2014-08-06 21:16:15
define (require, exports, module) ->
require '/static/har/contenteditable'
require '/static/har/editablelist'
utils = require '/static/utils'
angular.module('entry_editor', [
'contenteditable'
]).controller('EntryCtrl', ($scope, $rootScope, $sce, $http) ->
# init
$scope.panel = 'request'
$scope.copy_entry = null
# on edit event
$scope.$on('edit-entry', (ev, entry) ->
console.info(entry)
$scope.entry = entry
$scope.entry.success_asserts ?= [{re: '' + $scope.entry.response.status, from: 'status'},]
$scope.entry.failed_asserts ?= []
$scope.entry.extract_variables ?= []
$scope.copy_entry = JSON.parse(utils.storage.get('copy_request'))
angular.element('#edit-entry').modal('show')
$scope.alert_hide()
)
# on saved event
angular.element('#edit-entry').on('hidden.bs.modal', (ev) ->
if $scope.panel in ['preview-headers', 'preview']
$scope.$apply ->
$scope.panel = 'test'
# update env from extract_variables
env = utils.list2dict($scope.env)
for rule in $scope.entry.extract_variables
if ret = $scope.preview_match(rule.re, rule.from)
env[rule.name] = ret
$scope.env = utils.dict2list(env)
$scope.$apply ->
$scope.preview = undefined
console.debug('har-change')
$rootScope.$broadcast('har-change')
)
# alert message for test panel
$scope.alert = (message) ->
angular.element('.panel-test .alert').text(message).show()
$scope.alert_hide = () ->
angular.element('.panel-test .alert').hide()
# sync url with query string
changing = ''
$scope.$watch('entry.request.url', () ->
if changing and changing != 'url'
changing = ''
return
if not $scope.entry?
return
try
queryString = utils.dict2list(utils.querystring_parse_with_variables(utils.url_parse($scope.entry.request.url).query))
catch error
queryString = []
if not changing and not angular.equals(queryString, $scope.entry.request.queryString)
$scope.entry.request.queryString = queryString
changing = 'url'
)
# sync query string with url
$scope.$watch('entry.request.queryString', (() ->
if changing and changing != 'qs'
changing = ''
return
if not $scope.entry?
return
url = utils.url_parse($scope.entry.request.url)
query = utils.list2dict($scope.entry.request.queryString)
query = utils.querystring_unparse_with_variables(query)
url.search = "?#{query}" if query
url = utils.url_unparse(url)
if not changing and url != $scope.entry.request.url
$scope.entry.request.url = url
changing = 'qs'
), true)
# sync params with text
$scope.$watch('entry.request.postData.params', (() ->
if not $scope.entry?.request?.postData?
return
obj = utils.list2dict($scope.entry.request.postData.params)
$scope.entry.request.postData.text = utils.querystring_unparse_with_variables(obj)
), true)
# helper for delete item from array
$scope.delete = (hashKey, array) ->
for each, index in array
if each.$$hashKey == hashKey
array.splice(index, 1)
return
# variables template
$scope.variables_wrapper = (string, place_holder = '') ->
string = (string or place_holder).toString()
re = /{{\s*([\w]+)[^}]*?\s*}}/g
$sce.trustAsHtml(string.replace(re, '<span class="label label-primary">$&</span>'))
$scope.insert_request = (pos, entry)->
pos ?= 1
if (current_pos = $scope.$parent.har.log.entries.indexOf($scope.entry)) == -1
$scope.alert "can't find position to add request"
return
current_pos += pos
$scope.$parent.har.log.entries.splice(current_pos, 0, entry)
$rootScope.$broadcast('har-change')
angular.element('#edit-entry').modal('hide')
$scope.add_request = (pos) ->
$scope.insert_request(pos, {
checked: false
pageref: $scope.entry.pageref
recommend: true
request:
method: 'GET'
url: ''
postData:
test: ''
headers: []
cookies: []
response: {}
})
$scope.add_delay_request = ()->
$scope.insert_request(1, {
checked: true
pageref: $scope.entry.pageref
recommend: true,
comment: '延时3秒'
request:
method: 'GET'
url: location.origin + '/util/delay/3'
postData:
test: ''
headers: []
cookies: []
response: {}
success_asserts: [
{re: "200", from: "status"}
]
})
$scope.copy_request = ()->
if not $scope.entry
$scope.alert "can't find position to paste request"
return
$scope.copy_entry = angular.copy($scope.entry)
utils.storage.set('copy_request', angular.toJson($scope.copy_entry))
$scope.paste_request = (pos)->
$scope.copy_entry.comment ?= '';
$scope.copy_entry.comment = 'Copy_' + $scope.copy_entry.comment
$scope.copy_entry.pageref = $scope.entry.pageref
$scope.insert_request(pos, $scope.copy_entry)
# fetch test
$scope.do_test = () ->
angular.element('.do-test').button('loading')
$http.post('/har/test', {
request:
method: $scope.entry.request.method
url: $scope.entry.request.url
headers: ({name: h.name, value: h.value} for h in $scope.entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in $scope.entry.request.cookies when c.checked)
data: $scope.entry.request.postData?.text
mimeType: $scope.entry.request.postData?.mimeType
rule:
success_asserts: $scope.entry.success_asserts
failed_asserts: $scope.entry.failed_asserts
extract_variables: $scope.entry.extract_variables
env:
variables: utils.list2dict($scope.env)
session: $scope.session
}).
success((data, status, headers, config) ->
angular.element('.do-test').button('reset')
if (status != 200)
$scope.alert(data)
return
$scope.preview = data.har
$scope.preview.success = data.success
$scope.env = utils.dict2list(data.env.variables)
$scope.session = data.env.session
$scope.panel = 'preview'
if data.har.response?.content?.text?
setTimeout((() ->
angular.element('.panel-preview iframe').attr("src",
"data:#{data.har.response.content.mimeType};\
base64,#{data.har.response.content.text}")), 0)
).
error((data, status, headers, config) ->
angular.element('.do-test').button('reset')
console.error('error', data, status, headers, config)
$scope.alert(data)
)
$scope.preview_match = (re, from) ->
data = null
if not from
return null
else if from == 'content'
content = $scope.preview.response?.content
if not content? or not content.text?
return null
if not content.decoded
content.decoded = atob(content.text)
data = content.decoded
else if from == 'status'
data = '' + $scope.preview.response.status
else if from.indexOf('header-') == 0
from = from[7..]
for header in $scope.preview.response.headers
if header.name.toLowerCase() == from
data = header.value
else if from == 'header'
data = (h.name + ': ' + h.value for h in $scope.preview.response.headers).join("\n")
if not data
return null
try
if match = re.match(/^\/(.*?)\/([gim]*)$/)
re = new RegExp(match[1], match[2])
else
re = new RegExp(re)
catch error
console.error(error)
return null
if re.global
result = []
while m = re.exec(data)
result.push(if m[1] then m[1] else m[0])
return result
else
if m = data.match(re)
return if m[1] then m[1] else m[0]
return null
## eof
)
| 12657 | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<<EMAIL>>
# http://binux.me
# Created on 2014-08-06 21:16:15
define (require, exports, module) ->
require '/static/har/contenteditable'
require '/static/har/editablelist'
utils = require '/static/utils'
angular.module('entry_editor', [
'contenteditable'
]).controller('EntryCtrl', ($scope, $rootScope, $sce, $http) ->
# init
$scope.panel = 'request'
$scope.copy_entry = null
# on edit event
$scope.$on('edit-entry', (ev, entry) ->
console.info(entry)
$scope.entry = entry
$scope.entry.success_asserts ?= [{re: '' + $scope.entry.response.status, from: 'status'},]
$scope.entry.failed_asserts ?= []
$scope.entry.extract_variables ?= []
$scope.copy_entry = JSON.parse(utils.storage.get('copy_request'))
angular.element('#edit-entry').modal('show')
$scope.alert_hide()
)
# on saved event
angular.element('#edit-entry').on('hidden.bs.modal', (ev) ->
if $scope.panel in ['preview-headers', 'preview']
$scope.$apply ->
$scope.panel = 'test'
# update env from extract_variables
env = utils.list2dict($scope.env)
for rule in $scope.entry.extract_variables
if ret = $scope.preview_match(rule.re, rule.from)
env[rule.name] = ret
$scope.env = utils.dict2list(env)
$scope.$apply ->
$scope.preview = undefined
console.debug('har-change')
$rootScope.$broadcast('har-change')
)
# alert message for test panel
$scope.alert = (message) ->
angular.element('.panel-test .alert').text(message).show()
$scope.alert_hide = () ->
angular.element('.panel-test .alert').hide()
# sync url with query string
changing = ''
$scope.$watch('entry.request.url', () ->
if changing and changing != 'url'
changing = ''
return
if not $scope.entry?
return
try
queryString = utils.dict2list(utils.querystring_parse_with_variables(utils.url_parse($scope.entry.request.url).query))
catch error
queryString = []
if not changing and not angular.equals(queryString, $scope.entry.request.queryString)
$scope.entry.request.queryString = queryString
changing = 'url'
)
# sync query string with url
$scope.$watch('entry.request.queryString', (() ->
if changing and changing != 'qs'
changing = ''
return
if not $scope.entry?
return
url = utils.url_parse($scope.entry.request.url)
query = utils.list2dict($scope.entry.request.queryString)
query = utils.querystring_unparse_with_variables(query)
url.search = "?#{query}" if query
url = utils.url_unparse(url)
if not changing and url != $scope.entry.request.url
$scope.entry.request.url = url
changing = 'qs'
), true)
# sync params with text
$scope.$watch('entry.request.postData.params', (() ->
if not $scope.entry?.request?.postData?
return
obj = utils.list2dict($scope.entry.request.postData.params)
$scope.entry.request.postData.text = utils.querystring_unparse_with_variables(obj)
), true)
# helper for delete item from array
$scope.delete = (hashKey, array) ->
for each, index in array
if each.$$hashKey == hashKey
array.splice(index, 1)
return
# variables template
$scope.variables_wrapper = (string, place_holder = '') ->
string = (string or place_holder).toString()
re = /{{\s*([\w]+)[^}]*?\s*}}/g
$sce.trustAsHtml(string.replace(re, '<span class="label label-primary">$&</span>'))
$scope.insert_request = (pos, entry)->
pos ?= 1
if (current_pos = $scope.$parent.har.log.entries.indexOf($scope.entry)) == -1
$scope.alert "can't find position to add request"
return
current_pos += pos
$scope.$parent.har.log.entries.splice(current_pos, 0, entry)
$rootScope.$broadcast('har-change')
angular.element('#edit-entry').modal('hide')
$scope.add_request = (pos) ->
$scope.insert_request(pos, {
checked: false
pageref: $scope.entry.pageref
recommend: true
request:
method: 'GET'
url: ''
postData:
test: ''
headers: []
cookies: []
response: {}
})
$scope.add_delay_request = ()->
$scope.insert_request(1, {
checked: true
pageref: $scope.entry.pageref
recommend: true,
comment: '延时3秒'
request:
method: 'GET'
url: location.origin + '/util/delay/3'
postData:
test: ''
headers: []
cookies: []
response: {}
success_asserts: [
{re: "200", from: "status"}
]
})
$scope.copy_request = ()->
if not $scope.entry
$scope.alert "can't find position to paste request"
return
$scope.copy_entry = angular.copy($scope.entry)
utils.storage.set('copy_request', angular.toJson($scope.copy_entry))
$scope.paste_request = (pos)->
$scope.copy_entry.comment ?= '';
$scope.copy_entry.comment = 'Copy_' + $scope.copy_entry.comment
$scope.copy_entry.pageref = $scope.entry.pageref
$scope.insert_request(pos, $scope.copy_entry)
# fetch test
$scope.do_test = () ->
angular.element('.do-test').button('loading')
$http.post('/har/test', {
request:
method: $scope.entry.request.method
url: $scope.entry.request.url
headers: ({name: h.name, value: h.value} for h in $scope.entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in $scope.entry.request.cookies when c.checked)
data: $scope.entry.request.postData?.text
mimeType: $scope.entry.request.postData?.mimeType
rule:
success_asserts: $scope.entry.success_asserts
failed_asserts: $scope.entry.failed_asserts
extract_variables: $scope.entry.extract_variables
env:
variables: utils.list2dict($scope.env)
session: $scope.session
}).
success((data, status, headers, config) ->
angular.element('.do-test').button('reset')
if (status != 200)
$scope.alert(data)
return
$scope.preview = data.har
$scope.preview.success = data.success
$scope.env = utils.dict2list(data.env.variables)
$scope.session = data.env.session
$scope.panel = 'preview'
if data.har.response?.content?.text?
setTimeout((() ->
angular.element('.panel-preview iframe').attr("src",
"data:#{data.har.response.content.mimeType};\
base64,#{data.har.response.content.text}")), 0)
).
error((data, status, headers, config) ->
angular.element('.do-test').button('reset')
console.error('error', data, status, headers, config)
$scope.alert(data)
)
$scope.preview_match = (re, from) ->
data = null
if not from
return null
else if from == 'content'
content = $scope.preview.response?.content
if not content? or not content.text?
return null
if not content.decoded
content.decoded = atob(content.text)
data = content.decoded
else if from == 'status'
data = '' + $scope.preview.response.status
else if from.indexOf('header-') == 0
from = from[7..]
for header in $scope.preview.response.headers
if header.name.toLowerCase() == from
data = header.value
else if from == 'header'
data = (h.name + ': ' + h.value for h in $scope.preview.response.headers).join("\n")
if not data
return null
try
if match = re.match(/^\/(.*?)\/([gim]*)$/)
re = new RegExp(match[1], match[2])
else
re = new RegExp(re)
catch error
console.error(error)
return null
if re.global
result = []
while m = re.exec(data)
result.push(if m[1] then m[1] else m[0])
return result
else
if m = data.match(re)
return if m[1] then m[1] else m[0]
return null
## eof
)
| true | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<PI:EMAIL:<EMAIL>END_PI>
# http://binux.me
# Created on 2014-08-06 21:16:15
define (require, exports, module) ->
require '/static/har/contenteditable'
require '/static/har/editablelist'
utils = require '/static/utils'
angular.module('entry_editor', [
'contenteditable'
]).controller('EntryCtrl', ($scope, $rootScope, $sce, $http) ->
# init
$scope.panel = 'request'
$scope.copy_entry = null
# on edit event
$scope.$on('edit-entry', (ev, entry) ->
console.info(entry)
$scope.entry = entry
$scope.entry.success_asserts ?= [{re: '' + $scope.entry.response.status, from: 'status'},]
$scope.entry.failed_asserts ?= []
$scope.entry.extract_variables ?= []
$scope.copy_entry = JSON.parse(utils.storage.get('copy_request'))
angular.element('#edit-entry').modal('show')
$scope.alert_hide()
)
# on saved event
angular.element('#edit-entry').on('hidden.bs.modal', (ev) ->
if $scope.panel in ['preview-headers', 'preview']
$scope.$apply ->
$scope.panel = 'test'
# update env from extract_variables
env = utils.list2dict($scope.env)
for rule in $scope.entry.extract_variables
if ret = $scope.preview_match(rule.re, rule.from)
env[rule.name] = ret
$scope.env = utils.dict2list(env)
$scope.$apply ->
$scope.preview = undefined
console.debug('har-change')
$rootScope.$broadcast('har-change')
)
# alert message for test panel
$scope.alert = (message) ->
angular.element('.panel-test .alert').text(message).show()
$scope.alert_hide = () ->
angular.element('.panel-test .alert').hide()
# sync url with query string
changing = ''
$scope.$watch('entry.request.url', () ->
if changing and changing != 'url'
changing = ''
return
if not $scope.entry?
return
try
queryString = utils.dict2list(utils.querystring_parse_with_variables(utils.url_parse($scope.entry.request.url).query))
catch error
queryString = []
if not changing and not angular.equals(queryString, $scope.entry.request.queryString)
$scope.entry.request.queryString = queryString
changing = 'url'
)
# sync query string with url
$scope.$watch('entry.request.queryString', (() ->
if changing and changing != 'qs'
changing = ''
return
if not $scope.entry?
return
url = utils.url_parse($scope.entry.request.url)
query = utils.list2dict($scope.entry.request.queryString)
query = utils.querystring_unparse_with_variables(query)
url.search = "?#{query}" if query
url = utils.url_unparse(url)
if not changing and url != $scope.entry.request.url
$scope.entry.request.url = url
changing = 'qs'
), true)
# sync params with text
$scope.$watch('entry.request.postData.params', (() ->
if not $scope.entry?.request?.postData?
return
obj = utils.list2dict($scope.entry.request.postData.params)
$scope.entry.request.postData.text = utils.querystring_unparse_with_variables(obj)
), true)
# helper for delete item from array
$scope.delete = (hashKey, array) ->
for each, index in array
if each.$$hashKey == hashKey
array.splice(index, 1)
return
# variables template
$scope.variables_wrapper = (string, place_holder = '') ->
string = (string or place_holder).toString()
re = /{{\s*([\w]+)[^}]*?\s*}}/g
$sce.trustAsHtml(string.replace(re, '<span class="label label-primary">$&</span>'))
$scope.insert_request = (pos, entry)->
pos ?= 1
if (current_pos = $scope.$parent.har.log.entries.indexOf($scope.entry)) == -1
$scope.alert "can't find position to add request"
return
current_pos += pos
$scope.$parent.har.log.entries.splice(current_pos, 0, entry)
$rootScope.$broadcast('har-change')
angular.element('#edit-entry').modal('hide')
$scope.add_request = (pos) ->
$scope.insert_request(pos, {
checked: false
pageref: $scope.entry.pageref
recommend: true
request:
method: 'GET'
url: ''
postData:
test: ''
headers: []
cookies: []
response: {}
})
$scope.add_delay_request = ()->
$scope.insert_request(1, {
checked: true
pageref: $scope.entry.pageref
recommend: true,
comment: '延时3秒'
request:
method: 'GET'
url: location.origin + '/util/delay/3'
postData:
test: ''
headers: []
cookies: []
response: {}
success_asserts: [
{re: "200", from: "status"}
]
})
$scope.copy_request = ()->
if not $scope.entry
$scope.alert "can't find position to paste request"
return
$scope.copy_entry = angular.copy($scope.entry)
utils.storage.set('copy_request', angular.toJson($scope.copy_entry))
$scope.paste_request = (pos)->
$scope.copy_entry.comment ?= '';
$scope.copy_entry.comment = 'Copy_' + $scope.copy_entry.comment
$scope.copy_entry.pageref = $scope.entry.pageref
$scope.insert_request(pos, $scope.copy_entry)
# fetch test
$scope.do_test = () ->
angular.element('.do-test').button('loading')
$http.post('/har/test', {
request:
method: $scope.entry.request.method
url: $scope.entry.request.url
headers: ({name: h.name, value: h.value} for h in $scope.entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in $scope.entry.request.cookies when c.checked)
data: $scope.entry.request.postData?.text
mimeType: $scope.entry.request.postData?.mimeType
rule:
success_asserts: $scope.entry.success_asserts
failed_asserts: $scope.entry.failed_asserts
extract_variables: $scope.entry.extract_variables
env:
variables: utils.list2dict($scope.env)
session: $scope.session
}).
success((data, status, headers, config) ->
angular.element('.do-test').button('reset')
if (status != 200)
$scope.alert(data)
return
$scope.preview = data.har
$scope.preview.success = data.success
$scope.env = utils.dict2list(data.env.variables)
$scope.session = data.env.session
$scope.panel = 'preview'
if data.har.response?.content?.text?
setTimeout((() ->
angular.element('.panel-preview iframe').attr("src",
"data:#{data.har.response.content.mimeType};\
base64,#{data.har.response.content.text}")), 0)
).
error((data, status, headers, config) ->
angular.element('.do-test').button('reset')
console.error('error', data, status, headers, config)
$scope.alert(data)
)
$scope.preview_match = (re, from) ->
data = null
if not from
return null
else if from == 'content'
content = $scope.preview.response?.content
if not content? or not content.text?
return null
if not content.decoded
content.decoded = atob(content.text)
data = content.decoded
else if from == 'status'
data = '' + $scope.preview.response.status
else if from.indexOf('header-') == 0
from = from[7..]
for header in $scope.preview.response.headers
if header.name.toLowerCase() == from
data = header.value
else if from == 'header'
data = (h.name + ': ' + h.value for h in $scope.preview.response.headers).join("\n")
if not data
return null
try
if match = re.match(/^\/(.*?)\/([gim]*)$/)
re = new RegExp(match[1], match[2])
else
re = new RegExp(re)
catch error
console.error(error)
return null
if re.global
result = []
while m = re.exec(data)
result.push(if m[1] then m[1] else m[0])
return result
else
if m = data.match(re)
return if m[1] then m[1] else m[0]
return null
## eof
)
|
[
{
"context": " if Mapbox.loaded()\n L.mapbox.accessToken = 'pk.eyJ1Ijoic2FtY29yY29zIiwiYSI6IndLY0ZELUkifQ.HaLwwzHXtbi6XX8WBIVNwQ'\n map = L.mapbox.map('map', 'samcorcos.lgbb5",
"end": 163,
"score": 0.9997215270996094,
"start": 95,
"tag": "KEY",
"value": "pk.eyJ1Ijoic2FtY29yY29zIiwi... | client/views/home/home.coffee | samcorcos/SnapMap | 0 | Template.home.rendered = ->
@autorun ->
if Mapbox.loaded()
L.mapbox.accessToken = 'pk.eyJ1Ijoic2FtY29yY29zIiwiYSI6IndLY0ZELUkifQ.HaLwwzHXtbi6XX8WBIVNwQ'
map = L.mapbox.map('map', 'samcorcos.lgbb5nbd')
| 216525 | Template.home.rendered = ->
@autorun ->
if Mapbox.loaded()
L.mapbox.accessToken = '<KEY>'
map = L.mapbox.map('map', 'samcorcos.lgbb5nbd')
| true | Template.home.rendered = ->
@autorun ->
if Mapbox.loaded()
L.mapbox.accessToken = 'PI:KEY:<KEY>END_PI'
map = L.mapbox.map('map', 'samcorcos.lgbb5nbd')
|
[
{
"context": "\ndescribe 'Wongo CRUD All', ->\n\n docs = [{name: 'Meow'}, {name: 'Boo'}, {name: 'Fran'}]\n\n it 'should b",
"end": 190,
"score": 0.9997233152389526,
"start": 186,
"tag": "NAME",
"value": "Meow"
},
{
"context": " CRUD All', ->\n\n docs = [{name: 'Meow'}, {name: 'Boo... | test/crudall.test.coffee | wookets/wongo | 0 | _ = require 'underscore'
assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockAll',
fields:
name: String
describe 'Wongo CRUD All', ->
docs = [{name: 'Meow'}, {name: 'Boo'}, {name: 'Fran'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents', (done) ->
wongo.remove 'MockAll', docs, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents by id', (done) ->
_ids = _.pluck(docs, '_id')
wongo.remove 'MockAll', _ids, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
| 185247 | _ = require 'underscore'
assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockAll',
fields:
name: String
describe 'Wongo CRUD All', ->
docs = [{name: '<NAME>'}, {name: '<NAME>'}, {name: '<NAME>'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents', (done) ->
wongo.remove 'MockAll', docs, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents by id', (done) ->
_ids = _.pluck(docs, '_id')
wongo.remove 'MockAll', _ids, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
| true | _ = require 'underscore'
assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockAll',
fields:
name: String
describe 'Wongo CRUD All', ->
docs = [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents', (done) ->
wongo.remove 'MockAll', docs, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
it 'should be able to save all documents', (done) ->
wongo.save 'MockAll', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to remove all documents by id', (done) ->
_ids = _.pluck(docs, '_id')
wongo.remove 'MockAll', _ids, (err, result) ->
assert.ifError(err)
done()
it 'should be verify all this worked with a find', (done) ->
_ids = _.pluck(docs, '_id')
query = {_id: {$in: _ids}}
wongo.find 'MockAll', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 0)
done()
|
[
{
"context": "'use strict'\n#\n# Ethan Mick\n# 2015\n#\n\nmodule.exports = [\n method: 'GET'\n pa",
"end": 27,
"score": 0.9996577501296997,
"start": 17,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/routes/status.coffee | ethanmick/metrics | 0 | 'use strict'
#
# Ethan Mick
# 2015
#
module.exports = [
method: 'GET'
path: '/status'
handler: (req, reply)->
reply(status: 'up')
]
| 21858 | 'use strict'
#
# <NAME>
# 2015
#
module.exports = [
method: 'GET'
path: '/status'
handler: (req, reply)->
reply(status: 'up')
]
| true | 'use strict'
#
# PI:NAME:<NAME>END_PI
# 2015
#
module.exports = [
method: 'GET'
path: '/status'
handler: (req, reply)->
reply(status: 'up')
]
|
[
{
"context": "###\n Underscore.outcasts\n (c) 2012-2013 Dmitry Karpunin <koderfunk aet gmail dot com>\n Underscore.outcas",
"end": 57,
"score": 0.9998490214347839,
"start": 42,
"tag": "NAME",
"value": "Dmitry Karpunin"
},
{
"context": " MIT license.\n Documentation: https://githu... | app/assets/javascripts/ultimate/underscore/underscore.outcasts.js.coffee | KODerFunk/ultimate-base | 1 | ###
Underscore.outcasts
(c) 2012-2013 Dmitry Karpunin <koderfunk aet gmail dot com>
Underscore.outcasts is freely distributable under the terms of the MIT license.
Documentation: https://github.com/KODerFunk/underscore.outcasts
Some code is borrowed from outcasts pull requests to Underscore.
Version '0.1.6'
###
'use strict'
# Defining underscore.outcasts
UnderscoreOutcasts =
VERSION: '0.1.6'
delete: (object, key) ->
value = object[key]
delete object[key]
value
blockGiven: (args) ->
block = _.last(args)
if _.isFunction(block) then block else null
sortHash: (hash, byValue = false) ->
_.sortBy(_.map(hash, (value, key) -> [key, value]), (pair) -> pair[if byValue then 1 else 0])
regexpValidKey: /^[\w\-]+$/
invert: (object) ->
result = {}
for key, value of object
if _.isArray(value)
for newKey in value when UnderscoreOutcasts.regexpValidKey.test(newKey)
result[newKey] = key
else if UnderscoreOutcasts.regexpValidKey.test(value)
if _.has(result, value)
if _.isArray(result[value])
result[value].push key
else
result[value] = [result[value], key]
else
result[value] = key
result
scan: (str, pattern) ->
block = @blockGiven(arguments)
result = []
while str.length
matches = str.match(pattern)
if matches
cut = matches.shift()
str = str.slice(matches.index + cut.length)
result.push if block
if matches.length then block(matches...) else block(cut)
else
if matches.length then matches else cut
else
str = ''
result
arrayWrap: (object) ->
unless object?
[]
else if _.isArray(object)
object
else if _.isFunction(object.toArray)
object.toArray() or [object]
else
[object]
# http://coderwall.com/p/krcdig
deepBindAll: (obj) ->
target = _.last(arguments)
for key, value of obj
if _.isFunction(value)
obj[key] = _.bind(value, target)
else if _.isObject(value)
obj[key] = _.deepBindAll(value, target)
obj
###
Split array into slices of <number> elements.
Map result by iterator if last given.
>>> eachSlice [1..10], 3, (a) -> cout a
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
###
eachSlice: (array, number) ->
size = array.length
index = 0
slices = []
while index < size
nextIndex = index + number
slices.push array.slice(index, nextIndex)
index = nextIndex
if block = @blockGiven(arguments) then _.map(slices, block) else slices
###
Splits or iterates over the array in groups of size +number+,
padding any remaining slots with +fill_with+ unless it is +false+.
>>> inGroupsOf [1..7], 3, (group) -> cout group
[1, 2, 3]
[4, 5, 6]
[7, null, null]
>>> inGroupsOf [1..3], 2, ' ', (group) -> cout group
[1, 2]
[3, " "]
>>> inGroupsOf [1..3], 2, false, (group) -> cout group
[1, 2]
[3]
###
inGroupsOf: (array, number, fillWith = null) ->
return array if number < 1
unless fillWith is false
# size % number gives how many extra we have;
# subtracting from number gives how many to add;
# modulo number ensures we don't add group of just fill.
padding = (number - array.length % number) % number
if padding
fillWith = null if _.isFunction(fillWith)
array = array.slice()
array.push(fillWith) while padding-- > 0
@eachSlice array, number, @blockGiven(arguments)
###
Splits or iterates over the array in +number+ of groups, padding any
remaining slots with +fill_with+ unless it is +false+.
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", " "]
["8", "9", "10", " "]
%w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
["1", "2", "3"]
["4", "5"]
["6", "7"]
###
# TODO tests
inGroups: (array, number, fillWith = null) ->
# size / number gives minor group size;
# size % number gives how many objects need extra accommodation;
# each group hold either division or division + 1 items.
division = Math.floor(array.length / number)
modulo = array.length % number
# create a new array avoiding dup
groups = []
start = 0
for index in [0...number]
length = division + (if modulo > 0 and modulo > index then 1 else 0)
groups.push last_group = array.slice(start, start + length)
if fillWith isnt false and modulo > 0 and length is division
last_group.push fillWith
start += length
if block = @blockGiven(arguments)
_.map groups, block
else
groups
###
Create a (deep-cloned) duplicate of an object.
###
# TODO tests
deepClone: (obj) ->
return obj unless _.isObject(obj)
if _.isArray(obj)
@deepClone(element) for element in obj
else
newObj = {}
if obj
for prop, value of obj when not _.isFunction(value)
newObj[prop] = @deepClone(value)
newObj
exports: ->
result = {}
for prop of @
continue if not @hasOwnProperty(prop) or prop.match(/^(?:include|contains|reverse)$/)
result[prop] = @[prop]
result
# CommonJS module is defined
if exports?
if module?.exports
# Export module
module.exports = UnderscoreOutcasts
exports.UnderscoreOutcasts = UnderscoreOutcasts
else if define?.amd
# Register as a named module with AMD.
define 'underscore.outcasts', [], -> UnderscoreOutcasts
else
# Integrate with Underscore.js if defined
# or create our own underscore object.
@_ ||= {}
@_.outcasts = @_.out = UnderscoreOutcasts
| 153650 | ###
Underscore.outcasts
(c) 2012-2013 <NAME> <koderfunk aet gmail dot com>
Underscore.outcasts is freely distributable under the terms of the MIT license.
Documentation: https://github.com/KODerFunk/underscore.outcasts
Some code is borrowed from outcasts pull requests to Underscore.
Version '0.1.6'
###
'use strict'
# Defining underscore.outcasts
UnderscoreOutcasts =
VERSION: '0.1.6'
delete: (object, key) ->
value = object[key]
delete object[key]
value
blockGiven: (args) ->
block = _.last(args)
if _.isFunction(block) then block else null
sortHash: (hash, byValue = false) ->
_.sortBy(_.map(hash, (value, key) -> [key, value]), (pair) -> pair[if byValue then 1 else 0])
regexpValidKey: /^[\w\-]+$/
invert: (object) ->
result = {}
for key, value of object
if _.isArray(value)
for newKey in value when UnderscoreOutcasts.regexpValidKey.test(newKey)
result[newKey] = key
else if UnderscoreOutcasts.regexpValidKey.test(value)
if _.has(result, value)
if _.isArray(result[value])
result[value].push key
else
result[value] = [result[value], key]
else
result[value] = key
result
scan: (str, pattern) ->
block = @blockGiven(arguments)
result = []
while str.length
matches = str.match(pattern)
if matches
cut = matches.shift()
str = str.slice(matches.index + cut.length)
result.push if block
if matches.length then block(matches...) else block(cut)
else
if matches.length then matches else cut
else
str = ''
result
arrayWrap: (object) ->
unless object?
[]
else if _.isArray(object)
object
else if _.isFunction(object.toArray)
object.toArray() or [object]
else
[object]
# http://coderwall.com/p/krcdig
deepBindAll: (obj) ->
target = _.last(arguments)
for key, value of obj
if _.isFunction(value)
obj[key] = _.bind(value, target)
else if _.isObject(value)
obj[key] = _.deepBindAll(value, target)
obj
###
Split array into slices of <number> elements.
Map result by iterator if last given.
>>> eachSlice [1..10], 3, (a) -> cout a
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
###
eachSlice: (array, number) ->
size = array.length
index = 0
slices = []
while index < size
nextIndex = index + number
slices.push array.slice(index, nextIndex)
index = nextIndex
if block = @blockGiven(arguments) then _.map(slices, block) else slices
###
Splits or iterates over the array in groups of size +number+,
padding any remaining slots with +fill_with+ unless it is +false+.
>>> inGroupsOf [1..7], 3, (group) -> cout group
[1, 2, 3]
[4, 5, 6]
[7, null, null]
>>> inGroupsOf [1..3], 2, ' ', (group) -> cout group
[1, 2]
[3, " "]
>>> inGroupsOf [1..3], 2, false, (group) -> cout group
[1, 2]
[3]
###
inGroupsOf: (array, number, fillWith = null) ->
return array if number < 1
unless fillWith is false
# size % number gives how many extra we have;
# subtracting from number gives how many to add;
# modulo number ensures we don't add group of just fill.
padding = (number - array.length % number) % number
if padding
fillWith = null if _.isFunction(fillWith)
array = array.slice()
array.push(fillWith) while padding-- > 0
@eachSlice array, number, @blockGiven(arguments)
###
Splits or iterates over the array in +number+ of groups, padding any
remaining slots with +fill_with+ unless it is +false+.
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", " "]
["8", "9", "10", " "]
%w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
["1", "2", "3"]
["4", "5"]
["6", "7"]
###
# TODO tests
inGroups: (array, number, fillWith = null) ->
# size / number gives minor group size;
# size % number gives how many objects need extra accommodation;
# each group hold either division or division + 1 items.
division = Math.floor(array.length / number)
modulo = array.length % number
# create a new array avoiding dup
groups = []
start = 0
for index in [0...number]
length = division + (if modulo > 0 and modulo > index then 1 else 0)
groups.push last_group = array.slice(start, start + length)
if fillWith isnt false and modulo > 0 and length is division
last_group.push fillWith
start += length
if block = @blockGiven(arguments)
_.map groups, block
else
groups
###
Create a (deep-cloned) duplicate of an object.
###
# TODO tests
deepClone: (obj) ->
return obj unless _.isObject(obj)
if _.isArray(obj)
@deepClone(element) for element in obj
else
newObj = {}
if obj
for prop, value of obj when not _.isFunction(value)
newObj[prop] = @deepClone(value)
newObj
exports: ->
result = {}
for prop of @
continue if not @hasOwnProperty(prop) or prop.match(/^(?:include|contains|reverse)$/)
result[prop] = @[prop]
result
# CommonJS module is defined
if exports?
if module?.exports
# Export module
module.exports = UnderscoreOutcasts
exports.UnderscoreOutcasts = UnderscoreOutcasts
else if define?.amd
# Register as a named module with AMD.
define 'underscore.outcasts', [], -> UnderscoreOutcasts
else
# Integrate with Underscore.js if defined
# or create our own underscore object.
@_ ||= {}
@_.outcasts = @_.out = UnderscoreOutcasts
| true | ###
Underscore.outcasts
(c) 2012-2013 PI:NAME:<NAME>END_PI <koderfunk aet gmail dot com>
Underscore.outcasts is freely distributable under the terms of the MIT license.
Documentation: https://github.com/KODerFunk/underscore.outcasts
Some code is borrowed from outcasts pull requests to Underscore.
Version '0.1.6'
###
'use strict'
# Defining underscore.outcasts
UnderscoreOutcasts =
VERSION: '0.1.6'
delete: (object, key) ->
value = object[key]
delete object[key]
value
blockGiven: (args) ->
block = _.last(args)
if _.isFunction(block) then block else null
sortHash: (hash, byValue = false) ->
_.sortBy(_.map(hash, (value, key) -> [key, value]), (pair) -> pair[if byValue then 1 else 0])
regexpValidKey: /^[\w\-]+$/
invert: (object) ->
result = {}
for key, value of object
if _.isArray(value)
for newKey in value when UnderscoreOutcasts.regexpValidKey.test(newKey)
result[newKey] = key
else if UnderscoreOutcasts.regexpValidKey.test(value)
if _.has(result, value)
if _.isArray(result[value])
result[value].push key
else
result[value] = [result[value], key]
else
result[value] = key
result
scan: (str, pattern) ->
block = @blockGiven(arguments)
result = []
while str.length
matches = str.match(pattern)
if matches
cut = matches.shift()
str = str.slice(matches.index + cut.length)
result.push if block
if matches.length then block(matches...) else block(cut)
else
if matches.length then matches else cut
else
str = ''
result
arrayWrap: (object) ->
unless object?
[]
else if _.isArray(object)
object
else if _.isFunction(object.toArray)
object.toArray() or [object]
else
[object]
# http://coderwall.com/p/krcdig
deepBindAll: (obj) ->
target = _.last(arguments)
for key, value of obj
if _.isFunction(value)
obj[key] = _.bind(value, target)
else if _.isObject(value)
obj[key] = _.deepBindAll(value, target)
obj
###
Split array into slices of <number> elements.
Map result by iterator if last given.
>>> eachSlice [1..10], 3, (a) -> cout a
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
###
eachSlice: (array, number) ->
size = array.length
index = 0
slices = []
while index < size
nextIndex = index + number
slices.push array.slice(index, nextIndex)
index = nextIndex
if block = @blockGiven(arguments) then _.map(slices, block) else slices
###
Splits or iterates over the array in groups of size +number+,
padding any remaining slots with +fill_with+ unless it is +false+.
>>> inGroupsOf [1..7], 3, (group) -> cout group
[1, 2, 3]
[4, 5, 6]
[7, null, null]
>>> inGroupsOf [1..3], 2, ' ', (group) -> cout group
[1, 2]
[3, " "]
>>> inGroupsOf [1..3], 2, false, (group) -> cout group
[1, 2]
[3]
###
inGroupsOf: (array, number, fillWith = null) ->
return array if number < 1
unless fillWith is false
# size % number gives how many extra we have;
# subtracting from number gives how many to add;
# modulo number ensures we don't add group of just fill.
padding = (number - array.length % number) % number
if padding
fillWith = null if _.isFunction(fillWith)
array = array.slice()
array.push(fillWith) while padding-- > 0
@eachSlice array, number, @blockGiven(arguments)
###
Splits or iterates over the array in +number+ of groups, padding any
remaining slots with +fill_with+ unless it is +false+.
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", " "]
["8", "9", "10", " "]
%w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
["1", "2", "3"]
["4", "5"]
["6", "7"]
###
# TODO tests
inGroups: (array, number, fillWith = null) ->
# size / number gives minor group size;
# size % number gives how many objects need extra accommodation;
# each group hold either division or division + 1 items.
division = Math.floor(array.length / number)
modulo = array.length % number
# create a new array avoiding dup
groups = []
start = 0
for index in [0...number]
length = division + (if modulo > 0 and modulo > index then 1 else 0)
groups.push last_group = array.slice(start, start + length)
if fillWith isnt false and modulo > 0 and length is division
last_group.push fillWith
start += length
if block = @blockGiven(arguments)
_.map groups, block
else
groups
###
Create a (deep-cloned) duplicate of an object.
###
# TODO tests
deepClone: (obj) ->
return obj unless _.isObject(obj)
if _.isArray(obj)
@deepClone(element) for element in obj
else
newObj = {}
if obj
for prop, value of obj when not _.isFunction(value)
newObj[prop] = @deepClone(value)
newObj
exports: ->
result = {}
for prop of @
continue if not @hasOwnProperty(prop) or prop.match(/^(?:include|contains|reverse)$/)
result[prop] = @[prop]
result
# CommonJS module is defined
if exports?
if module?.exports
# Export module
module.exports = UnderscoreOutcasts
exports.UnderscoreOutcasts = UnderscoreOutcasts
else if define?.amd
# Register as a named module with AMD.
define 'underscore.outcasts', [], -> UnderscoreOutcasts
else
# Integrate with Underscore.js if defined
# or create our own underscore object.
@_ ||= {}
@_.outcasts = @_.out = UnderscoreOutcasts
|
[
{
"context": "# Contributors\ncontributors: [\n name: 'Season千'\n avatar: 'http://7xkd7e.com1.z0.glb.clouddn.c",
"end": 49,
"score": 0.9922714233398438,
"start": 42,
"tag": "USERNAME",
"value": "Season千"
},
{
"context": "w.pixiv.net/member.php?id=3991162'\n ,\n name: 'Magic... | constant.cson | wafer-li/poi | 0 | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: 'Magica'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: 'Yunze'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: 'Chiba'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: 'KochiyaOcean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: '马里酱'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: '吴钩霜雪明'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: 'Rui'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: 'Artoria'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
]
| 126228 | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: '<NAME>'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: '<NAME>'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: '<NAME>Ocean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: '<NAME>'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: '<NAME>'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: '<NAME>'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
]
| true | # Contributors
contributors: [
name: 'Season千'
avatar: 'http://7xkd7e.com1.z0.glb.clouddn.com/season.jpg'
link: 'http://www.pixiv.net/member.php?id=3991162'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars0.githubusercontent.com/u/6753092?v=3&s=460'
link: 'http://weibo.com/maginya'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/3362438?v=3&s=460'
link: 'http://weibo.com/myzwillmake'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars1.githubusercontent.com/u/6986642?v=3&s=460'
link: 'http://weibo.com/chibaheit'
,
name: 'PI:NAME:<NAME>END_PIOcean'
avatar: 'https://avatars3.githubusercontent.com/u/8194131?v=3&s=460'
link: 'http://www.kochiyaocean.org'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/10855724?v=3&s=460'
link: 'http://www.weibo.com/1791427467'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars2.githubusercontent.com/u/6861365?v=3&s=460'
link: 'http://www.weibo.com/jenningswu'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars3.githubusercontent.com/u/11897118?v=3&s=460'
link: 'https://github.com/ruiii'
,
name: 'PI:NAME:<NAME>END_PI'
avatar: 'https://avatars1.githubusercontent.com/u/1183568?v=3&s=460'
link: 'http://www.weibo.com/pheliox'
]
|
[
{
"context": "ions, schemas and models definitions.\n#\n# @author: Daniele Gazzelloni <daniele@danielegazzelloni.com>\n#################",
"end": 94,
"score": 0.9998762011528015,
"start": 76,
"tag": "NAME",
"value": "Daniele Gazzelloni"
},
{
"context": "els definitions.\n#\n# @author... | backend/src/db.coffee | danielegazzelloni/barbershop-challenge | 0 | ##
# Mongoose CRUD operations, schemas and models definitions.
#
# @author: Daniele Gazzelloni <daniele@danielegazzelloni.com>
######################################################################
mongoose = require('mongoose')
config = require('./config')
# Our db connection
db = mongoose.connect(config.dbHostname)
db = mongoose.connection
# Customers schema and model objects
schemas = {}
models = {}
# Initialize Mongo schemas and models
exports.initData = (callback) ->
schemas.customers = new mongoose.Schema({
name: {type: String},
email: {type: String},
barber: {type: String}
});
# Init models
models.Customers = mongoose.model("Customers", schemas.customers);
# call the callback
callback()
# Module exports
exports.schemas = schemas
exports.models = models
exports.connection = db
| 136642 | ##
# Mongoose CRUD operations, schemas and models definitions.
#
# @author: <NAME> <<EMAIL>>
######################################################################
mongoose = require('mongoose')
config = require('./config')
# Our db connection
db = mongoose.connect(config.dbHostname)
db = mongoose.connection
# Customers schema and model objects
schemas = {}
models = {}
# Initialize Mongo schemas and models
exports.initData = (callback) ->
schemas.customers = new mongoose.Schema({
name: {type: String},
email: {type: String},
barber: {type: String}
});
# Init models
models.Customers = mongoose.model("Customers", schemas.customers);
# call the callback
callback()
# Module exports
exports.schemas = schemas
exports.models = models
exports.connection = db
| true | ##
# Mongoose CRUD operations, schemas and models definitions.
#
# @author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
######################################################################
mongoose = require('mongoose')
config = require('./config')
# Our db connection
db = mongoose.connect(config.dbHostname)
db = mongoose.connection
# Customers schema and model objects
schemas = {}
models = {}
# Initialize Mongo schemas and models
exports.initData = (callback) ->
schemas.customers = new mongoose.Schema({
name: {type: String},
email: {type: String},
barber: {type: String}
});
# Init models
models.Customers = mongoose.model("Customers", schemas.customers);
# call the callback
callback()
# Module exports
exports.schemas = schemas
exports.models = models
exports.connection = db
|
[
{
"context": " config = new AWS.Config(\n accessKeyId: 'akid',\n secretAccessKey: 'secret',\n sess",
"end": 597,
"score": 0.9840964078903198,
"start": 593,
"tag": "KEY",
"value": "akid"
},
{
"context": " accessKeyId: 'akid',\n secretAccessKey: 'secret'... | test/config.spec.coffee | rwaldron/aws-sdk-js | 0 | helpers = require('./helpers')
AWS = helpers.AWS
configure = (options) -> new AWS.Config(options)
describe 'AWS.Config', ->
describe 'constructor', ->
it 'should be able to pass in a Config object as parameter', ->
config = new AWS.Config(sslEnabled: false, maxRetries: 0)
copyConfig = new AWS.Config(config)
expect(copyConfig).not.to.equal(config)
expect(copyConfig.sslEnabled).to.equal(false)
expect(copyConfig.maxRetries).to.equal(0)
it 'should be able to pass credential values directly', ->
config = new AWS.Config(
accessKeyId: 'akid',
secretAccessKey: 'secret',
sessionToken: 'session')
expect(config.credentials.accessKeyId).to.equal('akid')
expect(config.credentials.secretAccessKey).to.equal('secret')
expect(config.credentials.sessionToken).to.equal('session')
describe 'region', ->
oldEnv = process.env
beforeEach ->
process.env = {}
afterEach ->
process.env = oldEnv
it 'defaults to undefined', ->
expect(configure().region).not.to.exist
if AWS.util.isNode()
it 'grabs AWS_REGION from the env', ->
process.env.AWS_REGION = 'us-west-2'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'also grabs AMAZON_REGION from the env', ->
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-1')
it 'prefers AWS_REGION to AMAZON_REGION', ->
process.env.AWS_REGION = 'us-west-2'
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'can be set to a string', ->
expect(configure(region: 'us-west-1').region).to.equal('us-west-1')
describe 'maxRetries', ->
it 'defaults to unefined', ->
expect(configure().maxRetries).to.equal(undefined)
it 'can be set to an integer', ->
expect(configure(maxRetries: 2).maxRetries).to.equal(2)
describe 'retryDelayOptions', ->
it 'defaults to "base: 100"', ->
expect(configure().retryDelayOptions).to.eql({base: 100})
it 'can set "base" to an integer', ->
expect(configure(retryDelayOptions: {base: 30}).retryDelayOptions).to.eql({base: 30})
describe 'paramValidation', ->
it 'defaults to true', ->
expect(configure().paramValidation).to.equal(true)
describe 'computeChecksums', ->
it 'defaults to true', ->
expect(configure().computeChecksums).to.equal(true)
describe 'sslEnabled', ->
it 'defaults to true', ->
expect(configure().sslEnabled).to.equal(true)
it 'can be set to false', ->
expect(configure(sslEnabled: false).sslEnabled).to.equal(false)
describe 'httpOptions', ->
it 'defaults to {timeout:120000}', ->
expect(configure().httpOptions).to.eql(timeout: 120000)
describe 'systemClockOffset', ->
it 'defaults to 0', ->
expect(configure().systemClockOffset).to.equal(0)
describe 'correctClockSkew', ->
it 'defaults to false', ->
expect(configure().correctClockSkew).to.equal(false)
describe 'customUserAgent', ->
it 'defaults to null', ->
expect(configure().customUserAgent).to.equal(null)
describe 'set', ->
it 'should set a default value for a key', ->
config = new AWS.Config()
config.set('maxRetries', undefined, 'DEFAULT')
expect(config.maxRetries).to.equal('DEFAULT')
it 'should execute default value if it is a function', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', undefined, mock)
expect(mock.calls.length).not.to.equal(0)
it 'should not expand default value function if value is present', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', 'VALUE', mock)
expect(mock.calls.length).to.equal(0)
describe 'clear', ->
it 'should be able to clear all key values from a config object', ->
config = new AWS.Config(credentials: {}, maxRetries: 300, sslEnabled: 'foo')
expect(config.maxRetries).to.equal(300)
expect(config.sslEnabled).to.equal('foo')
expect(config.credentials).not.to.equal(undefined)
config.clear()
expect(config.maxRetries).to.equal(undefined)
expect(config.sslEnabled).to.equal(undefined)
expect(config.credentials).not.to.equal(undefined)
expect(config.credentialProvider).not.to.equal(undefined)
describe 'update', ->
it 'should be able to update keyed values', ->
config = new AWS.Config()
expect(config.maxRetries).to.equal(undefined)
config.update(maxRetries: 10)
expect(config.maxRetries).to.equal(10)
it 'should ignore non-keyed values', ->
config = new AWS.Config()
config.update(foo: 10)
expect(config.foo).to.equal(undefined)
it 'should allow service identifiers to be set', ->
config = new AWS.Config()
config.update(s3: {endpoint: 'localhost'})
expect(config.s3).to.eql(endpoint: 'localhost')
it 'allows unknown keys if allowUnknownKeys is set', ->
config = new AWS.Config()
config.update(foo: 10, true)
expect(config.foo).to.equal(10)
it 'should be able to update literal credentials', ->
config = new AWS.Config()
config.update(
accessKeyId: 'akid',
secretAccessKey: 'secret',
sessionToken: 'session')
expect(config.credentials.accessKeyId).to.equal('akid')
expect(config.credentials.secretAccessKey).to.equal('secret')
expect(config.credentials.sessionToken).to.equal('session')
it 'should deep merge httpOptions', ->
config = new AWS.Config()
config.update httpOptions: timeout: 1
config.update httpOptions: { xhrSync: true }
expect(config.httpOptions.timeout).to.equal(1)
expect(config.httpOptions.xhrSync).to.equal(true)
describe 'getCredentials', ->
spy = null
config = null
beforeEach ->
spy = helpers.createSpy('getCredentials callback')
expectValid = (options, key) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0]).not.to.exist
if key
expect(config.credentials.accessKeyId).to.equal(key)
expectError = (options, message) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0].code).to.equal('CredentialsError')
expect(spy.calls[0].arguments[0].message).to.equal(message)
it 'should check credentials for static object first', ->
expectValid credentials: accessKeyId: '123', secretAccessKey: '456'
it 'should error if static credentials are not available', ->
expectError(credentials: {}, 'Missing credentials')
it 'should check credentials for async get() method', ->
expectValid credentials: get: (cb) -> cb()
it 'should error if credentials.get() cannot resolve', ->
options = credentials:
constructor: name: 'CustomCredentials'
get: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from CustomCredentials'
it 'should check credentialProvider if no credentials', ->
expectValid credentials: null, credentialProvider:
resolve: (cb) -> cb(null, accessKeyId: 'key', secretAccessKey: 'secret')
it 'should error if credentialProvider fails to resolve', ->
options = credentials: null, credentialProvider:
resolve: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from any providers'
it 'should error if no credentials or credentialProvider', ->
options = credentials: null, credentialProvider: null
expectError options, 'No credentials to load'
describe 'AWS.config', ->
it 'should be a default Config object', ->
expect(AWS.config.sslEnabled).to.equal(true)
expect(AWS.config.maxRetries).to.equal(undefined)
it 'can set default config to an object literal', ->
oldConfig = AWS.config
AWS.config = {}
expect(AWS.config).to.eql({})
AWS.config = oldConfig
describe 'setPromisesDependency', ->
it 'updates promise support on requests', ->
utilSpy = helpers.spyOn(AWS.util, 'addPromisesToRequests')
AWS.config.setPromisesDependency(->)
expect(utilSpy.calls.length).to.equal(1) | 202447 | helpers = require('./helpers')
AWS = helpers.AWS
configure = (options) -> new AWS.Config(options)
describe 'AWS.Config', ->
describe 'constructor', ->
it 'should be able to pass in a Config object as parameter', ->
config = new AWS.Config(sslEnabled: false, maxRetries: 0)
copyConfig = new AWS.Config(config)
expect(copyConfig).not.to.equal(config)
expect(copyConfig.sslEnabled).to.equal(false)
expect(copyConfig.maxRetries).to.equal(0)
it 'should be able to pass credential values directly', ->
config = new AWS.Config(
accessKeyId: '<KEY>',
secretAccessKey: '<KEY>',
sessionToken: '<PASSWORD>')
expect(config.credentials.accessKeyId).to.equal('ak<KEY>')
expect(config.credentials.secretAccessKey).to.equal('<KEY>')
expect(config.credentials.sessionToken).to.equal('session')
describe 'region', ->
oldEnv = process.env
beforeEach ->
process.env = {}
afterEach ->
process.env = oldEnv
it 'defaults to undefined', ->
expect(configure().region).not.to.exist
if AWS.util.isNode()
it 'grabs AWS_REGION from the env', ->
process.env.AWS_REGION = 'us-west-2'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'also grabs AMAZON_REGION from the env', ->
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-1')
it 'prefers AWS_REGION to AMAZON_REGION', ->
process.env.AWS_REGION = 'us-west-2'
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'can be set to a string', ->
expect(configure(region: 'us-west-1').region).to.equal('us-west-1')
describe 'maxRetries', ->
it 'defaults to unefined', ->
expect(configure().maxRetries).to.equal(undefined)
it 'can be set to an integer', ->
expect(configure(maxRetries: 2).maxRetries).to.equal(2)
describe 'retryDelayOptions', ->
it 'defaults to "base: 100"', ->
expect(configure().retryDelayOptions).to.eql({base: 100})
it 'can set "base" to an integer', ->
expect(configure(retryDelayOptions: {base: 30}).retryDelayOptions).to.eql({base: 30})
describe 'paramValidation', ->
it 'defaults to true', ->
expect(configure().paramValidation).to.equal(true)
describe 'computeChecksums', ->
it 'defaults to true', ->
expect(configure().computeChecksums).to.equal(true)
describe 'sslEnabled', ->
it 'defaults to true', ->
expect(configure().sslEnabled).to.equal(true)
it 'can be set to false', ->
expect(configure(sslEnabled: false).sslEnabled).to.equal(false)
describe 'httpOptions', ->
it 'defaults to {timeout:120000}', ->
expect(configure().httpOptions).to.eql(timeout: 120000)
describe 'systemClockOffset', ->
it 'defaults to 0', ->
expect(configure().systemClockOffset).to.equal(0)
describe 'correctClockSkew', ->
it 'defaults to false', ->
expect(configure().correctClockSkew).to.equal(false)
describe 'customUserAgent', ->
it 'defaults to null', ->
expect(configure().customUserAgent).to.equal(null)
describe 'set', ->
it 'should set a default value for a key', ->
config = new AWS.Config()
config.set('maxRetries', undefined, 'DEFAULT')
expect(config.maxRetries).to.equal('DEFAULT')
it 'should execute default value if it is a function', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', undefined, mock)
expect(mock.calls.length).not.to.equal(0)
it 'should not expand default value function if value is present', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', 'VALUE', mock)
expect(mock.calls.length).to.equal(0)
describe 'clear', ->
it 'should be able to clear all key values from a config object', ->
config = new AWS.Config(credentials: {}, maxRetries: 300, sslEnabled: 'foo')
expect(config.maxRetries).to.equal(300)
expect(config.sslEnabled).to.equal('foo')
expect(config.credentials).not.to.equal(undefined)
config.clear()
expect(config.maxRetries).to.equal(undefined)
expect(config.sslEnabled).to.equal(undefined)
expect(config.credentials).not.to.equal(undefined)
expect(config.credentialProvider).not.to.equal(undefined)
describe 'update', ->
it 'should be able to update keyed values', ->
config = new AWS.Config()
expect(config.maxRetries).to.equal(undefined)
config.update(maxRetries: 10)
expect(config.maxRetries).to.equal(10)
it 'should ignore non-keyed values', ->
config = new AWS.Config()
config.update(foo: 10)
expect(config.foo).to.equal(undefined)
it 'should allow service identifiers to be set', ->
config = new AWS.Config()
config.update(s3: {endpoint: 'localhost'})
expect(config.s3).to.eql(endpoint: 'localhost')
it 'allows unknown keys if allowUnknownKeys is set', ->
config = new AWS.Config()
config.update(foo: 10, true)
expect(config.foo).to.equal(10)
it 'should be able to update literal credentials', ->
config = new AWS.Config()
config.update(
accessKeyId: '<KEY>',
secretAccessKey: '<KEY>',
sessionToken: '<PASSWORD>')
expect(config.credentials.accessKeyId).to.equal('<KEY>')
expect(config.credentials.secretAccessKey).to.equal('<KEY>')
expect(config.credentials.sessionToken).to.equal('session')
it 'should deep merge httpOptions', ->
config = new AWS.Config()
config.update httpOptions: timeout: 1
config.update httpOptions: { xhrSync: true }
expect(config.httpOptions.timeout).to.equal(1)
expect(config.httpOptions.xhrSync).to.equal(true)
describe 'getCredentials', ->
spy = null
config = null
beforeEach ->
spy = helpers.createSpy('getCredentials callback')
expectValid = (options, key) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0]).not.to.exist
if key
expect(config.credentials.accessKeyId).to.equal(key)
expectError = (options, message) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0].code).to.equal('CredentialsError')
expect(spy.calls[0].arguments[0].message).to.equal(message)
it 'should check credentials for static object first', ->
expectValid credentials: accessKeyId: '1<KEY>', secretAccessKey: '<KEY>'
it 'should error if static credentials are not available', ->
expectError(credentials: {}, 'Missing credentials')
it 'should check credentials for async get() method', ->
expectValid credentials: get: (cb) -> cb()
it 'should error if credentials.get() cannot resolve', ->
options = credentials:
constructor: name: 'CustomCredentials'
get: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from CustomCredentials'
it 'should check credentialProvider if no credentials', ->
expectValid credentials: null, credentialProvider:
resolve: (cb) -> cb(null, accessKeyId: 'key', secretAccessKey: 'secret')
it 'should error if credentialProvider fails to resolve', ->
options = credentials: null, credentialProvider:
resolve: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from any providers'
it 'should error if no credentials or credentialProvider', ->
options = credentials: null, credentialProvider: null
expectError options, 'No credentials to load'
describe 'AWS.config', ->
it 'should be a default Config object', ->
expect(AWS.config.sslEnabled).to.equal(true)
expect(AWS.config.maxRetries).to.equal(undefined)
it 'can set default config to an object literal', ->
oldConfig = AWS.config
AWS.config = {}
expect(AWS.config).to.eql({})
AWS.config = oldConfig
describe 'setPromisesDependency', ->
it 'updates promise support on requests', ->
utilSpy = helpers.spyOn(AWS.util, 'addPromisesToRequests')
AWS.config.setPromisesDependency(->)
expect(utilSpy.calls.length).to.equal(1) | true | helpers = require('./helpers')
AWS = helpers.AWS
configure = (options) -> new AWS.Config(options)
describe 'AWS.Config', ->
describe 'constructor', ->
it 'should be able to pass in a Config object as parameter', ->
config = new AWS.Config(sslEnabled: false, maxRetries: 0)
copyConfig = new AWS.Config(config)
expect(copyConfig).not.to.equal(config)
expect(copyConfig.sslEnabled).to.equal(false)
expect(copyConfig.maxRetries).to.equal(0)
it 'should be able to pass credential values directly', ->
config = new AWS.Config(
accessKeyId: 'PI:KEY:<KEY>END_PI',
secretAccessKey: 'PI:KEY:<KEY>END_PI',
sessionToken: 'PI:PASSWORD:<PASSWORD>END_PI')
expect(config.credentials.accessKeyId).to.equal('akPI:KEY:<KEY>END_PI')
expect(config.credentials.secretAccessKey).to.equal('PI:KEY:<KEY>END_PI')
expect(config.credentials.sessionToken).to.equal('session')
describe 'region', ->
oldEnv = process.env
beforeEach ->
process.env = {}
afterEach ->
process.env = oldEnv
it 'defaults to undefined', ->
expect(configure().region).not.to.exist
if AWS.util.isNode()
it 'grabs AWS_REGION from the env', ->
process.env.AWS_REGION = 'us-west-2'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'also grabs AMAZON_REGION from the env', ->
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-1')
it 'prefers AWS_REGION to AMAZON_REGION', ->
process.env.AWS_REGION = 'us-west-2'
process.env.AMAZON_REGION = 'us-west-1'
config = new AWS.Config()
expect(config.region).to.equal('us-west-2')
it 'can be set to a string', ->
expect(configure(region: 'us-west-1').region).to.equal('us-west-1')
describe 'maxRetries', ->
it 'defaults to unefined', ->
expect(configure().maxRetries).to.equal(undefined)
it 'can be set to an integer', ->
expect(configure(maxRetries: 2).maxRetries).to.equal(2)
describe 'retryDelayOptions', ->
it 'defaults to "base: 100"', ->
expect(configure().retryDelayOptions).to.eql({base: 100})
it 'can set "base" to an integer', ->
expect(configure(retryDelayOptions: {base: 30}).retryDelayOptions).to.eql({base: 30})
describe 'paramValidation', ->
it 'defaults to true', ->
expect(configure().paramValidation).to.equal(true)
describe 'computeChecksums', ->
it 'defaults to true', ->
expect(configure().computeChecksums).to.equal(true)
describe 'sslEnabled', ->
it 'defaults to true', ->
expect(configure().sslEnabled).to.equal(true)
it 'can be set to false', ->
expect(configure(sslEnabled: false).sslEnabled).to.equal(false)
describe 'httpOptions', ->
it 'defaults to {timeout:120000}', ->
expect(configure().httpOptions).to.eql(timeout: 120000)
describe 'systemClockOffset', ->
it 'defaults to 0', ->
expect(configure().systemClockOffset).to.equal(0)
describe 'correctClockSkew', ->
it 'defaults to false', ->
expect(configure().correctClockSkew).to.equal(false)
describe 'customUserAgent', ->
it 'defaults to null', ->
expect(configure().customUserAgent).to.equal(null)
describe 'set', ->
it 'should set a default value for a key', ->
config = new AWS.Config()
config.set('maxRetries', undefined, 'DEFAULT')
expect(config.maxRetries).to.equal('DEFAULT')
it 'should execute default value if it is a function', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', undefined, mock)
expect(mock.calls.length).not.to.equal(0)
it 'should not expand default value function if value is present', ->
mock = helpers.createSpy()
config = new AWS.Config()
config.set('maxRetries', 'VALUE', mock)
expect(mock.calls.length).to.equal(0)
describe 'clear', ->
it 'should be able to clear all key values from a config object', ->
config = new AWS.Config(credentials: {}, maxRetries: 300, sslEnabled: 'foo')
expect(config.maxRetries).to.equal(300)
expect(config.sslEnabled).to.equal('foo')
expect(config.credentials).not.to.equal(undefined)
config.clear()
expect(config.maxRetries).to.equal(undefined)
expect(config.sslEnabled).to.equal(undefined)
expect(config.credentials).not.to.equal(undefined)
expect(config.credentialProvider).not.to.equal(undefined)
describe 'update', ->
it 'should be able to update keyed values', ->
config = new AWS.Config()
expect(config.maxRetries).to.equal(undefined)
config.update(maxRetries: 10)
expect(config.maxRetries).to.equal(10)
it 'should ignore non-keyed values', ->
config = new AWS.Config()
config.update(foo: 10)
expect(config.foo).to.equal(undefined)
it 'should allow service identifiers to be set', ->
config = new AWS.Config()
config.update(s3: {endpoint: 'localhost'})
expect(config.s3).to.eql(endpoint: 'localhost')
it 'allows unknown keys if allowUnknownKeys is set', ->
config = new AWS.Config()
config.update(foo: 10, true)
expect(config.foo).to.equal(10)
it 'should be able to update literal credentials', ->
config = new AWS.Config()
config.update(
accessKeyId: 'PI:KEY:<KEY>END_PI',
secretAccessKey: 'PI:KEY:<KEY>END_PI',
sessionToken: 'PI:KEY:<PASSWORD>END_PI')
expect(config.credentials.accessKeyId).to.equal('PI:KEY:<KEY>END_PI')
expect(config.credentials.secretAccessKey).to.equal('PI:KEY:<KEY>END_PI')
expect(config.credentials.sessionToken).to.equal('session')
it 'should deep merge httpOptions', ->
config = new AWS.Config()
config.update httpOptions: timeout: 1
config.update httpOptions: { xhrSync: true }
expect(config.httpOptions.timeout).to.equal(1)
expect(config.httpOptions.xhrSync).to.equal(true)
describe 'getCredentials', ->
spy = null
config = null
beforeEach ->
spy = helpers.createSpy('getCredentials callback')
expectValid = (options, key) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0]).not.to.exist
if key
expect(config.credentials.accessKeyId).to.equal(key)
expectError = (options, message) ->
if options instanceof AWS.Config
config = options
else
config = new AWS.Config(options)
config.getCredentials(spy)
expect(spy.calls.length).not.to.equal(0)
expect(spy.calls[0].arguments[0].code).to.equal('CredentialsError')
expect(spy.calls[0].arguments[0].message).to.equal(message)
it 'should check credentials for static object first', ->
expectValid credentials: accessKeyId: '1PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI'
it 'should error if static credentials are not available', ->
expectError(credentials: {}, 'Missing credentials')
it 'should check credentials for async get() method', ->
expectValid credentials: get: (cb) -> cb()
it 'should error if credentials.get() cannot resolve', ->
options = credentials:
constructor: name: 'CustomCredentials'
get: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from CustomCredentials'
it 'should check credentialProvider if no credentials', ->
expectValid credentials: null, credentialProvider:
resolve: (cb) -> cb(null, accessKeyId: 'key', secretAccessKey: 'secret')
it 'should error if credentialProvider fails to resolve', ->
options = credentials: null, credentialProvider:
resolve: (cb) -> cb(new Error('Error!'), null)
expectError options, 'Could not load credentials from any providers'
it 'should error if no credentials or credentialProvider', ->
options = credentials: null, credentialProvider: null
expectError options, 'No credentials to load'
describe 'AWS.config', ->
it 'should be a default Config object', ->
expect(AWS.config.sslEnabled).to.equal(true)
expect(AWS.config.maxRetries).to.equal(undefined)
it 'can set default config to an object literal', ->
oldConfig = AWS.config
AWS.config = {}
expect(AWS.config).to.eql({})
AWS.config = oldConfig
describe 'setPromisesDependency', ->
it 'updates promise support on requests', ->
utilSpy = helpers.spyOn(AWS.util, 'addPromisesToRequests')
AWS.config.setPromisesDependency(->)
expect(utilSpy.calls.length).to.equal(1) |
[
{
"context": " email: validUser.email\n password: 'secret123'\n })\n\n $httpBackend.flush()\n\n teardo",
"end": 2731,
"score": 0.999326765537262,
"start": 2722,
"tag": "PASSWORD",
"value": "secret123"
}
] | test/test/unit/ng-token-auth/configuration.coffee | ybian/ng-token-auth | 2 | suite 'configuration', ->
suite 'basic settings', ->
apiUrl = '/kronos'
setup ->
sinon.spy($auth, 'validateUser')
$authProvider.configure({
apiUrl: apiUrl
validateOnPageLoad: true
proxyIf: -> true
})
# restore defaults
teardown ->
$authProvider.configure({
apiUrl: '/api'
proxyIf: -> false
})
test 'apiUrl has been changed', ->
assert.equal apiUrl, $auth.getConfig().apiUrl
test '$auth proxies to proxy url', ->
assert.equal '/proxy', $auth.apiUrl()
test 'headers are appended to requests to proxy', ->
successResp =
success: true
data: validUser
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$httpBackend
.expectGET('/proxy/auth/validate_token', (headers) ->
assert.equal(validAuthHeader['access-token'], headers['access-token'])
headers
)
.respond(201, successResp, {'access-token', 'whatever'})
$auth.validateUser()
$httpBackend.flush()
suite 'alternate token format', ->
expectedHeaders =
"Authorization": "token=#{validToken} expiry=#{validExpiry} uid=#{validUid}"
setup ->
$authProvider.configure({
tokenFormat:
"Authorization": "token={{token}} expiry={{expiry}} uid={{uid}}"
parseExpiry: (headers) ->
(parseInt(headers['Authorization'].match(/expiry=([^ ]+) /)[1], 10)) || null
})
teardown ->
$authProvider.configure({
tokenFormat:
"access-token": "{{ token }}"
"token-type": "Bearer"
client: "{{ clientId }}"
expiry: "{{ expiry }}"
uid: "{{ uid }}"
parseExpiry: (headers) ->
(parseInt(headers['expiry'], 10) * 1000) || null
})
test 'auth headers are built according to config.tokenFormat', ->
headers = $auth.buildAuthHeaders({
token: validToken
clientId: validClient
uid: validUid
expiry: validExpiry
})
assert.deepEqual(headers, expectedHeaders)
test 'expiry should be derived from cached headers', ->
$auth.setAuthHeaders(expectedHeaders)
expiry = $auth.getExpiry()
assert.equal(expiry, validExpiry)
suite 'alternate login response format', ->
setup ->
# define custom login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp
})
# return non-standard login response format
$httpBackend
.expectPOST('/api/auth/sign_in')
.respond(201, validUser)
$auth.submitLogin({
email: validUser.email
password: 'secret123'
})
$httpBackend.flush()
teardown ->
# restore default login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
test 'success event should return user info', ->
assert $rootScope.$broadcast.calledWithMatch('auth:login-success', validUser)
suite 'alternate token validation response format', ->
successResp = validUser
newAuthHeader = {
"access-token": "(✿◠‿◠)"
"token-type": 'Bearer'
client: validClient
expiry: validExpiry.toString()
uid: validUid.toString()
}
dfd = null
setup ->
# define custom token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp
})
$httpBackend
.expectGET('/api/auth/validate_token')
.respond(201, successResp, newAuthHeader)
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$auth.validateUser()
$httpBackend.flush()
teardown ->
# restore default token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
| 211477 | suite 'configuration', ->
suite 'basic settings', ->
apiUrl = '/kronos'
setup ->
sinon.spy($auth, 'validateUser')
$authProvider.configure({
apiUrl: apiUrl
validateOnPageLoad: true
proxyIf: -> true
})
# restore defaults
teardown ->
$authProvider.configure({
apiUrl: '/api'
proxyIf: -> false
})
test 'apiUrl has been changed', ->
assert.equal apiUrl, $auth.getConfig().apiUrl
test '$auth proxies to proxy url', ->
assert.equal '/proxy', $auth.apiUrl()
test 'headers are appended to requests to proxy', ->
successResp =
success: true
data: validUser
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$httpBackend
.expectGET('/proxy/auth/validate_token', (headers) ->
assert.equal(validAuthHeader['access-token'], headers['access-token'])
headers
)
.respond(201, successResp, {'access-token', 'whatever'})
$auth.validateUser()
$httpBackend.flush()
suite 'alternate token format', ->
expectedHeaders =
"Authorization": "token=#{validToken} expiry=#{validExpiry} uid=#{validUid}"
setup ->
$authProvider.configure({
tokenFormat:
"Authorization": "token={{token}} expiry={{expiry}} uid={{uid}}"
parseExpiry: (headers) ->
(parseInt(headers['Authorization'].match(/expiry=([^ ]+) /)[1], 10)) || null
})
teardown ->
$authProvider.configure({
tokenFormat:
"access-token": "{{ token }}"
"token-type": "Bearer"
client: "{{ clientId }}"
expiry: "{{ expiry }}"
uid: "{{ uid }}"
parseExpiry: (headers) ->
(parseInt(headers['expiry'], 10) * 1000) || null
})
test 'auth headers are built according to config.tokenFormat', ->
headers = $auth.buildAuthHeaders({
token: validToken
clientId: validClient
uid: validUid
expiry: validExpiry
})
assert.deepEqual(headers, expectedHeaders)
test 'expiry should be derived from cached headers', ->
$auth.setAuthHeaders(expectedHeaders)
expiry = $auth.getExpiry()
assert.equal(expiry, validExpiry)
suite 'alternate login response format', ->
setup ->
# define custom login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp
})
# return non-standard login response format
$httpBackend
.expectPOST('/api/auth/sign_in')
.respond(201, validUser)
$auth.submitLogin({
email: validUser.email
password: '<PASSWORD>'
})
$httpBackend.flush()
teardown ->
# restore default login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
test 'success event should return user info', ->
assert $rootScope.$broadcast.calledWithMatch('auth:login-success', validUser)
suite 'alternate token validation response format', ->
successResp = validUser
newAuthHeader = {
"access-token": "(✿◠‿◠)"
"token-type": 'Bearer'
client: validClient
expiry: validExpiry.toString()
uid: validUid.toString()
}
dfd = null
setup ->
# define custom token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp
})
$httpBackend
.expectGET('/api/auth/validate_token')
.respond(201, successResp, newAuthHeader)
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$auth.validateUser()
$httpBackend.flush()
teardown ->
# restore default token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
| true | suite 'configuration', ->
suite 'basic settings', ->
apiUrl = '/kronos'
setup ->
sinon.spy($auth, 'validateUser')
$authProvider.configure({
apiUrl: apiUrl
validateOnPageLoad: true
proxyIf: -> true
})
# restore defaults
teardown ->
$authProvider.configure({
apiUrl: '/api'
proxyIf: -> false
})
test 'apiUrl has been changed', ->
assert.equal apiUrl, $auth.getConfig().apiUrl
test '$auth proxies to proxy url', ->
assert.equal '/proxy', $auth.apiUrl()
test 'headers are appended to requests to proxy', ->
successResp =
success: true
data: validUser
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$httpBackend
.expectGET('/proxy/auth/validate_token', (headers) ->
assert.equal(validAuthHeader['access-token'], headers['access-token'])
headers
)
.respond(201, successResp, {'access-token', 'whatever'})
$auth.validateUser()
$httpBackend.flush()
suite 'alternate token format', ->
expectedHeaders =
"Authorization": "token=#{validToken} expiry=#{validExpiry} uid=#{validUid}"
setup ->
$authProvider.configure({
tokenFormat:
"Authorization": "token={{token}} expiry={{expiry}} uid={{uid}}"
parseExpiry: (headers) ->
(parseInt(headers['Authorization'].match(/expiry=([^ ]+) /)[1], 10)) || null
})
teardown ->
$authProvider.configure({
tokenFormat:
"access-token": "{{ token }}"
"token-type": "Bearer"
client: "{{ clientId }}"
expiry: "{{ expiry }}"
uid: "{{ uid }}"
parseExpiry: (headers) ->
(parseInt(headers['expiry'], 10) * 1000) || null
})
test 'auth headers are built according to config.tokenFormat', ->
headers = $auth.buildAuthHeaders({
token: validToken
clientId: validClient
uid: validUid
expiry: validExpiry
})
assert.deepEqual(headers, expectedHeaders)
test 'expiry should be derived from cached headers', ->
$auth.setAuthHeaders(expectedHeaders)
expiry = $auth.getExpiry()
assert.equal(expiry, validExpiry)
suite 'alternate login response format', ->
setup ->
# define custom login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp
})
# return non-standard login response format
$httpBackend
.expectPOST('/api/auth/sign_in')
.respond(201, validUser)
$auth.submitLogin({
email: validUser.email
password: 'PI:PASSWORD:<PASSWORD>END_PI'
})
$httpBackend.flush()
teardown ->
# restore default login response handler
$authProvider.configure({
handleLoginResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
test 'success event should return user info', ->
assert $rootScope.$broadcast.calledWithMatch('auth:login-success', validUser)
suite 'alternate token validation response format', ->
successResp = validUser
newAuthHeader = {
"access-token": "(✿◠‿◠)"
"token-type": 'Bearer'
client: validClient
expiry: validExpiry.toString()
uid: validUid.toString()
}
dfd = null
setup ->
# define custom token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp
})
$httpBackend
.expectGET('/api/auth/validate_token')
.respond(201, successResp, newAuthHeader)
ipCookie('auth_headers', validAuthHeader, {path: '/'})
$auth.validateUser()
$httpBackend.flush()
teardown ->
# restore default token validation response handler
$authProvider.configure({
handleTokenValidationResponse: (resp) -> resp.data
})
test 'new user is defined in the root scope', ->
assert.equal(validUser.uid, $rootScope.user.uid)
|
[
{
"context": " beforeEach ->\n mob = new Mob\n name: 'foo'\n gender: Mob.gender.male\n level: 5",
"end": 6819,
"score": 0.8845665454864502,
"start": 6816,
"tag": "NAME",
"value": "foo"
}
] | plugins/coffeekeep.core/test/security.coffee | leonexis/coffeekeep | 0 | should = require 'should'
security = require '../security'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
]
describe 'coffeekeep.core:security', ->
app = null
log = null
Mob = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
Mob = app.getService('model').models.mob
done null
after ->
app.destroy()
describe 'AttributeResolver', ->
br = new security.AttributeResolver
foo: 1
bar: 'baz'
tree:
leaf: 'foo'
list: ['foo', 'bar']
it 'should support "get"', ->
br.get('foo').should.eql 1
br.get('bar').should.eql 'baz'
it 'should support dotted property form', ->
br.get('tree.leaf').should.eql 'foo'
should(br.get('tree.foo')).eql null
should(br.get('trees.baz')).eql null
it 'should support "equal"', ->
br.equal('bar', 'baz').should.be.true
br.equal('bar', 'faz').should.be.false
br.equal('foo', 1).should.be.true
br.equal('foo', '1').should.be.true
it 'should support "gt"', ->
br.gt('foo', 0).should.be.true
br.gt('foo', 1).should.be.false
br.gt('foo', 2).should.be.false
br.gt('bar', 0).should.be.false
it 'should support "gte"', ->
br.gte('foo', 0).should.be.true
br.gte('foo', 1).should.be.true
br.gte('foo', 2).should.be.false
br.gte('bar', 0).should.be.false
it 'should support "lt"', ->
br.lt('foo', 0).should.be.false
br.lt('foo', 1).should.be.false
br.lt('foo', 2).should.be.true
br.lt('bar', 0).should.be.false
it 'should support "lte"', ->
br.lte('foo', 0).should.be.false
br.lte('foo', 1).should.be.true
br.lte('foo', 2).should.be.true
br.lte('bar', 0).should.be.false
it 'should support "has"', ->
br.has('list', 'foo').should.be.true
br.has('list', 'baz').should.be.false
it.skip 'should support substrings in "has"', ->
br.has('bar', 'oo').should.be.false
br.has('bar', 'az').should.be.true
describe 'MaskFactory', ->
describe '#parse', ->
mf = new security.MaskFactory()
it 'should parse just attributes', ->
tokens = mf.parse 'all'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'all'
tokens[0].should.have.property 'operator', undefined
tokens[0].should.have.property 'value', undefined
it 'should parse complex attributes', ->
tokens = mf.parse 'level>5'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>'
tokens[0].should.have.property 'value', '5'
it 'should only allow <, > with numbers', ->
for op in ['>', '<', '>=', '<=']
do ->
(->
mf.parse "level#{op}foo"
).should.throw /does not match/
(->
mf.parse "level#{op}5"
).should.not.throw()
it 'should support floating point numbers for <, >', ->
mf.parse "level<0.52342"
mf.parse "level>1.31234:foo"
mf.parse "level<=4.22134:foo,bar"
tokens = mf.parse "level>=0.999:foo,baz"
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>='
tokens[0].should.have.property 'value', '0.999'
it 'should support prefixes +, - or no prefix', ->
for op in ['+', '-']
do ->
token = mf.parse op + "all"
token[0].should.have.property 'prefix', op
it 'should support multiple permissions', ->
tokens = mf.parse 'level:one,two'
tokens.should.have.length 1
tokens[0].should.have.property 'permissions'
tokens[0].permissions.should.have.length 2
tokens[0].permissions[0].should.eql 'one'
it 'should support quotes with spaces', ->
tokens = mf.parse 'name="foo bar"'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'name'
tokens[0].should.have.property 'operator', '='
tokens[0].should.have.property 'value', 'foo bar'
it 'should support multiple tokens in an ACL', ->
tokens = mf.parse '+all:say,tell +level>5:ooc -guest:ooc'
tokens.should.have.length 3
[t0, t1, t2] = tokens
t0.should.have.property 'name', 'all'
t0.should.have.property 'prefix', '+'
t1.should.have.property 'name', 'level'
t1.should.have.property 'operator', '>'
t1.permissions.should.have.length 1
t1.permissions.should.eql ['ooc']
t2.should.have.property 'prefix', '-'
describe '#resolve', ->
fr = null
mf = new security.MaskFactory()
beforeEach ->
fr = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve "all"', ->
perms = mf.resolve '+all:one', fr
perms.should.containEql ''
perms.should.containEql 'one'
it 'should support additive tokens', ->
perms = mf.resolve '+all +level>6:one +abilities.foo:two', fr
perms.should.containEql ''
perms.should.containEql 'two'
perms.should.not.containEql 'one'
it 'should support subtractive tokens', ->
perms = mf.resolve(
'+all:one,two,three -level<5:two -level<10:three', fr)
perms.should.containEql ''
perms.should.containEql 'one'
perms.should.containEql 'two'
perms.should.not.containEql 'three'
describe 'Mask', ->
ar = null
beforeEach ->
ar = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve', ->
mask = new security.Mask '+all:one'
mask.resolve(ar).should.containEql 'one'
it 'should check for permissions', ->
mask = new security.Mask '+all:one'
mask.hasPermission(ar, 'one').should.be.true
it 'should allow positive wildcards', ->
mask = new security.Mask '-all +level>5 +sysop:*'
mask.hasPermission(ar, 'anything').should.be.false
mask.hasPermission(ar, '').should.be.false
ar.attributes['level'] = 6
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.false
ar.attributes['level'] = 5
ar.attributes['sysop'] = true
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.true
describe 'Mob#hasPermission', ->
mob = null
beforeEach ->
mob = new Mob
name: 'foo'
gender: Mob.gender.male
level: 5
it 'should match on basic attributes', ->
mob.hasPermission('+all').should.be.true
mob.hasPermission('-all +level>=5').should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.false
mob.set 'level', 10
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.true
it 'should match on gender string', ->
mob.hasPermission('-all +gender=male').should.be.true
mob.hasPermission('-all +gender=transman').should.be.false
mob.hasPermission('-all +gender=female').should.be.false
mob.set 'gender', Mob.gender.transman
mob.hasPermission('-all +gender=transman').should.be.true
mob.hasPermission('-all +gender=male').should.be.true
| 156315 | should = require 'should'
security = require '../security'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
]
describe 'coffeekeep.core:security', ->
app = null
log = null
Mob = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
Mob = app.getService('model').models.mob
done null
after ->
app.destroy()
describe 'AttributeResolver', ->
br = new security.AttributeResolver
foo: 1
bar: 'baz'
tree:
leaf: 'foo'
list: ['foo', 'bar']
it 'should support "get"', ->
br.get('foo').should.eql 1
br.get('bar').should.eql 'baz'
it 'should support dotted property form', ->
br.get('tree.leaf').should.eql 'foo'
should(br.get('tree.foo')).eql null
should(br.get('trees.baz')).eql null
it 'should support "equal"', ->
br.equal('bar', 'baz').should.be.true
br.equal('bar', 'faz').should.be.false
br.equal('foo', 1).should.be.true
br.equal('foo', '1').should.be.true
it 'should support "gt"', ->
br.gt('foo', 0).should.be.true
br.gt('foo', 1).should.be.false
br.gt('foo', 2).should.be.false
br.gt('bar', 0).should.be.false
it 'should support "gte"', ->
br.gte('foo', 0).should.be.true
br.gte('foo', 1).should.be.true
br.gte('foo', 2).should.be.false
br.gte('bar', 0).should.be.false
it 'should support "lt"', ->
br.lt('foo', 0).should.be.false
br.lt('foo', 1).should.be.false
br.lt('foo', 2).should.be.true
br.lt('bar', 0).should.be.false
it 'should support "lte"', ->
br.lte('foo', 0).should.be.false
br.lte('foo', 1).should.be.true
br.lte('foo', 2).should.be.true
br.lte('bar', 0).should.be.false
it 'should support "has"', ->
br.has('list', 'foo').should.be.true
br.has('list', 'baz').should.be.false
it.skip 'should support substrings in "has"', ->
br.has('bar', 'oo').should.be.false
br.has('bar', 'az').should.be.true
describe 'MaskFactory', ->
describe '#parse', ->
mf = new security.MaskFactory()
it 'should parse just attributes', ->
tokens = mf.parse 'all'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'all'
tokens[0].should.have.property 'operator', undefined
tokens[0].should.have.property 'value', undefined
it 'should parse complex attributes', ->
tokens = mf.parse 'level>5'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>'
tokens[0].should.have.property 'value', '5'
it 'should only allow <, > with numbers', ->
for op in ['>', '<', '>=', '<=']
do ->
(->
mf.parse "level#{op}foo"
).should.throw /does not match/
(->
mf.parse "level#{op}5"
).should.not.throw()
it 'should support floating point numbers for <, >', ->
mf.parse "level<0.52342"
mf.parse "level>1.31234:foo"
mf.parse "level<=4.22134:foo,bar"
tokens = mf.parse "level>=0.999:foo,baz"
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>='
tokens[0].should.have.property 'value', '0.999'
it 'should support prefixes +, - or no prefix', ->
for op in ['+', '-']
do ->
token = mf.parse op + "all"
token[0].should.have.property 'prefix', op
it 'should support multiple permissions', ->
tokens = mf.parse 'level:one,two'
tokens.should.have.length 1
tokens[0].should.have.property 'permissions'
tokens[0].permissions.should.have.length 2
tokens[0].permissions[0].should.eql 'one'
it 'should support quotes with spaces', ->
tokens = mf.parse 'name="foo bar"'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'name'
tokens[0].should.have.property 'operator', '='
tokens[0].should.have.property 'value', 'foo bar'
it 'should support multiple tokens in an ACL', ->
tokens = mf.parse '+all:say,tell +level>5:ooc -guest:ooc'
tokens.should.have.length 3
[t0, t1, t2] = tokens
t0.should.have.property 'name', 'all'
t0.should.have.property 'prefix', '+'
t1.should.have.property 'name', 'level'
t1.should.have.property 'operator', '>'
t1.permissions.should.have.length 1
t1.permissions.should.eql ['ooc']
t2.should.have.property 'prefix', '-'
describe '#resolve', ->
fr = null
mf = new security.MaskFactory()
beforeEach ->
fr = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve "all"', ->
perms = mf.resolve '+all:one', fr
perms.should.containEql ''
perms.should.containEql 'one'
it 'should support additive tokens', ->
perms = mf.resolve '+all +level>6:one +abilities.foo:two', fr
perms.should.containEql ''
perms.should.containEql 'two'
perms.should.not.containEql 'one'
it 'should support subtractive tokens', ->
perms = mf.resolve(
'+all:one,two,three -level<5:two -level<10:three', fr)
perms.should.containEql ''
perms.should.containEql 'one'
perms.should.containEql 'two'
perms.should.not.containEql 'three'
describe 'Mask', ->
ar = null
beforeEach ->
ar = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve', ->
mask = new security.Mask '+all:one'
mask.resolve(ar).should.containEql 'one'
it 'should check for permissions', ->
mask = new security.Mask '+all:one'
mask.hasPermission(ar, 'one').should.be.true
it 'should allow positive wildcards', ->
mask = new security.Mask '-all +level>5 +sysop:*'
mask.hasPermission(ar, 'anything').should.be.false
mask.hasPermission(ar, '').should.be.false
ar.attributes['level'] = 6
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.false
ar.attributes['level'] = 5
ar.attributes['sysop'] = true
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.true
describe 'Mob#hasPermission', ->
mob = null
beforeEach ->
mob = new Mob
name: '<NAME>'
gender: Mob.gender.male
level: 5
it 'should match on basic attributes', ->
mob.hasPermission('+all').should.be.true
mob.hasPermission('-all +level>=5').should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.false
mob.set 'level', 10
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.true
it 'should match on gender string', ->
mob.hasPermission('-all +gender=male').should.be.true
mob.hasPermission('-all +gender=transman').should.be.false
mob.hasPermission('-all +gender=female').should.be.false
mob.set 'gender', Mob.gender.transman
mob.hasPermission('-all +gender=transman').should.be.true
mob.hasPermission('-all +gender=male').should.be.true
| true | should = require 'should'
security = require '../security'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
]
describe 'coffeekeep.core:security', ->
app = null
log = null
Mob = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
Mob = app.getService('model').models.mob
done null
after ->
app.destroy()
describe 'AttributeResolver', ->
br = new security.AttributeResolver
foo: 1
bar: 'baz'
tree:
leaf: 'foo'
list: ['foo', 'bar']
it 'should support "get"', ->
br.get('foo').should.eql 1
br.get('bar').should.eql 'baz'
it 'should support dotted property form', ->
br.get('tree.leaf').should.eql 'foo'
should(br.get('tree.foo')).eql null
should(br.get('trees.baz')).eql null
it 'should support "equal"', ->
br.equal('bar', 'baz').should.be.true
br.equal('bar', 'faz').should.be.false
br.equal('foo', 1).should.be.true
br.equal('foo', '1').should.be.true
it 'should support "gt"', ->
br.gt('foo', 0).should.be.true
br.gt('foo', 1).should.be.false
br.gt('foo', 2).should.be.false
br.gt('bar', 0).should.be.false
it 'should support "gte"', ->
br.gte('foo', 0).should.be.true
br.gte('foo', 1).should.be.true
br.gte('foo', 2).should.be.false
br.gte('bar', 0).should.be.false
it 'should support "lt"', ->
br.lt('foo', 0).should.be.false
br.lt('foo', 1).should.be.false
br.lt('foo', 2).should.be.true
br.lt('bar', 0).should.be.false
it 'should support "lte"', ->
br.lte('foo', 0).should.be.false
br.lte('foo', 1).should.be.true
br.lte('foo', 2).should.be.true
br.lte('bar', 0).should.be.false
it 'should support "has"', ->
br.has('list', 'foo').should.be.true
br.has('list', 'baz').should.be.false
it.skip 'should support substrings in "has"', ->
br.has('bar', 'oo').should.be.false
br.has('bar', 'az').should.be.true
describe 'MaskFactory', ->
describe '#parse', ->
mf = new security.MaskFactory()
it 'should parse just attributes', ->
tokens = mf.parse 'all'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'all'
tokens[0].should.have.property 'operator', undefined
tokens[0].should.have.property 'value', undefined
it 'should parse complex attributes', ->
tokens = mf.parse 'level>5'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>'
tokens[0].should.have.property 'value', '5'
it 'should only allow <, > with numbers', ->
for op in ['>', '<', '>=', '<=']
do ->
(->
mf.parse "level#{op}foo"
).should.throw /does not match/
(->
mf.parse "level#{op}5"
).should.not.throw()
it 'should support floating point numbers for <, >', ->
mf.parse "level<0.52342"
mf.parse "level>1.31234:foo"
mf.parse "level<=4.22134:foo,bar"
tokens = mf.parse "level>=0.999:foo,baz"
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'level'
tokens[0].should.have.property 'operator', '>='
tokens[0].should.have.property 'value', '0.999'
it 'should support prefixes +, - or no prefix', ->
for op in ['+', '-']
do ->
token = mf.parse op + "all"
token[0].should.have.property 'prefix', op
it 'should support multiple permissions', ->
tokens = mf.parse 'level:one,two'
tokens.should.have.length 1
tokens[0].should.have.property 'permissions'
tokens[0].permissions.should.have.length 2
tokens[0].permissions[0].should.eql 'one'
it 'should support quotes with spaces', ->
tokens = mf.parse 'name="foo bar"'
tokens.should.have.length 1
tokens[0].should.have.property 'name', 'name'
tokens[0].should.have.property 'operator', '='
tokens[0].should.have.property 'value', 'foo bar'
it 'should support multiple tokens in an ACL', ->
tokens = mf.parse '+all:say,tell +level>5:ooc -guest:ooc'
tokens.should.have.length 3
[t0, t1, t2] = tokens
t0.should.have.property 'name', 'all'
t0.should.have.property 'prefix', '+'
t1.should.have.property 'name', 'level'
t1.should.have.property 'operator', '>'
t1.permissions.should.have.length 1
t1.permissions.should.eql ['ooc']
t2.should.have.property 'prefix', '-'
describe '#resolve', ->
fr = null
mf = new security.MaskFactory()
beforeEach ->
fr = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve "all"', ->
perms = mf.resolve '+all:one', fr
perms.should.containEql ''
perms.should.containEql 'one'
it 'should support additive tokens', ->
perms = mf.resolve '+all +level>6:one +abilities.foo:two', fr
perms.should.containEql ''
perms.should.containEql 'two'
perms.should.not.containEql 'one'
it 'should support subtractive tokens', ->
perms = mf.resolve(
'+all:one,two,three -level<5:two -level<10:three', fr)
perms.should.containEql ''
perms.should.containEql 'one'
perms.should.containEql 'two'
perms.should.not.containEql 'three'
describe 'Mask', ->
ar = null
beforeEach ->
ar = new security.AttributeResolver
sysop: false
abilities:
foo: 3
level: 5
it 'should resolve', ->
mask = new security.Mask '+all:one'
mask.resolve(ar).should.containEql 'one'
it 'should check for permissions', ->
mask = new security.Mask '+all:one'
mask.hasPermission(ar, 'one').should.be.true
it 'should allow positive wildcards', ->
mask = new security.Mask '-all +level>5 +sysop:*'
mask.hasPermission(ar, 'anything').should.be.false
mask.hasPermission(ar, '').should.be.false
ar.attributes['level'] = 6
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.false
ar.attributes['level'] = 5
ar.attributes['sysop'] = true
mask.hasPermission(ar, '').should.be.true
mask.hasPermission(ar, 'anything').should.be.true
describe 'Mob#hasPermission', ->
mob = null
beforeEach ->
mob = new Mob
name: 'PI:NAME:<NAME>END_PI'
gender: Mob.gender.male
level: 5
it 'should match on basic attributes', ->
mob.hasPermission('+all').should.be.true
mob.hasPermission('-all +level>=5').should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.false
mob.set 'level', 10
mob.hasPermission('-all +level>=5:one +level>=10:two', 'one')
.should.be.true
mob.hasPermission('-all +level>=5:one +level>=10:two', 'two')
.should.be.true
it 'should match on gender string', ->
mob.hasPermission('-all +gender=male').should.be.true
mob.hasPermission('-all +gender=transman').should.be.false
mob.hasPermission('-all +gender=female').should.be.false
mob.set 'gender', Mob.gender.transman
mob.hasPermission('-all +gender=transman').should.be.true
mob.hasPermission('-all +gender=male').should.be.true
|
[
{
"context": "o infomation views and the copyright.\n\n @author Sebastian Sachtleben\n###\nclass Footer extends BaseView\n\n\tclassName: 'f",
"end": 177,
"score": 0.9998905658721924,
"start": 157,
"tag": "NAME",
"value": "Sebastian Sachtleben"
}
] | app/assets/javascripts/admin/views/footer.coffee | ssachtleben/herowar | 1 | BaseView = require 'views/baseView'
templates = require 'templates'
###
The Footer shows some links to infomation views and the copyright.
@author Sebastian Sachtleben
###
class Footer extends BaseView
className: 'footer'
template: templates.get 'footer.tmpl'
return Footer | 55629 | BaseView = require 'views/baseView'
templates = require 'templates'
###
The Footer shows some links to infomation views and the copyright.
@author <NAME>
###
class Footer extends BaseView
className: 'footer'
template: templates.get 'footer.tmpl'
return Footer | true | BaseView = require 'views/baseView'
templates = require 'templates'
###
The Footer shows some links to infomation views and the copyright.
@author PI:NAME:<NAME>END_PI
###
class Footer extends BaseView
className: 'footer'
template: templates.get 'footer.tmpl'
return Footer |
[
{
"context": "g driver for channel #{CHANNEL} using username: #{USERNAME}, password: #{PASSWORD}\"\n\ndriver = new selenium.B",
"end": 235,
"score": 0.9928601980209351,
"start": 227,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "name]'\n .then (username) ->\n username.s... | automation/src/watch.coffee | codyseibert/random | 3 | selenium = require 'selenium-webdriver'
By = selenium.By
USERNAME = process.argv[2]
PASSWORD = process.argv[3]
CHANNEL = process.argv[4]
TIME = 5*60*1000
console.log "Starting driver for channel #{CHANNEL} using username: #{USERNAME}, password: #{PASSWORD}"
driver = new selenium.Builder()
.withCapabilities(selenium.Capabilities.chrome())
.build()
driver.getWindowHandle()
driver.manage().window().setSize 1200, 700
driver.get CHANNEL
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css '#header_login'
.then (element) ->
element.click()
.then ->
driver.sleep 5000
.then ->
driver.getWindowHandle()
.then (handle) ->
driver.sleep 5000
.then ->
driver.switchTo().frame 0
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css 'input[name=username]'
.then (username) ->
username.sendKeys USERNAME
.then ->
driver.findElement By.css 'input[name=password]'
.then (password) ->
password.sendKeys PASSWORD
.then ->
driver.findElement By.css 'input[type=submit]'
.then (submit) ->
submit.click()
.then ->
driver.sleep 5000
.then ->
driver.switchTo().defaultContent()
.then ->
driver.sleep TIME
.then ->
driver.quit()
| 176521 | selenium = require 'selenium-webdriver'
By = selenium.By
USERNAME = process.argv[2]
PASSWORD = process.argv[3]
CHANNEL = process.argv[4]
TIME = 5*60*1000
console.log "Starting driver for channel #{CHANNEL} using username: #{USERNAME}, password: #{PASSWORD}"
driver = new selenium.Builder()
.withCapabilities(selenium.Capabilities.chrome())
.build()
driver.getWindowHandle()
driver.manage().window().setSize 1200, 700
driver.get CHANNEL
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css '#header_login'
.then (element) ->
element.click()
.then ->
driver.sleep 5000
.then ->
driver.getWindowHandle()
.then (handle) ->
driver.sleep 5000
.then ->
driver.switchTo().frame 0
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css 'input[name=username]'
.then (username) ->
username.sendKeys USERNAME
.then ->
driver.findElement By.css 'input[name=password]'
.then (password) ->
password.sendKeys <PASSWORD>
.then ->
driver.findElement By.css 'input[type=submit]'
.then (submit) ->
submit.click()
.then ->
driver.sleep 5000
.then ->
driver.switchTo().defaultContent()
.then ->
driver.sleep TIME
.then ->
driver.quit()
| true | selenium = require 'selenium-webdriver'
By = selenium.By
USERNAME = process.argv[2]
PASSWORD = process.argv[3]
CHANNEL = process.argv[4]
TIME = 5*60*1000
console.log "Starting driver for channel #{CHANNEL} using username: #{USERNAME}, password: #{PASSWORD}"
driver = new selenium.Builder()
.withCapabilities(selenium.Capabilities.chrome())
.build()
driver.getWindowHandle()
driver.manage().window().setSize 1200, 700
driver.get CHANNEL
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css '#header_login'
.then (element) ->
element.click()
.then ->
driver.sleep 5000
.then ->
driver.getWindowHandle()
.then (handle) ->
driver.sleep 5000
.then ->
driver.switchTo().frame 0
.then ->
driver.sleep 5000
.then ->
driver.findElement By.css 'input[name=username]'
.then (username) ->
username.sendKeys USERNAME
.then ->
driver.findElement By.css 'input[name=password]'
.then (password) ->
password.sendKeys PI:PASSWORD:<PASSWORD>END_PI
.then ->
driver.findElement By.css 'input[type=submit]'
.then (submit) ->
submit.click()
.then ->
driver.sleep 5000
.then ->
driver.switchTo().defaultContent()
.then ->
driver.sleep TIME
.then ->
driver.quit()
|
[
{
"context": "T_KEY - AWS Secret Key for Billing\n#\n# Author:\n# moqada <moqada@gmail.com>\nKanjo = require 'kanjo'\nTable ",
"end": 515,
"score": 0.9997406005859375,
"start": 509,
"tag": "USERNAME",
"value": "moqada"
},
{
"context": "WS Secret Key for Billing\n#\n# Author:\n# m... | src/scripts/kanjo.coffee | moqada/hubot-kanjo | 1 | # Description
# Summarize AWS Billing for Hubot.
#
# Commands:
# hubot kanjo - Show AWS Billing of current month
# hubot kanjo <YYYYMM> - Show AWS Billing of target month
#
# Configuration:
# HUBOT_KANJO_AWS_ACCOUNT_ID - AWS Account ID for Billing
# HUBOT_KANJO_AWS_ACCESS_KEY_ID - AWS Access Key ID for Billing
# HUBOT_KANJO_AWS_BUCKET_NAME - S3 Bucket name for Billing
# HUBOT_KANJO_AWS_REGION - Region for S3 Bucket
# HUBOT_KANJO_AWS_SECRET_KEY - AWS Secret Key for Billing
#
# Author:
# moqada <moqada@gmail.com>
Kanjo = require 'kanjo'
Table = require 'cli-table'
roundTo = require 'round-to'
PREFIX = 'HUBOT_KANJO_'
AWS_ACCOUNT_ID = process.env["#{PREFIX}AWS_ACCOUNT_ID"]
AWS_ACCESS_KEY_ID = process.env["#{PREFIX}AWS_ACCESS_KEY_ID"]
AWS_BUCKET_NAME = process.env["#{PREFIX}AWS_BUCKET_NAME"]
AWS_REGION = process.env["#{PREFIX}AWS_REGION"]
AWS_SECRET_KEY = process.env["#{PREFIX}AWS_SECRET_KEY"]
module.exports = (robot) ->
robot.respond /kanjo(?:\s+(?:(\d{4})(0[1-9]|1[0-2])))?$/i, (res) ->
[year, month] = res.match.slice(1)
kanjo = new Kanjo({
account: AWS_ACCOUNT_ID
bucket: AWS_BUCKET_NAME
region: AWS_REGION
accessKeyId: AWS_ACCESS_KEY_ID
secretAccessKey: AWS_SECRET_KEY
})
if year and month
year = parseInt year, 10
month = parseInt month, 10
else
now = new Date()
year = now.getFullYear()
month = now.getMonth() + 1
kanjo.fetch(year, month).then (report) ->
output = """
#{year}/#{month}
#{outputTable report}
"""
res.send output
.catch (err) ->
console.error err
res.send "Error: #{err}"
outputTable = (report) ->
head = ['', 'Consolidated'].concat(report.accounts.map (b) -> b.accountName)
table = new Table({
head: head
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:
compact: true
'padding-right': 1
'padding-left': 0
head: ['gray']
colAligns: head.map -> 'right'
})
rows = report.total.sortedProducts.map (charge) ->
code = charge.code
costs = report.accounts.map (b) ->
if b.products[code] then b.products[code] else ''
costs = [charge.cost].concat costs
ret = {}
ret[charge.shortCode] = costs.map round
ret
totalCosts = [report.total.totalCost].concat(report.accounts.map (b) -> b.totalCost)
head = {}
head.Total = totalCosts.map(round)
[head].concat(rows).forEach (row) -> table.push row
return table.toString()
round = (num) ->
if typeof num is 'number'
return roundTo num, 2
return num
| 18429 | # Description
# Summarize AWS Billing for Hubot.
#
# Commands:
# hubot kanjo - Show AWS Billing of current month
# hubot kanjo <YYYYMM> - Show AWS Billing of target month
#
# Configuration:
# HUBOT_KANJO_AWS_ACCOUNT_ID - AWS Account ID for Billing
# HUBOT_KANJO_AWS_ACCESS_KEY_ID - AWS Access Key ID for Billing
# HUBOT_KANJO_AWS_BUCKET_NAME - S3 Bucket name for Billing
# HUBOT_KANJO_AWS_REGION - Region for S3 Bucket
# HUBOT_KANJO_AWS_SECRET_KEY - AWS Secret Key for Billing
#
# Author:
# moqada <<EMAIL>>
Kanjo = require 'kanjo'
Table = require 'cli-table'
roundTo = require 'round-to'
PREFIX = 'HUBOT_KANJO_'
AWS_ACCOUNT_ID = process.env["#{PREFIX}AWS_ACCOUNT_ID"]
AWS_ACCESS_KEY_ID = process.env["#{PREFIX}AWS_ACCESS_KEY_ID"]
AWS_BUCKET_NAME = process.env["#{PREFIX}AWS_BUCKET_NAME"]
AWS_REGION = process.env["#{PREFIX}AWS_REGION"]
AWS_SECRET_KEY = process.env["#{PREFIX}AWS_SECRET_KEY"]
module.exports = (robot) ->
robot.respond /kanjo(?:\s+(?:(\d{4})(0[1-9]|1[0-2])))?$/i, (res) ->
[year, month] = res.match.slice(1)
kanjo = new Kanjo({
account: AWS_ACCOUNT_ID
bucket: AWS_BUCKET_NAME
region: AWS_REGION
accessKeyId: AWS_ACCESS_KEY_ID
secretAccessKey: AWS_SECRET_KEY
})
if year and month
year = parseInt year, 10
month = parseInt month, 10
else
now = new Date()
year = now.getFullYear()
month = now.getMonth() + 1
kanjo.fetch(year, month).then (report) ->
output = """
#{year}/#{month}
#{outputTable report}
"""
res.send output
.catch (err) ->
console.error err
res.send "Error: #{err}"
outputTable = (report) ->
head = ['', 'Consolidated'].concat(report.accounts.map (b) -> b.accountName)
table = new Table({
head: head
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:
compact: true
'padding-right': 1
'padding-left': 0
head: ['gray']
colAligns: head.map -> 'right'
})
rows = report.total.sortedProducts.map (charge) ->
code = charge.code
costs = report.accounts.map (b) ->
if b.products[code] then b.products[code] else ''
costs = [charge.cost].concat costs
ret = {}
ret[charge.shortCode] = costs.map round
ret
totalCosts = [report.total.totalCost].concat(report.accounts.map (b) -> b.totalCost)
head = {}
head.Total = totalCosts.map(round)
[head].concat(rows).forEach (row) -> table.push row
return table.toString()
round = (num) ->
if typeof num is 'number'
return roundTo num, 2
return num
| true | # Description
# Summarize AWS Billing for Hubot.
#
# Commands:
# hubot kanjo - Show AWS Billing of current month
# hubot kanjo <YYYYMM> - Show AWS Billing of target month
#
# Configuration:
# HUBOT_KANJO_AWS_ACCOUNT_ID - AWS Account ID for Billing
# HUBOT_KANJO_AWS_ACCESS_KEY_ID - AWS Access Key ID for Billing
# HUBOT_KANJO_AWS_BUCKET_NAME - S3 Bucket name for Billing
# HUBOT_KANJO_AWS_REGION - Region for S3 Bucket
# HUBOT_KANJO_AWS_SECRET_KEY - AWS Secret Key for Billing
#
# Author:
# moqada <PI:EMAIL:<EMAIL>END_PI>
Kanjo = require 'kanjo'
Table = require 'cli-table'
roundTo = require 'round-to'
PREFIX = 'HUBOT_KANJO_'
AWS_ACCOUNT_ID = process.env["#{PREFIX}AWS_ACCOUNT_ID"]
AWS_ACCESS_KEY_ID = process.env["#{PREFIX}AWS_ACCESS_KEY_ID"]
AWS_BUCKET_NAME = process.env["#{PREFIX}AWS_BUCKET_NAME"]
AWS_REGION = process.env["#{PREFIX}AWS_REGION"]
AWS_SECRET_KEY = process.env["#{PREFIX}AWS_SECRET_KEY"]
module.exports = (robot) ->
robot.respond /kanjo(?:\s+(?:(\d{4})(0[1-9]|1[0-2])))?$/i, (res) ->
[year, month] = res.match.slice(1)
kanjo = new Kanjo({
account: AWS_ACCOUNT_ID
bucket: AWS_BUCKET_NAME
region: AWS_REGION
accessKeyId: AWS_ACCESS_KEY_ID
secretAccessKey: AWS_SECRET_KEY
})
if year and month
year = parseInt year, 10
month = parseInt month, 10
else
now = new Date()
year = now.getFullYear()
month = now.getMonth() + 1
kanjo.fetch(year, month).then (report) ->
output = """
#{year}/#{month}
#{outputTable report}
"""
res.send output
.catch (err) ->
console.error err
res.send "Error: #{err}"
outputTable = (report) ->
head = ['', 'Consolidated'].concat(report.accounts.map (b) -> b.accountName)
table = new Table({
head: head
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:
compact: true
'padding-right': 1
'padding-left': 0
head: ['gray']
colAligns: head.map -> 'right'
})
rows = report.total.sortedProducts.map (charge) ->
code = charge.code
costs = report.accounts.map (b) ->
if b.products[code] then b.products[code] else ''
costs = [charge.cost].concat costs
ret = {}
ret[charge.shortCode] = costs.map round
ret
totalCosts = [report.total.totalCost].concat(report.accounts.map (b) -> b.totalCost)
head = {}
head.Total = totalCosts.map(round)
[head].concat(rows).forEach (row) -> table.push row
return table.toString()
round = (num) ->
if typeof num is 'number'
return roundTo num, 2
return num
|
[
{
"context": "# Default password is null\n passwd: process.env.SYNO_PASSWORD\n # Default protocol is HTTP (",
"end": 434,
"score": 0.8215766549110413,
"start": 431,
"tag": "PASSWORD",
"value": "env"
},
{
"context": "if @debug\n console.log \"[DEBUG] : Password: #... | src/syno/Syno.coffee | weshouman/syno | 252 | # Require node modules
request = require 'request'
fs = require 'fs'
path = require 'path'
{defaults, mapValues, keys, values, flatten, filter,
first, last, some, merge, isArray, startsWith, endsWith} = require 'lodash'
# Class Syno
class Syno
# Default synology parameters
defParams =
# Default account is null
account: process.env.SYNO_ACCOUNT
# Default password is null
passwd: process.env.SYNO_PASSWORD
# Default protocol is HTTP (`http`)
protocol: process.env.SYNO_PROTOCOL or 'http'
# Default host is `localhost`
host: process.env.SYNO_HOST or 'localhost'
# Default port is `5000`
port: process.env.SYNO_PORT or 5000
# Default api version is `6.2.2`
apiVersion: process.env.SYNO_API_VERSION or '6.2.2'
# Default debug flag is `false`
debug: process.env.SYNO_DEBUG or false
# Default ignore certificate errors
ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or false
apiVersionsAvailable = ['5.0', '5.1', '5.2',
'6.0', '6.0.1', '6.0.2', '6.0.3',
'6.1', '6.1.1', '6.1.2', '6.1.3', '6.1.4', '6.1.5', '6.1.6', '6.1.7',
'6.2', '6.2.1', '6.2.2']
# Constructor for the Syno class
# `params` [Object]
# `params.account` [String] Account for the syno instance. * Required *
# `params.passwd` [String] Password for the account. * Required *
# `params.protocol` [String] Protocol for the syno requests.
# `params.host` [String] Host of the syno.
# `params.port` [String] Port for the syno requests.
# `params.apiVersion` [String] DSM api version.
constructor: (params)->
# Use defaults options
defaults this, params, defParams
# Debug mode
console.log "[DEBUG] : Account: #{@account}" if @debug
console.log "[DEBUG] : Password: #{@passwd}" if @debug
console.log "[DEBUG] : Host: #{@host}" if @debug
console.log "[DEBUG] : Port: #{@port}" if @debug
console.log "[DEBUG] : API: #{@apiVersion}" if @debug
console.log "[DEBUG] : Ignore certificate errors: #{@ignoreCertificateErrors}" if @debug
# Throw errors if required params are not passed
if not @account then throw new Error 'Did not specified `account` for syno'
if not @passwd then throw new Error 'Did not specified `passwd` for syno'
if not (new RegExp(apiVersionsAvailable.join('|')).test(@apiVersion))
then throw new Error "Api version: #{@apiVersion} is not available.
Available versions are: #{apiVersionsAvailable.join(', ')}"
# Create request with jar
@request = request.defaults rejectUnauthorized: not @ignoreCertificateErrors, json: true
request.debug = true if @debug
# Init session property
@session = null
# Add auth API
@auth = new Auth this
# Add DSM API
@dsm = @diskStationManager = new DSM this
# Add FileStation API
@fs = @fileStation = new FileStation this
# Add Download Station API
@dl = @downloadStation = new DownloadStation this
# Add Audio Station API
@as = @audioStation = new AudioStation this
# Add Video Station API
@vs = @videoStation = new VideoStation this
# Add Video Station DTV API
@dtv = @videoStationDTV = new VideoStationDTV this
# Add Surveillance Station API
@ss = @surveillanceStation = new SurveillanceStation this
loadDefinitions: ->
return @definitions if @definitions
majorVersion = "#{@apiVersion.charAt(0)}.x"
file_path = path.join(__dirname, "../definitions/#{majorVersion}/_full.json")
@definitions = JSON.parse(fs.readFileSync file_path, 'utf8')
return @definitions
createFunctionsFor: (object, apis) ->
definitions = this.loadDefinitions()
for api in apis
apiKeys = filter(keys(definitions), (key) -> startsWith(key, api))
for api in apiKeys
if definitions[api].methods
lastApiVersionMethods = definitions[api].methods[last(keys(definitions[api].methods))]
if not some(lastApiVersionMethods, (m) -> typeof(m) is 'string')
lastApiVersionMethods =
flatten(values(mapValues(lastApiVersionMethods, (m) -> keys(m))))
for method in lastApiVersionMethods
method = first(keys(method)) if typeof(method) is 'object'
functionName = Utils.createFunctionName(api, method)
path = if 'path' of definitions[api] then definitions[api].path else 'entry.cgi'
version = if 'maxVersion' of definitions[api] then definitions[api].maxVersion else 1
object.__proto__[functionName] = new Function('params', 'done', '
this.requestAPI({
params: params,
done: done,
apiInfos: {
sessionName: ' + "'" + object.sessionName + "'" + ',
api: ' + "'" + api + "'" + ',
version:' + "'" + version + "'" + ',
path: ' + "'" + path + "'" + ',
method: ' + "'" + method + "'" + '
}
});')
| 116424 | # Require node modules
request = require 'request'
fs = require 'fs'
path = require 'path'
{defaults, mapValues, keys, values, flatten, filter,
first, last, some, merge, isArray, startsWith, endsWith} = require 'lodash'
# Class Syno
class Syno
# Default synology parameters
defParams =
# Default account is null
account: process.env.SYNO_ACCOUNT
# Default password is null
passwd: process.<PASSWORD>.SYNO_PASSWORD
# Default protocol is HTTP (`http`)
protocol: process.env.SYNO_PROTOCOL or 'http'
# Default host is `localhost`
host: process.env.SYNO_HOST or 'localhost'
# Default port is `5000`
port: process.env.SYNO_PORT or 5000
# Default api version is `6.2.2`
apiVersion: process.env.SYNO_API_VERSION or '6.2.2'
# Default debug flag is `false`
debug: process.env.SYNO_DEBUG or false
# Default ignore certificate errors
ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or false
apiVersionsAvailable = ['5.0', '5.1', '5.2',
'6.0', '6.0.1', '6.0.2', '6.0.3',
'6.1', '6.1.1', '6.1.2', '6.1.3', '6.1.4', '6.1.5', '6.1.6', '6.1.7',
'6.2', '6.2.1', '6.2.2']
# Constructor for the Syno class
# `params` [Object]
# `params.account` [String] Account for the syno instance. * Required *
# `params.passwd` [String] Password for the account. * Required *
# `params.protocol` [String] Protocol for the syno requests.
# `params.host` [String] Host of the syno.
# `params.port` [String] Port for the syno requests.
# `params.apiVersion` [String] DSM api version.
constructor: (params)->
# Use defaults options
defaults this, params, defParams
# Debug mode
console.log "[DEBUG] : Account: #{@account}" if @debug
console.log "[DEBUG] : Password: <PASSWORD>}" if @debug
console.log "[DEBUG] : Host: #{@host}" if @debug
console.log "[DEBUG] : Port: #{@port}" if @debug
console.log "[DEBUG] : API: #{@apiVersion}" if @debug
console.log "[DEBUG] : Ignore certificate errors: #{@ignoreCertificateErrors}" if @debug
# Throw errors if required params are not passed
if not @account then throw new Error 'Did not specified `account` for syno'
if not @passwd then throw new Error 'Did not specified `passwd` for syno'
if not (new RegExp(apiVersionsAvailable.join('|')).test(@apiVersion))
then throw new Error "Api version: #{@apiVersion} is not available.
Available versions are: #{apiVersionsAvailable.join(', ')}"
# Create request with jar
@request = request.defaults rejectUnauthorized: not @ignoreCertificateErrors, json: true
request.debug = true if @debug
# Init session property
@session = null
# Add auth API
@auth = new Auth this
# Add DSM API
@dsm = @diskStationManager = new DSM this
# Add FileStation API
@fs = @fileStation = new FileStation this
# Add Download Station API
@dl = @downloadStation = new DownloadStation this
# Add Audio Station API
@as = @audioStation = new AudioStation this
# Add Video Station API
@vs = @videoStation = new VideoStation this
# Add Video Station DTV API
@dtv = @videoStationDTV = new VideoStationDTV this
# Add Surveillance Station API
@ss = @surveillanceStation = new SurveillanceStation this
loadDefinitions: ->
return @definitions if @definitions
majorVersion = "#{@apiVersion.charAt(0)}.x"
file_path = path.join(__dirname, "../definitions/#{majorVersion}/_full.json")
@definitions = JSON.parse(fs.readFileSync file_path, 'utf8')
return @definitions
createFunctionsFor: (object, apis) ->
definitions = this.loadDefinitions()
for api in apis
apiKeys = filter(keys(definitions), (key) -> startsWith(key, api))
for api in apiKeys
if definitions[api].methods
lastApiVersionMethods = definitions[api].methods[last(keys(definitions[api].methods))]
if not some(lastApiVersionMethods, (m) -> typeof(m) is 'string')
lastApiVersionMethods =
flatten(values(mapValues(lastApiVersionMethods, (m) -> keys(m))))
for method in lastApiVersionMethods
method = first(keys(method)) if typeof(method) is 'object'
functionName = Utils.createFunctionName(api, method)
path = if 'path' of definitions[api] then definitions[api].path else 'entry.cgi'
version = if 'maxVersion' of definitions[api] then definitions[api].maxVersion else 1
object.__proto__[functionName] = new Function('params', 'done', '
this.requestAPI({
params: params,
done: done,
apiInfos: {
sessionName: ' + "'" + object.sessionName + "'" + ',
api: ' + "'" + api + "'" + ',
version:' + "'" + version + "'" + ',
path: ' + "'" + path + "'" + ',
method: ' + "'" + method + "'" + '
}
});')
| true | # Require node modules
request = require 'request'
fs = require 'fs'
path = require 'path'
{defaults, mapValues, keys, values, flatten, filter,
first, last, some, merge, isArray, startsWith, endsWith} = require 'lodash'
# Class Syno
class Syno
# Default synology parameters
defParams =
# Default account is null
account: process.env.SYNO_ACCOUNT
# Default password is null
passwd: process.PI:PASSWORD:<PASSWORD>END_PI.SYNO_PASSWORD
# Default protocol is HTTP (`http`)
protocol: process.env.SYNO_PROTOCOL or 'http'
# Default host is `localhost`
host: process.env.SYNO_HOST or 'localhost'
# Default port is `5000`
port: process.env.SYNO_PORT or 5000
# Default api version is `6.2.2`
apiVersion: process.env.SYNO_API_VERSION or '6.2.2'
# Default debug flag is `false`
debug: process.env.SYNO_DEBUG or false
# Default ignore certificate errors
ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or false
apiVersionsAvailable = ['5.0', '5.1', '5.2',
'6.0', '6.0.1', '6.0.2', '6.0.3',
'6.1', '6.1.1', '6.1.2', '6.1.3', '6.1.4', '6.1.5', '6.1.6', '6.1.7',
'6.2', '6.2.1', '6.2.2']
# Constructor for the Syno class
# `params` [Object]
# `params.account` [String] Account for the syno instance. * Required *
# `params.passwd` [String] Password for the account. * Required *
# `params.protocol` [String] Protocol for the syno requests.
# `params.host` [String] Host of the syno.
# `params.port` [String] Port for the syno requests.
# `params.apiVersion` [String] DSM api version.
constructor: (params)->
# Use defaults options
defaults this, params, defParams
# Debug mode
console.log "[DEBUG] : Account: #{@account}" if @debug
console.log "[DEBUG] : Password: PI:PASSWORD:<PASSWORD>END_PI}" if @debug
console.log "[DEBUG] : Host: #{@host}" if @debug
console.log "[DEBUG] : Port: #{@port}" if @debug
console.log "[DEBUG] : API: #{@apiVersion}" if @debug
console.log "[DEBUG] : Ignore certificate errors: #{@ignoreCertificateErrors}" if @debug
# Throw errors if required params are not passed
if not @account then throw new Error 'Did not specified `account` for syno'
if not @passwd then throw new Error 'Did not specified `passwd` for syno'
if not (new RegExp(apiVersionsAvailable.join('|')).test(@apiVersion))
then throw new Error "Api version: #{@apiVersion} is not available.
Available versions are: #{apiVersionsAvailable.join(', ')}"
# Create request with jar
@request = request.defaults rejectUnauthorized: not @ignoreCertificateErrors, json: true
request.debug = true if @debug
# Init session property
@session = null
# Add auth API
@auth = new Auth this
# Add DSM API
@dsm = @diskStationManager = new DSM this
# Add FileStation API
@fs = @fileStation = new FileStation this
# Add Download Station API
@dl = @downloadStation = new DownloadStation this
# Add Audio Station API
@as = @audioStation = new AudioStation this
# Add Video Station API
@vs = @videoStation = new VideoStation this
# Add Video Station DTV API
@dtv = @videoStationDTV = new VideoStationDTV this
# Add Surveillance Station API
@ss = @surveillanceStation = new SurveillanceStation this
loadDefinitions: ->
return @definitions if @definitions
majorVersion = "#{@apiVersion.charAt(0)}.x"
file_path = path.join(__dirname, "../definitions/#{majorVersion}/_full.json")
@definitions = JSON.parse(fs.readFileSync file_path, 'utf8')
return @definitions
createFunctionsFor: (object, apis) ->
definitions = this.loadDefinitions()
for api in apis
apiKeys = filter(keys(definitions), (key) -> startsWith(key, api))
for api in apiKeys
if definitions[api].methods
lastApiVersionMethods = definitions[api].methods[last(keys(definitions[api].methods))]
if not some(lastApiVersionMethods, (m) -> typeof(m) is 'string')
lastApiVersionMethods =
flatten(values(mapValues(lastApiVersionMethods, (m) -> keys(m))))
for method in lastApiVersionMethods
method = first(keys(method)) if typeof(method) is 'object'
functionName = Utils.createFunctionName(api, method)
path = if 'path' of definitions[api] then definitions[api].path else 'entry.cgi'
version = if 'maxVersion' of definitions[api] then definitions[api].maxVersion else 1
object.__proto__[functionName] = new Function('params', 'done', '
this.requestAPI({
params: params,
done: done,
apiInfos: {
sessionName: ' + "'" + object.sessionName + "'" + ',
api: ' + "'" + api + "'" + ',
version:' + "'" + version + "'" + ',
path: ' + "'" + path + "'" + ',
method: ' + "'" + method + "'" + '
}
});')
|
[
{
"context": "ject\", ->\n assert objects.get('name', { name: \"John\" }) == \"John\"\n\n it \"can be partially applied\", -",
"end": 174,
"score": 0.9995059370994568,
"start": 170,
"tag": "NAME",
"value": "John"
},
{
"context": " assert objects.get('name', { name: \"John\" }) ==... | test/objects.coffee | ianthehenry/effing | 5 | objects = require 'effing/objects'
{ assert } = require 'chai'
describe "objects.get", ->
it "looks up a key on an object", ->
assert objects.get('name', { name: "John" }) == "John"
it "can be partially applied", ->
getName = objects.get 'name'
assert getName(name: "Mary") == "Mary"
describe "objects.lookup", ->
it "looks up a key on an object", ->
assert objects.lookup({ name: "John" }, 'name') == "John"
it "can be partially applied", ->
mary =
name: "Mary"
age: 25
investigateMary = objects.lookup mary
assert investigateMary('name') == "Mary"
assert investigateMary('age') == 25
describe "objects.set", ->
it "sets a key on an object", ->
person = {}
objects.set('name', person, "John")
assert person.name == "John"
it "allows the key to be partially applied", ->
person = {}
setName = objects.set('name')
setName(person, "Mary")
assert person.name == "Mary"
it "allows the object to be partially applied", ->
person = {}
setPersonName = objects.set('name', person)
setPersonName("John")
assert person.name == "John"
it "returns the value that it sets", ->
person = {}
assert objects.set('name', person, "John") == "John"
describe "objects.method", ->
it "invokes a method on an object", ->
assert objects.method('foo')({ foo: -> 5 }) == 5
it "preserves the context", ->
person =
name: "John"
getName: -> @name
assert objects.method('getName')(person) == "John"
it "forwards any supplied arguments", ->
person =
age: 18
ageInTheFuture: (years) -> @age + years
assert objects.method('ageInTheFuture', 10)(person) == 28
it "forwards arguments after being partially applied", ->
person =
age: 18
addAge: (x) -> @age + x
ageAdder = objects.method('addAge')
assert ageAdder(person, 10) == 28
| 177297 | objects = require 'effing/objects'
{ assert } = require 'chai'
describe "objects.get", ->
it "looks up a key on an object", ->
assert objects.get('name', { name: "<NAME>" }) == "<NAME>"
it "can be partially applied", ->
getName = objects.get 'name'
assert getName(name: "<NAME>") == "<NAME>"
describe "objects.lookup", ->
it "looks up a key on an object", ->
assert objects.lookup({ name: "<NAME>" }, 'name') == "<NAME>"
it "can be partially applied", ->
mary =
name: "<NAME>"
age: 25
investigateMary = objects.lookup mary
assert investigateMary('name') == "<NAME>"
assert investigateMary('age') == 25
describe "objects.set", ->
it "sets a key on an object", ->
person = {}
objects.set('name', person, "<NAME>")
assert person.name == "<NAME>"
it "allows the key to be partially applied", ->
person = {}
setName = objects.set('name')
setName(person, "<NAME>")
assert person.name == "<NAME>"
it "allows the object to be partially applied", ->
person = {}
setPersonName = objects.set('name', person)
setPersonName("<NAME>")
assert person.name == "<NAME>"
it "returns the value that it sets", ->
person = {}
assert objects.set('name', person, "<NAME>") == "<NAME>"
describe "objects.method", ->
it "invokes a method on an object", ->
assert objects.method('foo')({ foo: -> 5 }) == 5
it "preserves the context", ->
person =
name: "<NAME>"
getName: -> @name
assert objects.method('getName')(person) == "John"
it "forwards any supplied arguments", ->
person =
age: 18
ageInTheFuture: (years) -> @age + years
assert objects.method('ageInTheFuture', 10)(person) == 28
it "forwards arguments after being partially applied", ->
person =
age: 18
addAge: (x) -> @age + x
ageAdder = objects.method('addAge')
assert ageAdder(person, 10) == 28
| true | objects = require 'effing/objects'
{ assert } = require 'chai'
describe "objects.get", ->
it "looks up a key on an object", ->
assert objects.get('name', { name: "PI:NAME:<NAME>END_PI" }) == "PI:NAME:<NAME>END_PI"
it "can be partially applied", ->
getName = objects.get 'name'
assert getName(name: "PI:NAME:<NAME>END_PI") == "PI:NAME:<NAME>END_PI"
describe "objects.lookup", ->
it "looks up a key on an object", ->
assert objects.lookup({ name: "PI:NAME:<NAME>END_PI" }, 'name') == "PI:NAME:<NAME>END_PI"
it "can be partially applied", ->
mary =
name: "PI:NAME:<NAME>END_PI"
age: 25
investigateMary = objects.lookup mary
assert investigateMary('name') == "PI:NAME:<NAME>END_PI"
assert investigateMary('age') == 25
describe "objects.set", ->
it "sets a key on an object", ->
person = {}
objects.set('name', person, "PI:NAME:<NAME>END_PI")
assert person.name == "PI:NAME:<NAME>END_PI"
it "allows the key to be partially applied", ->
person = {}
setName = objects.set('name')
setName(person, "PI:NAME:<NAME>END_PI")
assert person.name == "PI:NAME:<NAME>END_PI"
it "allows the object to be partially applied", ->
person = {}
setPersonName = objects.set('name', person)
setPersonName("PI:NAME:<NAME>END_PI")
assert person.name == "PI:NAME:<NAME>END_PI"
it "returns the value that it sets", ->
person = {}
assert objects.set('name', person, "PI:NAME:<NAME>END_PI") == "PI:NAME:<NAME>END_PI"
describe "objects.method", ->
it "invokes a method on an object", ->
assert objects.method('foo')({ foo: -> 5 }) == 5
it "preserves the context", ->
person =
name: "PI:NAME:<NAME>END_PI"
getName: -> @name
assert objects.method('getName')(person) == "John"
it "forwards any supplied arguments", ->
person =
age: 18
ageInTheFuture: (years) -> @age + years
assert objects.method('ageInTheFuture', 10)(person) == 28
it "forwards arguments after being partially applied", ->
person =
age: 18
addAge: (x) -> @age + x
ageAdder = objects.method('addAge')
assert ageAdder(person, 10) == 28
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.