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": "BEST_KEY = 'score:best'\n\nclass Score\n constructor: ->\n @last = 0\n ", "end": 22, "score": 0.8670603632926941, "start": 12, "tag": "KEY", "value": "score:best" } ]
src/models/score.coffee
kkmonlee/Link
0
BEST_KEY = 'score:best' class Score constructor: -> @last = 0 try @best = if localStorage[BEST_KEY] then \ parseInt(localStorage[BEST_KEY]) \ else 0 catch e console.log e save: (score) => @last = score if score > @best @setBest(score) getLast: (score) => @last setBest: (score) => @best = score try localStorage[BEST_KEY] = score catch e console.log e getBest: -> @best module.exports = new Score()
151744
BEST_KEY = '<KEY>' class Score constructor: -> @last = 0 try @best = if localStorage[BEST_KEY] then \ parseInt(localStorage[BEST_KEY]) \ else 0 catch e console.log e save: (score) => @last = score if score > @best @setBest(score) getLast: (score) => @last setBest: (score) => @best = score try localStorage[BEST_KEY] = score catch e console.log e getBest: -> @best module.exports = new Score()
true
BEST_KEY = 'PI:KEY:<KEY>END_PI' class Score constructor: -> @last = 0 try @best = if localStorage[BEST_KEY] then \ parseInt(localStorage[BEST_KEY]) \ else 0 catch e console.log e save: (score) => @last = score if score > @best @setBest(score) getLast: (score) => @last setBest: (score) => @best = score try localStorage[BEST_KEY] = score catch e console.log e getBest: -> @best module.exports = new Score()
[ { "context": "await baseClient.getSecret(label)\n key = utl.strip0x(key)\n client = await clientFactory.createC", "end": 1256, "score": 0.8441166877746582, "start": 1247, "tag": "KEY", "value": "l.strip0x" } ]
source/autodetectkeysmodule/autodetectkeysmodule.coffee
JhonnyJason/secret-cockpit-sources
0
autodetectkeysmodule = {name: "autodetectkeysmodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["autodetectkeysmodule"]? then console.log "[autodetectkeysmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null aliasModule = null clientStore = null baseClient = null #endregion ############################################################ autodetectkeysmodule.initialize = -> log "autodetectkeysmodule.initialize" utl = allModules.utilmodule state = allModules.statemodule aliasModule = allModules.idaliasmodule clientStore = allModules.clientstoremodule return ############################################################ importKeyForLabel = (label) -> log "importKeyForLabel" url = state.get("secretManagerURL") try key = await baseClient.getSecret(label) key = utl.strip0x(key) client = await clientFactory.createClient(key, null, url) clientStore.storeNewClient(client, "unsafe") ## Managing potential alias identifyingEnding = state.get("secretIdentifyingEnding") id = client.publicKeyHex alias = label.slice(0, -identifyingEnding.length) log alias if !aliasModule.aliasFrom(id)? and !aliasModule.idFrom(alias) aliasModule.updateAlias(alias, id) catch err then log err return ############################################################ autodetectkeysmodule.detectFor = (client) -> log "autodetectkeysmodule.detectFor" return unless state.get("autodetectStoredSecrets") try baseClient = client identifyingEnding = state.get("secretIdentifyingEnding") space = await client.getSecretSpace() labels = Object.keys(space) log labels keyLabels = labels.filter((str) -> str.endsWith(identifyingEnding)) log keyLabels promises = (importKeyForLabel(label) for label in keyLabels) await Promise.all(promises) catch err log err return module.exports = autodetectkeysmodule
67631
autodetectkeysmodule = {name: "autodetectkeysmodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["autodetectkeysmodule"]? then console.log "[autodetectkeysmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null aliasModule = null clientStore = null baseClient = null #endregion ############################################################ autodetectkeysmodule.initialize = -> log "autodetectkeysmodule.initialize" utl = allModules.utilmodule state = allModules.statemodule aliasModule = allModules.idaliasmodule clientStore = allModules.clientstoremodule return ############################################################ importKeyForLabel = (label) -> log "importKeyForLabel" url = state.get("secretManagerURL") try key = await baseClient.getSecret(label) key = ut<KEY>(key) client = await clientFactory.createClient(key, null, url) clientStore.storeNewClient(client, "unsafe") ## Managing potential alias identifyingEnding = state.get("secretIdentifyingEnding") id = client.publicKeyHex alias = label.slice(0, -identifyingEnding.length) log alias if !aliasModule.aliasFrom(id)? and !aliasModule.idFrom(alias) aliasModule.updateAlias(alias, id) catch err then log err return ############################################################ autodetectkeysmodule.detectFor = (client) -> log "autodetectkeysmodule.detectFor" return unless state.get("autodetectStoredSecrets") try baseClient = client identifyingEnding = state.get("secretIdentifyingEnding") space = await client.getSecretSpace() labels = Object.keys(space) log labels keyLabels = labels.filter((str) -> str.endsWith(identifyingEnding)) log keyLabels promises = (importKeyForLabel(label) for label in keyLabels) await Promise.all(promises) catch err log err return module.exports = autodetectkeysmodule
true
autodetectkeysmodule = {name: "autodetectkeysmodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["autodetectkeysmodule"]? then console.log "[autodetectkeysmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null aliasModule = null clientStore = null baseClient = null #endregion ############################################################ autodetectkeysmodule.initialize = -> log "autodetectkeysmodule.initialize" utl = allModules.utilmodule state = allModules.statemodule aliasModule = allModules.idaliasmodule clientStore = allModules.clientstoremodule return ############################################################ importKeyForLabel = (label) -> log "importKeyForLabel" url = state.get("secretManagerURL") try key = await baseClient.getSecret(label) key = utPI:KEY:<KEY>END_PI(key) client = await clientFactory.createClient(key, null, url) clientStore.storeNewClient(client, "unsafe") ## Managing potential alias identifyingEnding = state.get("secretIdentifyingEnding") id = client.publicKeyHex alias = label.slice(0, -identifyingEnding.length) log alias if !aliasModule.aliasFrom(id)? and !aliasModule.idFrom(alias) aliasModule.updateAlias(alias, id) catch err then log err return ############################################################ autodetectkeysmodule.detectFor = (client) -> log "autodetectkeysmodule.detectFor" return unless state.get("autodetectStoredSecrets") try baseClient = client identifyingEnding = state.get("secretIdentifyingEnding") space = await client.getSecretSpace() labels = Object.keys(space) log labels keyLabels = labels.filter((str) -> str.endsWith(identifyingEnding)) log keyLabels promises = (importKeyForLabel(label) for label in keyLabels) await Promise.all(promises) catch err log err return module.exports = autodetectkeysmodule
[ { "context": "moscow rules - Prints Moscow Rules\n#\n# Author:\n# Scott J Roberts - @sroberts\n\nmoscow_rules = [\n \"Any operation ca", "end": 225, "score": 0.9998693466186523, "start": 210, "tag": "NAME", "value": "Scott J Roberts" }, { "context": "nts Moscow Rules\n#\n# Author:...
src/scripts/moscow-rules.coffee
3ch01c/hubot-vtr-scripts
47
# Description: # Give some information on following Moscow Rules # # Dependencies: # None # # Configuration: # None # # Commands: # hubot what are the moscow rules - Prints Moscow Rules # # Author: # Scott J Roberts - @sroberts moscow_rules = [ "Any operation can be aborted. If it feels wrong, it is wrong.", "Assume nothing.", "Build in opportunity, but use it sparingly.", "Don't harass the opposition.", "Don't look back; you are never completely alone.", "Everyone is potentially under opposition control.", "Float like a butterfly, sting like a bee.", "Go with the flow, blend in.", "Keep your options open.", "Lull them into a sense of complacency.", "Maintain a natural pace.", "Murphy is right.", "Never go against your gut; it is your operational antenna.", "Pick the time and place for action.", "There is no limit to a human being's ability to rationalize the truth.", "Vary your pattern and stay within your cover.", "Once is an accident. Twice is coincidence. Three times is an enemy action." ] module.exports = (robot) -> robot.respond /what are the moscow rules/i, (msg) -> msg.send "The Moscow Rules: " msg.send "- " + rule for rule in moscow_rules robot.respond /moscow rule/i, (msg) -> phrase = msg.random moscow_rules msg.send "Always remember: " + phrase
137657
# Description: # Give some information on following Moscow Rules # # Dependencies: # None # # Configuration: # None # # Commands: # hubot what are the moscow rules - Prints Moscow Rules # # Author: # <NAME> - @sroberts moscow_rules = [ "Any operation can be aborted. If it feels wrong, it is wrong.", "Assume nothing.", "Build in opportunity, but use it sparingly.", "Don't harass the opposition.", "Don't look back; you are never completely alone.", "Everyone is potentially under opposition control.", "Float like a butterfly, sting like a bee.", "Go with the flow, blend in.", "Keep your options open.", "Lull them into a sense of complacency.", "Maintain a natural pace.", "Murphy is right.", "Never go against your gut; it is your operational antenna.", "Pick the time and place for action.", "There is no limit to a human being's ability to rationalize the truth.", "Vary your pattern and stay within your cover.", "Once is an accident. Twice is coincidence. Three times is an enemy action." ] module.exports = (robot) -> robot.respond /what are the moscow rules/i, (msg) -> msg.send "The Moscow Rules: " msg.send "- " + rule for rule in moscow_rules robot.respond /moscow rule/i, (msg) -> phrase = msg.random moscow_rules msg.send "Always remember: " + phrase
true
# Description: # Give some information on following Moscow Rules # # Dependencies: # None # # Configuration: # None # # Commands: # hubot what are the moscow rules - Prints Moscow Rules # # Author: # PI:NAME:<NAME>END_PI - @sroberts moscow_rules = [ "Any operation can be aborted. If it feels wrong, it is wrong.", "Assume nothing.", "Build in opportunity, but use it sparingly.", "Don't harass the opposition.", "Don't look back; you are never completely alone.", "Everyone is potentially under opposition control.", "Float like a butterfly, sting like a bee.", "Go with the flow, blend in.", "Keep your options open.", "Lull them into a sense of complacency.", "Maintain a natural pace.", "Murphy is right.", "Never go against your gut; it is your operational antenna.", "Pick the time and place for action.", "There is no limit to a human being's ability to rationalize the truth.", "Vary your pattern and stay within your cover.", "Once is an accident. Twice is coincidence. Three times is an enemy action." ] module.exports = (robot) -> robot.respond /what are the moscow rules/i, (msg) -> msg.send "The Moscow Rules: " msg.send "- " + rule for rule in moscow_rules robot.respond /moscow rule/i, (msg) -> phrase = msg.random moscow_rules msg.send "Always remember: " + phrase
[ { "context": " {\n name: 'Todo',\n renderer: 'stack',\n", "end": 17569, "score": 0.9348122477531433, "start": 17565, "tag": "NAME", "value": "Todo" }, { "context": "eTimeGraphTeam()\n InitializeAverageStoriesGraph(@...
app/assets/javascripts/teams.coffee
eddygarcas/vortrics
0
` function TimeToFirstResponse(data) { document.getElementById('bars-first-response-loader').innerHTML = ""; graph_f = new Rickshaw.Graph({ element: document.getElementById('bars-first-response'), height: 220, renderer: 'multi', series: [ { name: 'Time First Response', renderer: 'bar', color: '#90caf9', data: data[2] }, { name: 'Average First Time Response', renderer: 'line', color: '#d13b47', data: data[3] } ] }); var format = function (n) { if (data[1][n] === undefined) { return; } return data[1][n].y; } var legend = new Rickshaw.Graph.Legend({ graph: graph_f, element: document.getElementById('bars-first-response-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph_f, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph_f, legend: legend }) new Rickshaw.Graph.ClickDetail({ graph: graph_f, clickHandler: function (value) { window.open('/issues/key/' + $(".key_bug_sprint").text(), "_self") } }); new Rickshaw.Graph.Axis.X({ graph: graph_f, orientation: 'bottom', element: document.getElementById('bars-first-response-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-first-response-y_axis1'), graph: graph_f, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph_f.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_bug_sprint").text(); }, graph: graph_f, formatter: function (series, x, y) { var sprint = '<span class="date key_bug_sprint">' + data[0][x].y + '</span><span class="date"> created on ' + data[1][x].y + '</span>'; var content = series.name + " " + parseInt(y) + ' Hours<br>' + sprint; if (series.name === 'Time First Response') return content; return content; } }); $(window).on('resize', function () { graph_f.configure({ width: $('#bars-first-response').parent('.panel-body').width(), height: 220 }); graph_f.render(); }); } function InitializeCycleTimeGraphTeam() { graph = new Rickshaw.Graph.Ajax({ element: document.getElementById('bars-cycle-time'), height: 220, renderer: 'multi', method: 'POST', dataURL: '/teams/' + $('#teamid')[0].value + '/cycle_time_chart', onData: function (data) { document.getElementById('bars-cycle-time-loader').innerHTML = ""; series = data[0]; min = Number.MAX_VALUE; max = Number.MIN_VALUE; for (_l = 0, _len2 = series.length; _l < _len2; _l++) { point = series[_l]; min = Math.min(min, point.y); max = Math.max(max, point.y); } var scale_x = d3.scale.linear().domain([min, max]); window.store.state.selector.mseries = [ { name: 'Tickets', renderer: 'bar', color: '#90caf9', data: data[0], scale: scale_x }, { name: 'Cumulative', renderer: 'line', color: '#d13b47', data: data[1], scale: d3.scale.linear().domain([0, 100]) } ]; return window.store.state.selector.mseries }, onComplete: function (transport) { graph = transport.graph; var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-cycle-time-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-cycle-time-x_axis'), pixelsPerTick: 100, tickFormat: function (x) { return x + ' days'; } }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis1'), graph: graph, orientation: 'left', scale: window.store.state.selector.mseries[0].scale, pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis2'), graph: graph, grid: false, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: function (x) { return x + '%'; } }); graph.render(); new Rickshaw.Graph.HoverDetail({ graph: graph, formatter: function (series, x, y) { var content = 'Days: ' + x + '<br>'; window.store.state.selector.summary.days = x if (window.store.state.selector.mseries[0].data[x]) { window.store.state.selector.summary.tickets = window.store.state.selector.mseries[0].data[x].y content += '#Tickets: ' + window.store.state.selector.mseries[0].data[x].y + '<br>'; } if (window.store.state.selector.mseries[1].data[x]) { window.store.state.selector.summary.cumulative = window.store.state.selector.mseries[1].data[x].y content += 'Cumulative: ' + window.store.state.selector.mseries[1].data[x].y + '%'; } return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-cycle-time').parent('.container-fluid').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }); } function InitializeReleaseTimeBugsGraphTeam() { $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_lead_time_bugs', success: function (data) { if ($('#bars-team-release-bugs')[0] === undefined) { return; } else { document.getElementById('bars-team-release-bugs-loader').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById('bars-team-release-bugs'), height: 220, renderer: 'multi', series: [ { name: 'Waiting Time', renderer: 'bar', color: '#ff9642', data: data[1] }, { name: 'Working Time', renderer: 'bar', color: '#ffcc80', data: data[9] }, { name: 'Rolling Average', renderer: 'line', color: '#d13b47', data: data[8] } ] }); var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-team-release-bugs-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.ClickDetail({ graph: graph, clickHandler: function (value) { window.open('/issues/key/' + $(".key_team_bug").text(), "_self") } }); var format = function (n) { if (data[4][n] === undefined) { return; } return data[4][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-team-release-bugs-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-team-release-bugs-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[0][x].y + '</span><span class="date"> ' + data[7][x].y + ' ' + data[4][x].y + '</span>'; var flagged = ' <i class="fa fa-flag"></i>'; var bug = ' <i class="fa fa-bug"></i>'; var firsttime = ' <i class="fa fa-bolt"></i>'; var moreonesprint = ' <i class="fa fa-exclamation-triangle"></i>'; var content = series.name + ": " + parseInt(y) + ' days<br>' + sprint; if (data[2][x].y) content += flagged; if (data[3][x].y) content += firsttime; if (data[5][x].y) content += moreonesprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-team-release-bugs').parent('.panel-body').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }) } function InitializeOpenClosedBugsGraphTeam(id) { var _id = '' if (id === undefined) { _id = 'bars-team-openclosed-bugs' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_ratio_bugs_closed', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 220, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#ffcc80', data: data[1] }, { name: 'Open/Backlog', renderer: 'stack', color: '#ff9642', data: data[0] } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; } new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var content = series.name + ": " + parseInt(y) + ' Bugs<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 220 }); graph.render(); }); } }) } function InitializeComulativeFlowChart(id) { var _id = '' if (id === undefined) { _id = 'team-comulative-flow' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_comulative_flow_diagram', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var axis_scale = d3.scale.linear().domain([0, 100]); graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 440, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#0085f9', data: data[1], scale: axis_scale }, { name: 'In Progress', renderer: 'stack', color: '#90caf9', data: data[0], scale: axis_scale }, { name: 'Todo', renderer: 'stack', color: '#ffcc80', data: data[3], scale: axis_scale } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 50, tickFormat: format }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: axis_scale, pixelsPerTick: 15, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.RangeSlider.Preview({ graph: graph, element: document.querySelector("#rangeSlider") }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var leadime = data[4][x].y; var content = series.name + ": " + parseInt(y) + ' User Stories<br>Acumlated: ' + leadime + '<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 440 }); graph.render(); }); } }) } function InitializeAverageStoriesGraph(_id) { $.ajax({ type: 'GET', url: '/teams/' + _id + '/graph_stories', success: function (data) { flotMetric($('#metric-monthly-earnings'), data); } }); } ` class Teams boards = this constructor: -> @teamid = $('#teamid')[0].value if $('#teamid')[0]? @setup() setup: -> $("[data-behaviour='team_project_change']").on "change", @handleChange $("[data-behaviour='team_board_id_change']").on "change", @handleBoardChange @handleFirstResponse() @handleCycleTime() @handleHistoricalCFD() @handleSupportBugsCharts() handleChange: (e) -> return if $('#team_project').val() == undefined $.ajax( url: "/teams/full_project_details/" + $('#team_project').val() type: "JSON" method: "GET" success: (data) -> if (data != undefined) $("#project_image")[0].src = data['icon'] else $("[data-behaviour='board_type']").html("Error") ) $.ajax( url: "/teams/boards_by_team/" + $('#team_project').val() type: "JSON" method: "GET" contentType: "application/json" success: (data) -> boards = data $('#team_board_id').empty() $('#team_board_id').append($('<option>', {value: '', text: 'Select board...'})) data.map (board) -> $('#team_board_id').append($('<option>', {value: board['id'], text: board['name']})) ) handleBoardChange: (e) -> $("[data-behaviour='board_type']").val(boards[$('select#team_board_id option:selected').index() - 1].type) if ($("[data-behaviour='board_type']").val() == "" ) $("[data-behaviour='board_type']").val("kanban"); $.ajax( url: "/teams/custom_fields_by_board/" + $('select#team_board_id').val() type: "JSON" method: "GET" contentType: "application/json" success: (resp) -> $('select#team_estimated').empty() $('select#team_estimated').append($('<option>', {value: '', text: 'Select estimation field...'})) resp.map (board) -> $('select#team_estimated').append($('<option>', {value: board['id'], text: board['name']})) ) handleFirstResponse: (e) -> return if $('#teamid').val() == undefined return if $('#bars-first-response')[0] == undefined return if ($('#bars-first-response')[0].dataset.behaviour != 'chart_first_response') $.ajax( url: "/teams/" + $('#teamid')[0].value + "/graph_time_first_response/" type: "JSON" method: "GET" success: (data) -> if (data != undefined) TimeToFirstResponse(data); ) handleCycleTime: (e) -> return if $('#bars-cycle-time')[0] == undefined return if ($('#bars-cycle-time')[0].dataset.behaviour != 'chart_cycle_time') InitializeCycleTimeGraphTeam() InitializeAverageStoriesGraph(@teamid) return 0 handleHistoricalCFD: (e) -> return if $('#team-comulative-flow')[0] == undefined return if ($('#team-comulative-flow')[0].dataset.behaviour != 'chart_historical_stories_cfd') InitializeComulativeFlowChart() return 0 handleSupportBugsCharts: -> return if $('#bars-team-release-bugs')[0] == undefined return if ($('#bars-team-release-bugs')[0].dataset.behaviour != 'chart_release_bugs') InitializeReleaseTimeBugsGraphTeam() InitializeOpenClosedBugsGraphTeam() return 0 ready = -> jQuery -> new Teams $(document).on('turbolinks:load', ready)
107848
` function TimeToFirstResponse(data) { document.getElementById('bars-first-response-loader').innerHTML = ""; graph_f = new Rickshaw.Graph({ element: document.getElementById('bars-first-response'), height: 220, renderer: 'multi', series: [ { name: 'Time First Response', renderer: 'bar', color: '#90caf9', data: data[2] }, { name: 'Average First Time Response', renderer: 'line', color: '#d13b47', data: data[3] } ] }); var format = function (n) { if (data[1][n] === undefined) { return; } return data[1][n].y; } var legend = new Rickshaw.Graph.Legend({ graph: graph_f, element: document.getElementById('bars-first-response-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph_f, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph_f, legend: legend }) new Rickshaw.Graph.ClickDetail({ graph: graph_f, clickHandler: function (value) { window.open('/issues/key/' + $(".key_bug_sprint").text(), "_self") } }); new Rickshaw.Graph.Axis.X({ graph: graph_f, orientation: 'bottom', element: document.getElementById('bars-first-response-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-first-response-y_axis1'), graph: graph_f, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph_f.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_bug_sprint").text(); }, graph: graph_f, formatter: function (series, x, y) { var sprint = '<span class="date key_bug_sprint">' + data[0][x].y + '</span><span class="date"> created on ' + data[1][x].y + '</span>'; var content = series.name + " " + parseInt(y) + ' Hours<br>' + sprint; if (series.name === 'Time First Response') return content; return content; } }); $(window).on('resize', function () { graph_f.configure({ width: $('#bars-first-response').parent('.panel-body').width(), height: 220 }); graph_f.render(); }); } function InitializeCycleTimeGraphTeam() { graph = new Rickshaw.Graph.Ajax({ element: document.getElementById('bars-cycle-time'), height: 220, renderer: 'multi', method: 'POST', dataURL: '/teams/' + $('#teamid')[0].value + '/cycle_time_chart', onData: function (data) { document.getElementById('bars-cycle-time-loader').innerHTML = ""; series = data[0]; min = Number.MAX_VALUE; max = Number.MIN_VALUE; for (_l = 0, _len2 = series.length; _l < _len2; _l++) { point = series[_l]; min = Math.min(min, point.y); max = Math.max(max, point.y); } var scale_x = d3.scale.linear().domain([min, max]); window.store.state.selector.mseries = [ { name: 'Tickets', renderer: 'bar', color: '#90caf9', data: data[0], scale: scale_x }, { name: 'Cumulative', renderer: 'line', color: '#d13b47', data: data[1], scale: d3.scale.linear().domain([0, 100]) } ]; return window.store.state.selector.mseries }, onComplete: function (transport) { graph = transport.graph; var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-cycle-time-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-cycle-time-x_axis'), pixelsPerTick: 100, tickFormat: function (x) { return x + ' days'; } }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis1'), graph: graph, orientation: 'left', scale: window.store.state.selector.mseries[0].scale, pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis2'), graph: graph, grid: false, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: function (x) { return x + '%'; } }); graph.render(); new Rickshaw.Graph.HoverDetail({ graph: graph, formatter: function (series, x, y) { var content = 'Days: ' + x + '<br>'; window.store.state.selector.summary.days = x if (window.store.state.selector.mseries[0].data[x]) { window.store.state.selector.summary.tickets = window.store.state.selector.mseries[0].data[x].y content += '#Tickets: ' + window.store.state.selector.mseries[0].data[x].y + '<br>'; } if (window.store.state.selector.mseries[1].data[x]) { window.store.state.selector.summary.cumulative = window.store.state.selector.mseries[1].data[x].y content += 'Cumulative: ' + window.store.state.selector.mseries[1].data[x].y + '%'; } return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-cycle-time').parent('.container-fluid').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }); } function InitializeReleaseTimeBugsGraphTeam() { $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_lead_time_bugs', success: function (data) { if ($('#bars-team-release-bugs')[0] === undefined) { return; } else { document.getElementById('bars-team-release-bugs-loader').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById('bars-team-release-bugs'), height: 220, renderer: 'multi', series: [ { name: 'Waiting Time', renderer: 'bar', color: '#ff9642', data: data[1] }, { name: 'Working Time', renderer: 'bar', color: '#ffcc80', data: data[9] }, { name: 'Rolling Average', renderer: 'line', color: '#d13b47', data: data[8] } ] }); var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-team-release-bugs-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.ClickDetail({ graph: graph, clickHandler: function (value) { window.open('/issues/key/' + $(".key_team_bug").text(), "_self") } }); var format = function (n) { if (data[4][n] === undefined) { return; } return data[4][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-team-release-bugs-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-team-release-bugs-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[0][x].y + '</span><span class="date"> ' + data[7][x].y + ' ' + data[4][x].y + '</span>'; var flagged = ' <i class="fa fa-flag"></i>'; var bug = ' <i class="fa fa-bug"></i>'; var firsttime = ' <i class="fa fa-bolt"></i>'; var moreonesprint = ' <i class="fa fa-exclamation-triangle"></i>'; var content = series.name + ": " + parseInt(y) + ' days<br>' + sprint; if (data[2][x].y) content += flagged; if (data[3][x].y) content += firsttime; if (data[5][x].y) content += moreonesprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-team-release-bugs').parent('.panel-body').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }) } function InitializeOpenClosedBugsGraphTeam(id) { var _id = '' if (id === undefined) { _id = 'bars-team-openclosed-bugs' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_ratio_bugs_closed', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 220, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#ffcc80', data: data[1] }, { name: 'Open/Backlog', renderer: 'stack', color: '#ff9642', data: data[0] } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; } new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var content = series.name + ": " + parseInt(y) + ' Bugs<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 220 }); graph.render(); }); } }) } function InitializeComulativeFlowChart(id) { var _id = '' if (id === undefined) { _id = 'team-comulative-flow' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_comulative_flow_diagram', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var axis_scale = d3.scale.linear().domain([0, 100]); graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 440, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#0085f9', data: data[1], scale: axis_scale }, { name: 'In Progress', renderer: 'stack', color: '#90caf9', data: data[0], scale: axis_scale }, { name: '<NAME>', renderer: 'stack', color: '#ffcc80', data: data[3], scale: axis_scale } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 50, tickFormat: format }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: axis_scale, pixelsPerTick: 15, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.RangeSlider.Preview({ graph: graph, element: document.querySelector("#rangeSlider") }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var leadime = data[4][x].y; var content = series.name + ": " + parseInt(y) + ' User Stories<br>Acumlated: ' + leadime + '<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 440 }); graph.render(); }); } }) } function InitializeAverageStoriesGraph(_id) { $.ajax({ type: 'GET', url: '/teams/' + _id + '/graph_stories', success: function (data) { flotMetric($('#metric-monthly-earnings'), data); } }); } ` class Teams boards = this constructor: -> @teamid = $('#teamid')[0].value if $('#teamid')[0]? @setup() setup: -> $("[data-behaviour='team_project_change']").on "change", @handleChange $("[data-behaviour='team_board_id_change']").on "change", @handleBoardChange @handleFirstResponse() @handleCycleTime() @handleHistoricalCFD() @handleSupportBugsCharts() handleChange: (e) -> return if $('#team_project').val() == undefined $.ajax( url: "/teams/full_project_details/" + $('#team_project').val() type: "JSON" method: "GET" success: (data) -> if (data != undefined) $("#project_image")[0].src = data['icon'] else $("[data-behaviour='board_type']").html("Error") ) $.ajax( url: "/teams/boards_by_team/" + $('#team_project').val() type: "JSON" method: "GET" contentType: "application/json" success: (data) -> boards = data $('#team_board_id').empty() $('#team_board_id').append($('<option>', {value: '', text: 'Select board...'})) data.map (board) -> $('#team_board_id').append($('<option>', {value: board['id'], text: board['name']})) ) handleBoardChange: (e) -> $("[data-behaviour='board_type']").val(boards[$('select#team_board_id option:selected').index() - 1].type) if ($("[data-behaviour='board_type']").val() == "" ) $("[data-behaviour='board_type']").val("kanban"); $.ajax( url: "/teams/custom_fields_by_board/" + $('select#team_board_id').val() type: "JSON" method: "GET" contentType: "application/json" success: (resp) -> $('select#team_estimated').empty() $('select#team_estimated').append($('<option>', {value: '', text: 'Select estimation field...'})) resp.map (board) -> $('select#team_estimated').append($('<option>', {value: board['id'], text: board['name']})) ) handleFirstResponse: (e) -> return if $('#teamid').val() == undefined return if $('#bars-first-response')[0] == undefined return if ($('#bars-first-response')[0].dataset.behaviour != 'chart_first_response') $.ajax( url: "/teams/" + $('#teamid')[0].value + "/graph_time_first_response/" type: "JSON" method: "GET" success: (data) -> if (data != undefined) TimeToFirstResponse(data); ) handleCycleTime: (e) -> return if $('#bars-cycle-time')[0] == undefined return if ($('#bars-cycle-time')[0].dataset.behaviour != 'chart_cycle_time') InitializeCycleTimeGraphTeam() InitializeAverageStoriesGraph(@teamid) return 0 handleHistoricalCFD: (e) -> return if $('#team-comulative-flow')[0] == undefined return if ($('#team-comulative-flow')[0].dataset.behaviour != 'chart_historical_stories_cfd') InitializeComulativeFlowChart() return 0 handleSupportBugsCharts: -> return if $('#bars-team-release-bugs')[0] == undefined return if ($('#bars-team-release-bugs')[0].dataset.behaviour != 'chart_release_bugs') InitializeReleaseTimeBugsGraphTeam() InitializeOpenClosedBugsGraphTeam() return 0 ready = -> jQuery -> new Teams $(document).on('turbolinks:load', ready)
true
` function TimeToFirstResponse(data) { document.getElementById('bars-first-response-loader').innerHTML = ""; graph_f = new Rickshaw.Graph({ element: document.getElementById('bars-first-response'), height: 220, renderer: 'multi', series: [ { name: 'Time First Response', renderer: 'bar', color: '#90caf9', data: data[2] }, { name: 'Average First Time Response', renderer: 'line', color: '#d13b47', data: data[3] } ] }); var format = function (n) { if (data[1][n] === undefined) { return; } return data[1][n].y; } var legend = new Rickshaw.Graph.Legend({ graph: graph_f, element: document.getElementById('bars-first-response-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph_f, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph_f, legend: legend }) new Rickshaw.Graph.ClickDetail({ graph: graph_f, clickHandler: function (value) { window.open('/issues/key/' + $(".key_bug_sprint").text(), "_self") } }); new Rickshaw.Graph.Axis.X({ graph: graph_f, orientation: 'bottom', element: document.getElementById('bars-first-response-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-first-response-y_axis1'), graph: graph_f, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph_f.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_bug_sprint").text(); }, graph: graph_f, formatter: function (series, x, y) { var sprint = '<span class="date key_bug_sprint">' + data[0][x].y + '</span><span class="date"> created on ' + data[1][x].y + '</span>'; var content = series.name + " " + parseInt(y) + ' Hours<br>' + sprint; if (series.name === 'Time First Response') return content; return content; } }); $(window).on('resize', function () { graph_f.configure({ width: $('#bars-first-response').parent('.panel-body').width(), height: 220 }); graph_f.render(); }); } function InitializeCycleTimeGraphTeam() { graph = new Rickshaw.Graph.Ajax({ element: document.getElementById('bars-cycle-time'), height: 220, renderer: 'multi', method: 'POST', dataURL: '/teams/' + $('#teamid')[0].value + '/cycle_time_chart', onData: function (data) { document.getElementById('bars-cycle-time-loader').innerHTML = ""; series = data[0]; min = Number.MAX_VALUE; max = Number.MIN_VALUE; for (_l = 0, _len2 = series.length; _l < _len2; _l++) { point = series[_l]; min = Math.min(min, point.y); max = Math.max(max, point.y); } var scale_x = d3.scale.linear().domain([min, max]); window.store.state.selector.mseries = [ { name: 'Tickets', renderer: 'bar', color: '#90caf9', data: data[0], scale: scale_x }, { name: 'Cumulative', renderer: 'line', color: '#d13b47', data: data[1], scale: d3.scale.linear().domain([0, 100]) } ]; return window.store.state.selector.mseries }, onComplete: function (transport) { graph = transport.graph; var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-cycle-time-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-cycle-time-x_axis'), pixelsPerTick: 100, tickFormat: function (x) { return x + ' days'; } }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis1'), graph: graph, orientation: 'left', scale: window.store.state.selector.mseries[0].scale, pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById('bars-cycle-time-y_axis2'), graph: graph, grid: false, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: function (x) { return x + '%'; } }); graph.render(); new Rickshaw.Graph.HoverDetail({ graph: graph, formatter: function (series, x, y) { var content = 'Days: ' + x + '<br>'; window.store.state.selector.summary.days = x if (window.store.state.selector.mseries[0].data[x]) { window.store.state.selector.summary.tickets = window.store.state.selector.mseries[0].data[x].y content += '#Tickets: ' + window.store.state.selector.mseries[0].data[x].y + '<br>'; } if (window.store.state.selector.mseries[1].data[x]) { window.store.state.selector.summary.cumulative = window.store.state.selector.mseries[1].data[x].y content += 'Cumulative: ' + window.store.state.selector.mseries[1].data[x].y + '%'; } return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-cycle-time').parent('.container-fluid').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }); } function InitializeReleaseTimeBugsGraphTeam() { $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_lead_time_bugs', success: function (data) { if ($('#bars-team-release-bugs')[0] === undefined) { return; } else { document.getElementById('bars-team-release-bugs-loader').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById('bars-team-release-bugs'), height: 220, renderer: 'multi', series: [ { name: 'Waiting Time', renderer: 'bar', color: '#ff9642', data: data[1] }, { name: 'Working Time', renderer: 'bar', color: '#ffcc80', data: data[9] }, { name: 'Rolling Average', renderer: 'line', color: '#d13b47', data: data[8] } ] }); var legend = new Rickshaw.Graph.Legend({ graph: graph, element: document.getElementById('bars-team-release-bugs-legend') }); new Rickshaw.Graph.Behavior.Series.Highlight({ graph: graph, legend: legend, disabledColor: function () { return 'rgba(0, 0, 0, 0.2)' } }); new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: legend }); new Rickshaw.Graph.ClickDetail({ graph: graph, clickHandler: function (value) { window.open('/issues/key/' + $(".key_team_bug").text(), "_self") } }); var format = function (n) { if (data[4][n] === undefined) { return; } return data[4][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById('bars-team-release-bugs-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById('bars-team-release-bugs-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[0][x].y + '</span><span class="date"> ' + data[7][x].y + ' ' + data[4][x].y + '</span>'; var flagged = ' <i class="fa fa-flag"></i>'; var bug = ' <i class="fa fa-bug"></i>'; var firsttime = ' <i class="fa fa-bolt"></i>'; var moreonesprint = ' <i class="fa fa-exclamation-triangle"></i>'; var content = series.name + ": " + parseInt(y) + ' days<br>' + sprint; if (data[2][x].y) content += flagged; if (data[3][x].y) content += firsttime; if (data[5][x].y) content += moreonesprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#bars-team-release-bugs').parent('.panel-body').width(), height: 220 }); graph.render(); }); }, timeout: 5000 }) } function InitializeOpenClosedBugsGraphTeam(id) { var _id = '' if (id === undefined) { _id = 'bars-team-openclosed-bugs' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_ratio_bugs_closed', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var graph; graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 220, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#ffcc80', data: data[1] }, { name: 'Open/Backlog', renderer: 'stack', color: '#ff9642', data: data[0] } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; } new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 100, tickFormat: format }); new Rickshaw.Graph.Axis.Y({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: d3.scale.linear().domain([0, 100]), pixelsPerTick: 20, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { $('#key')[0].value = $(".key_team_bug").text(); }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var content = series.name + ": " + parseInt(y) + ' Bugs<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 220 }); graph.render(); }); } }) } function InitializeComulativeFlowChart(id) { var _id = '' if (id === undefined) { _id = 'team-comulative-flow' } if ($('#teamid')[0] === undefined) { return; } $.ajax({ type: 'GET', url: '/teams/' + $('#teamid')[0].value + '/graph_comulative_flow_diagram', success: function (data) { if ($('#' + _id)[0] === undefined) { return; } else { document.getElementById(_id).innerHTML = ""; document.getElementById(_id + '-x_axis').innerHTML = ""; } var axis_scale = d3.scale.linear().domain([0, 100]); graph = new Rickshaw.Graph({ element: document.getElementById(_id), height: 440, renderer: 'multi', series: [ { name: 'Closed', renderer: 'stack', color: '#0085f9', data: data[1], scale: axis_scale }, { name: 'In Progress', renderer: 'stack', color: '#90caf9', data: data[0], scale: axis_scale }, { name: 'PI:NAME:<NAME>END_PI', renderer: 'stack', color: '#ffcc80', data: data[3], scale: axis_scale } ] }); var format = function (n) { if (data[2][n] === undefined) { return; } return data[2][n].y; }; new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', element: document.getElementById(_id + '-x_axis'), pixelsPerTick: 50, tickFormat: format }); new Rickshaw.Graph.Axis.Y.Scaled({ element: document.getElementById(_id + '-y_axis1'), graph: graph, orientation: 'left', scale: axis_scale, pixelsPerTick: 15, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); new Rickshaw.Graph.RangeSlider.Preview({ graph: graph, element: document.querySelector("#rangeSlider") }); graph.render(); new Rickshaw.Graph.HoverDetail({ onShow: function (event) { }, graph: graph, formatter: function (series, x, y) { var sprint = '<span class="date key_team_bug">' + data[2][x].y + '</span>'; var leadime = data[4][x].y; var content = series.name + ": " + parseInt(y) + ' User Stories<br>Acumlated: ' + leadime + '<br>' + sprint; return content; } }); $(window).on('resize', function () { graph.configure({ width: $('#' + _id).parent('.panel-body').width(), height: 440 }); graph.render(); }); } }) } function InitializeAverageStoriesGraph(_id) { $.ajax({ type: 'GET', url: '/teams/' + _id + '/graph_stories', success: function (data) { flotMetric($('#metric-monthly-earnings'), data); } }); } ` class Teams boards = this constructor: -> @teamid = $('#teamid')[0].value if $('#teamid')[0]? @setup() setup: -> $("[data-behaviour='team_project_change']").on "change", @handleChange $("[data-behaviour='team_board_id_change']").on "change", @handleBoardChange @handleFirstResponse() @handleCycleTime() @handleHistoricalCFD() @handleSupportBugsCharts() handleChange: (e) -> return if $('#team_project').val() == undefined $.ajax( url: "/teams/full_project_details/" + $('#team_project').val() type: "JSON" method: "GET" success: (data) -> if (data != undefined) $("#project_image")[0].src = data['icon'] else $("[data-behaviour='board_type']").html("Error") ) $.ajax( url: "/teams/boards_by_team/" + $('#team_project').val() type: "JSON" method: "GET" contentType: "application/json" success: (data) -> boards = data $('#team_board_id').empty() $('#team_board_id').append($('<option>', {value: '', text: 'Select board...'})) data.map (board) -> $('#team_board_id').append($('<option>', {value: board['id'], text: board['name']})) ) handleBoardChange: (e) -> $("[data-behaviour='board_type']").val(boards[$('select#team_board_id option:selected').index() - 1].type) if ($("[data-behaviour='board_type']").val() == "" ) $("[data-behaviour='board_type']").val("kanban"); $.ajax( url: "/teams/custom_fields_by_board/" + $('select#team_board_id').val() type: "JSON" method: "GET" contentType: "application/json" success: (resp) -> $('select#team_estimated').empty() $('select#team_estimated').append($('<option>', {value: '', text: 'Select estimation field...'})) resp.map (board) -> $('select#team_estimated').append($('<option>', {value: board['id'], text: board['name']})) ) handleFirstResponse: (e) -> return if $('#teamid').val() == undefined return if $('#bars-first-response')[0] == undefined return if ($('#bars-first-response')[0].dataset.behaviour != 'chart_first_response') $.ajax( url: "/teams/" + $('#teamid')[0].value + "/graph_time_first_response/" type: "JSON" method: "GET" success: (data) -> if (data != undefined) TimeToFirstResponse(data); ) handleCycleTime: (e) -> return if $('#bars-cycle-time')[0] == undefined return if ($('#bars-cycle-time')[0].dataset.behaviour != 'chart_cycle_time') InitializeCycleTimeGraphTeam() InitializeAverageStoriesGraph(@teamid) return 0 handleHistoricalCFD: (e) -> return if $('#team-comulative-flow')[0] == undefined return if ($('#team-comulative-flow')[0].dataset.behaviour != 'chart_historical_stories_cfd') InitializeComulativeFlowChart() return 0 handleSupportBugsCharts: -> return if $('#bars-team-release-bugs')[0] == undefined return if ($('#bars-team-release-bugs')[0].dataset.behaviour != 'chart_release_bugs') InitializeReleaseTimeBugsGraphTeam() InitializeOpenClosedBugsGraphTeam() return 0 ready = -> jQuery -> new Teams $(document).on('turbolinks:load', ready)
[ { "context": "nt _.extend {}, @props,\n key: \"settings-widget-#{name}\"\n onChange: @onWidgetUpdate\n DOM", "end": 1601, "score": 0.7306637763977051, "start": 1586, "tag": "KEY", "value": "widget-#{name}\"" } ]
src/components/settings.coffee
brianshaler/kerplunk-blog
0
_ = require 'lodash' React = require 'react' Bootstrap = require 'react-bootstrap' {DOM} = React Input = React.createFactory Bootstrap.Input module.exports = React.createFactory React.createClass onWidgetUpdate: (update) -> return console.log 'update!', update render: -> DOM.section className: 'content' , DOM.h3 null, 'Blog Settings' DOM.form method: 'post' action: '/admin/blog' className: 'form-horizontal' , DOM.p null, Input type: 'text' name: 'title' label: 'Title' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'my blag' defaultValue: @props.blogSettings.title DOM.p null, Input type: 'text' name: 'tagline' label: 'Tagline' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'just another non-WordPress blag' defaultValue: @props.blogSettings.tagline DOM.p null, Input type: 'text' name: 'baseUrl' label: 'Base path' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'e.g. /blog' defaultValue: @props.blogSettings.baseUrl DOM.div null, _.map @props.globals.public.blog.settings, (componentPath, name) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "settings-widget-#{name}" onChange: @onWidgetUpdate DOM.p null, DOM.input type: 'submit' value: 'save'
119718
_ = require 'lodash' React = require 'react' Bootstrap = require 'react-bootstrap' {DOM} = React Input = React.createFactory Bootstrap.Input module.exports = React.createFactory React.createClass onWidgetUpdate: (update) -> return console.log 'update!', update render: -> DOM.section className: 'content' , DOM.h3 null, 'Blog Settings' DOM.form method: 'post' action: '/admin/blog' className: 'form-horizontal' , DOM.p null, Input type: 'text' name: 'title' label: 'Title' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'my blag' defaultValue: @props.blogSettings.title DOM.p null, Input type: 'text' name: 'tagline' label: 'Tagline' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'just another non-WordPress blag' defaultValue: @props.blogSettings.tagline DOM.p null, Input type: 'text' name: 'baseUrl' label: 'Base path' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'e.g. /blog' defaultValue: @props.blogSettings.baseUrl DOM.div null, _.map @props.globals.public.blog.settings, (componentPath, name) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "settings-<KEY> onChange: @onWidgetUpdate DOM.p null, DOM.input type: 'submit' value: 'save'
true
_ = require 'lodash' React = require 'react' Bootstrap = require 'react-bootstrap' {DOM} = React Input = React.createFactory Bootstrap.Input module.exports = React.createFactory React.createClass onWidgetUpdate: (update) -> return console.log 'update!', update render: -> DOM.section className: 'content' , DOM.h3 null, 'Blog Settings' DOM.form method: 'post' action: '/admin/blog' className: 'form-horizontal' , DOM.p null, Input type: 'text' name: 'title' label: 'Title' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'my blag' defaultValue: @props.blogSettings.title DOM.p null, Input type: 'text' name: 'tagline' label: 'Tagline' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'just another non-WordPress blag' defaultValue: @props.blogSettings.tagline DOM.p null, Input type: 'text' name: 'baseUrl' label: 'Base path' labelClassName: 'col-xs-2' wrapperClassName: 'col-xs-10' placeholder: 'e.g. /blog' defaultValue: @props.blogSettings.baseUrl DOM.div null, _.map @props.globals.public.blog.settings, (componentPath, name) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "settings-PI:KEY:<KEY>END_PI onChange: @onWidgetUpdate DOM.p null, DOM.input type: 'submit' value: 'save'
[ { "context": "ost:27017/mean\"\n mailer:\n defaultFromAddres: \"postmaster@blade.mailgun.org\"\n sessionSecret: process.env.SESSION_SECRET or \"", "end": 141, "score": 0.9999329447746277, "start": 113, "tag": "EMAIL", "value": "postmaster@blade.mailgun.org" }, { "context": "s.en...
development/server/config/env/all.coffee
SwingDev/MEAN-starter
0
module.exports = db: process.env.MONGODB or "mongodb://localhost:27017/mean" mailer: defaultFromAddres: "postmaster@blade.mailgun.org" sessionSecret: process.env.SESSION_SECRET or "Your Session Secret goes here" mailgun: user: process.env.MAILGUN_USER or "MAILGUN_USER" password: process.env.MAILGUN_PASSWORD or "MAILGUN_PASSWORD"
190255
module.exports = db: process.env.MONGODB or "mongodb://localhost:27017/mean" mailer: defaultFromAddres: "<EMAIL>" sessionSecret: process.env.SESSION_SECRET or "Your Session Secret goes here" mailgun: user: process.env.MAILGUN_USER or "MAILGUN_USER" password: <PASSWORD> or "<PASSWORD>"
true
module.exports = db: process.env.MONGODB or "mongodb://localhost:27017/mean" mailer: defaultFromAddres: "PI:EMAIL:<EMAIL>END_PI" sessionSecret: process.env.SESSION_SECRET or "Your Session Secret goes here" mailgun: user: process.env.MAILGUN_USER or "MAILGUN_USER" password: PI:PASSWORD:<PASSWORD>END_PI or "PI:PASSWORD:<PASSWORD>END_PI"
[ { "context": "(done) ->\n _global.createUser\n # username: _global.username3\n region: '86'\n phone: _global.phoneNumb", "end": 185, "score": 0.9893914461135864, "start": 168, "tag": "USERNAME", "value": "_global.username3" }, { "context": "ickname: _global.nickname...
spec/userSpec.coffee
lly5401/dhcseltalkserver
1
describe '用户接口测试', -> _global = null verificationCodeToken = null beforeAll -> _global = this afterAll (done) -> _global.createUser # username: _global.username3 region: '86' phone: _global.phoneNumber3 nickname: _global.nickname3 password: _global.password , (userId) -> _global.userId3 = userId done() describe '获取短信图验', -> xit '成功', (done) -> this.testGETAPI '/user/get_sms_img_code' , 200 , code: 200 result: url: 'STRING' verifyId: 'STRING' , done describe '发送验证码', -> it '成功', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '20012341234' , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '130qwerasdf' , 400 , null , done it '超过频率限制', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 5000 , done describe '验证验证码', -> xit '正确', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: code , 200 , code: 200 result: verification_token: 'UUID' , (body) -> verificationCodeToken = body.result.verification_token done() it '测试环境万能验证码', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '9999' , 200 , code: 200 result: verification_token: 'UUID' , (body) -> verificationCodeToken = body.result.verification_token done() it '错误', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '1234' # May be incorrect. , 200 , code: 1000 , done it '验证码为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '' , 400 , null , done xit '过期', (done) -> _global.getVerificationCode '86', _global.phoneNumber1, (code) -> _global.testPOSTAPI '/user/verify_code', region: '86' phone: _global.phoneNumber1 code: code , 200 , code: 2000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '' phone: _global.phoneNumber1 code: '0000' , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '' code: '0000' , 400 , null , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '0000' , 404 , null , done describe '用户注册', -> it '成功', (done) -> this.testPOSTAPI '/user/register', nickname: _global.xssString # username: _global.username password: _global.password verification_token: verificationCodeToken , 200 , code: 200 result: id: 'STRING' , (body, cookie) -> _global.userId1 = body.result.id _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done # it '用户名已经存在', (done) -> # this.testPOSTAPI '/user/register', # nickname: _global.nickname1 # username: _global.username1 # password: _global.password # verification_token: verificationCodeToken # , 403 # , null # , done it '手机号已经存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 # username: username + 'a' password: _global.password verification_token: verificationCodeToken , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI '/user/register', nickname: '' password: _global.password verification_token: verificationCodeToken , 400 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: 'a'.repeat 33 password: _global.password verification_token: verificationCodeToken , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '' verification_token: verificationCodeToken , 400 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'qwe qwe' verification_token: verificationCodeToken , 400 , null , done it '密码长度小于下限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'a'.repeat 5 verification_token: verificationCodeToken , 400 , null , done it '密码长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'a'.repeat 21 verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: _global.password verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: _global.password verification_token: '...' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: _global.password verification_token: '9a615598-7caa-11e5-a305-525439e49ee9' , 404 , null , done describe '检查手机号', -> it '存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 result: false , done it '不存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '13910000000' , 200 , code: 200 result: true , done it '区域号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '' , 400 , null , done it '手机号非法-23412341234', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '23412341234' , 400 , null , done it '手机号非法-130qwerasdf', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '130qwerasdf' , 400 , null , done describe '登录', -> it '成功', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _global.password , 200 , code: 200 result: token: 'STRING' , (body, cookie) -> _global.userCookie1 = cookie expect(cookie).not.toBeNull() expect(body.result.id).toEqual(_global.userId1) done() it '密码错误', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _global.password + '1' , 200 , code: 1000 , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '13' + Math.floor(Math.random() * 99999999 + 900000000) password: _global.password , 200 , code: 1000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/login', region: '' phone: _global.phoneNumber1 password: _global.password , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '' password: _global.password , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '20012341234' password: _global.password , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '130qwerasdf' password: _global.password , 400 , null , done xdescribe '获取融云 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_token", _global.userCookie1 , 200 , code: 200 result: userId: 'STRING' token: 'STRING' , done describe '获取用户基本信息', -> beforeAll (done) -> this.createUser # username: _global.username2 region: '86' phone: _global.phoneNumber2 nickname: _global.nickname2 password: _global.password , (userId) -> _global.userId2 = userId done() it '成功', (done) -> this.testGETAPI "/user/#{_global.userId2}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户 Id 不存在', (done) -> this.testGETAPI "/user/5Vg2XCh9f", _global.userCookie1 , 404 , null , done describe '批量获取用户基本信息', -> it '成功,数组', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=#{_global.userId2}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(2) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() expect(body.result[1].id).toBeDefined() expect(body.result[1].nickname).toBeDefined() expect(body.result[1].portraitUri).toBeDefined() done() it '成功,单一元素', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() it 'UserId 不存在', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=5Vg2XCh9f", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() describe '根据手机号查找用户信息', -> it '成功', (done) -> this.testGETAPI "/user/find/86/#{_global.phoneNumber1}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户不存在', (done) -> this.testGETAPI "/user/find/86/13912345678", _global.userCookie1 , 404 , null , done it '区号+手机号不合法', (done) -> this.testGETAPI "/user/find/86/1391234567", _global.userCookie1 , 400 , null , done describe '获取当前用户所属群组', -> it '成功', (done) -> this.testGETAPI "/user/groups", _global.userCookie1 , 200 , null , (body) -> expect(body.result.length).toEqual(0) done() describe '通过 Token 修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI '/user/reset_password', password: _global.passwordNew verification_token: verificationCodeToken , 200 , code: 200 , done it '密码为空', (done) -> this.testPOSTAPI '/user/reset_password', password: '' verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/reset_password', password: _global.passwordNew verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/reset_password', password: _global.passwordNew verification_token: '123' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/reset_password', password: _global.passwordNew verification_token: '9a615598-7caa-11e5-a305-525439e49ee9' , 404 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/reset_password', password: 'qwe qwe' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-少于6位', (done) -> this.testPOSTAPI '/user/reset_password', password: '123' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-多于20位', (done) -> this.testPOSTAPI '/user/reset_password', password: '01234567890qwe0123456789' verification_token: verificationCodeToken , 400 , null , done describe '通过旧密码修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _global.password oldPassword: _global.passwordNew , 200 , code: 200 , done it '旧密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _global.passwordNew oldPassword: '' , 400 , null , done it '新密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '' oldPassword: _global.password , 400 , null , done it '新密码不能包含空格', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: 'qwe qwe' oldPassword: _global.password , 400 , null , done it '新密码长度限制-少于6位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '123' oldPassword: _global.password , 400 , null , done it '新密码长度限制-多于20位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '01234567890qwe0123456789' oldPassword: _global.password , 400 , null , done it '密码错误', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _global.passwordNew oldPassword: '123123qwe' , 200 , code: 1000 , done describe '修改昵称', -> it '成功', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: _global.xssString , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done it '昵称包含需要转义的字符,转义后长度超过上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '<'.repeat 32 , 200 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: 'a'.repeat 33 , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '' , 400 , null , done describe '设置头像地址', -> it '成功', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.com/new_address' , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: portraitUri: 'http://a.com/new_address' , done it '头像地址格式不正确', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'abcd.com/abcdefgh' , 400 , null , done it '头像地址长度大于上限', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.co/' + 'a'.repeat 256 , 400 , null , done it '头像地址为空', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: '' , 400 , null , done describe '加入黑名单列表', -> it '成功', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: null , 400 , null , done it '好友 Id 不存在', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: 'SeWrfDYG8' , 404 , null , done describe '获取黑名单列表', -> it '成功', (done) -> this.testGETAPI "/user/blacklist", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].user.id).toBeDefined() expect(body.result[0].user.nickname).toBeDefined() expect(body.result[0].user.portraitUri).toBeDefined() done() describe '从黑名单列表中移除', -> it '成功', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: null , 400 , null , done describe '获取云存储所用 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_image_token", _global.userCookie1 , 200 , code: 200 result: target: 'qiniu' token: 'STRING' , done it '没有登录', (done) -> this.testGETAPI '/user/get_image_token' , 403 , null , done describe '注销', -> it '成功', (done) -> _global.testPOSTAPI "/user/logout", _global.userCookie1 , {} , 200 , null , (body, cookie) -> _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 403 , null , done
76924
describe '用户接口测试', -> _global = null verificationCodeToken = null beforeAll -> _global = this afterAll (done) -> _global.createUser # username: _global.username3 region: '86' phone: _global.phoneNumber3 nickname: _global.nickname3 password: _global.<PASSWORD> , (userId) -> _global.userId3 = userId done() describe '获取短信图验', -> xit '成功', (done) -> this.testGETAPI '/user/get_sms_img_code' , 200 , code: 200 result: url: 'STRING' verifyId: 'STRING' , done describe '发送验证码', -> it '成功', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '20012341234' , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '130qwerasdf' , 400 , null , done it '超过频率限制', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 5000 , done describe '验证验证码', -> xit '正确', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: code , 200 , code: 200 result: verification_token: '<KEY>' , (body) -> verificationCodeToken = body.result.verification_token done() it '测试环境万能验证码', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '9999' , 200 , code: 200 result: verification_token: '<KEY>' , (body) -> verificationCodeToken = body.result.verification_token done() it '错误', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '1234' # May be incorrect. , 200 , code: 1000 , done it '验证码为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '' , 400 , null , done xit '过期', (done) -> _global.getVerificationCode '86', _global.phoneNumber1, (code) -> _global.testPOSTAPI '/user/verify_code', region: '86' phone: _global.phoneNumber1 code: code , 200 , code: 2000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '' phone: _global.phoneNumber1 code: '0000' , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '' code: '0000' , 400 , null , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '0000' , 404 , null , done describe '用户注册', -> it '成功', (done) -> this.testPOSTAPI '/user/register', nickname: _global.xssString # username: _global.username password: <PASSWORD> verification_token: verificationCodeToken , 200 , code: 200 result: id: 'STRING' , (body, cookie) -> _global.userId1 = body.result.id _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done # it '用户名已经存在', (done) -> # this.testPOSTAPI '/user/register', # nickname: _global.nickname1 # username: _global.username1 # password: <PASSWORD> # verification_token: verificationCodeToken # , 403 # , null # , done it '手机号已经存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 # username: username + 'a' password: <PASSWORD> verification_token: verificationCodeToken , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI '/user/register', nickname: '' password: <PASSWORD> verification_token: verificationCodeToken , 400 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: 'a'.repeat 33 password: <PASSWORD> verification_token: verificationCodeToken , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '' verification_token: verificationCodeToken , 400 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '<PASSWORD>' verification_token: verificationCodeToken , 400 , null , done it '密码长度小于下限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '<PASSWORD>'.repeat 5 verification_token: verificationCodeToken , 400 , null , done it '密码长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '<PASSWORD>'.repeat 21 verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: <PASSWORD> verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: _<PASSWORD> verification_token: '...' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: <PASSWORD> verification_token: '<PASSWORD>' , 404 , null , done describe '检查手机号', -> it '存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 result: false , done it '不存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '13910000000' , 200 , code: 200 result: true , done it '区域号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '' , 400 , null , done it '手机号非法-23412341234', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '23412341234' , 400 , null , done it '手机号非法-130qwerasdf', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '130qwerasdf' , 400 , null , done describe '登录', -> it '成功', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _<PASSWORD> , 200 , code: 200 result: token: 'STRING' , (body, cookie) -> _global.userCookie1 = cookie expect(cookie).not.toBeNull() expect(body.result.id).toEqual(_global.userId1) done() it '密码错误', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _<PASSWORD> + '<PASSWORD>' , 200 , code: 1000 , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '13' + Math.floor(Math.random() * 99999999 + 900000000) password: <PASSWORD> , 200 , code: 1000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/login', region: '' phone: _global.phoneNumber1 password: _<PASSWORD> , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '' password: _<PASSWORD> , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '20012341234' password: <PASSWORD> , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '130qwerasdf' password: _<PASSWORD> , 400 , null , done xdescribe '获取融云 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_token", _global.userCookie1 , 200 , code: 200 result: userId: 'STRING' token: 'STRING' , done describe '获取用户基本信息', -> beforeAll (done) -> this.createUser # username: _global.username2 region: '86' phone: _global.phoneNumber2 nickname: _global.nickname2 password: <PASSWORD> , (userId) -> _global.userId2 = userId done() it '成功', (done) -> this.testGETAPI "/user/#{_global.userId2}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户 Id 不存在', (done) -> this.testGETAPI "/user/5Vg2XCh9f", _global.userCookie1 , 404 , null , done describe '批量获取用户基本信息', -> it '成功,数组', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=#{_global.userId2}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(2) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() expect(body.result[1].id).toBeDefined() expect(body.result[1].nickname).toBeDefined() expect(body.result[1].portraitUri).toBeDefined() done() it '成功,单一元素', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() it 'UserId 不存在', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=5Vg2XCh9f", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() describe '根据手机号查找用户信息', -> it '成功', (done) -> this.testGETAPI "/user/find/86/#{_global.phoneNumber1}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户不存在', (done) -> this.testGETAPI "/user/find/86/13912345678", _global.userCookie1 , 404 , null , done it '区号+手机号不合法', (done) -> this.testGETAPI "/user/find/86/1391234567", _global.userCookie1 , 400 , null , done describe '获取当前用户所属群组', -> it '成功', (done) -> this.testGETAPI "/user/groups", _global.userCookie1 , 200 , null , (body) -> expect(body.result.length).toEqual(0) done() describe '通过 Token 修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI '/user/reset_password', password: <PASSWORD> verification_token: verificationCodeToken , 200 , code: 200 , done it '密码为空', (done) -> this.testPOSTAPI '/user/reset_password', password: '' verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/reset_password', password: <PASSWORD> verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/reset_password', password: <PASSWORD> verification_token: '<PASSWORD>' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/reset_password', password: _<PASSWORD> verification_token: '<PASSWORD>' , 404 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/reset_password', password: '<PASSWORD>' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-少于6位', (done) -> this.testPOSTAPI '/user/reset_password', password: '<PASSWORD>' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-多于20位', (done) -> this.testPOSTAPI '/user/reset_password', password: '<PASSWORD>' verification_token: verificationCodeToken , 400 , null , done describe '通过旧密码修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _<PASSWORD> oldPassword: _<PASSWORD> , 200 , code: 200 , done it '旧密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _<PASSWORD> oldPassword: '' , 400 , null , done it '新密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '' oldPassword: _global.<PASSWORD> , 400 , null , done it '新密码不能包含空格', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '<PASSWORD>' oldPassword: _global.<PASSWORD> , 400 , null , done it '新密码长度限制-少于6位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '<PASSWORD>' oldPassword: _global.<PASSWORD> , 400 , null , done it '新密码长度限制-多于20位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '<PASSWORD>' oldPassword: _<PASSWORD> , 400 , null , done it '密码错误', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _<PASSWORD> oldPassword: '<PASSWORD>' , 200 , code: 1000 , done describe '修改昵称', -> it '成功', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: _global.xssString , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done it '昵称包含需要转义的字符,转义后长度超过上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '<'.repeat 32 , 200 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: 'a'.repeat 33 , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '' , 400 , null , done describe '设置头像地址', -> it '成功', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.com/new_address' , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: portraitUri: 'http://a.com/new_address' , done it '头像地址格式不正确', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'abcd.com/abcdefgh' , 400 , null , done it '头像地址长度大于上限', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.co/' + 'a'.repeat 256 , 400 , null , done it '头像地址为空', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: '' , 400 , null , done describe '加入黑名单列表', -> it '成功', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: null , 400 , null , done it '好友 Id 不存在', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: 'Se<PASSWORD>' , 404 , null , done describe '获取黑名单列表', -> it '成功', (done) -> this.testGETAPI "/user/blacklist", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].user.id).toBeDefined() expect(body.result[0].user.nickname).toBeDefined() expect(body.result[0].user.portraitUri).toBeDefined() done() describe '从黑名单列表中移除', -> it '成功', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: null , 400 , null , done describe '获取云存储所用 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_image_token", _global.userCookie1 , 200 , code: 200 result: target: 'qiniu' token: 'STRING' , done it '没有登录', (done) -> this.testGETAPI '/user/get_image_token' , 403 , null , done describe '注销', -> it '成功', (done) -> _global.testPOSTAPI "/user/logout", _global.userCookie1 , {} , 200 , null , (body, cookie) -> _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 403 , null , done
true
describe '用户接口测试', -> _global = null verificationCodeToken = null beforeAll -> _global = this afterAll (done) -> _global.createUser # username: _global.username3 region: '86' phone: _global.phoneNumber3 nickname: _global.nickname3 password: _global.PI:PASSWORD:<PASSWORD>END_PI , (userId) -> _global.userId3 = userId done() describe '获取短信图验', -> xit '成功', (done) -> this.testGETAPI '/user/get_sms_img_code' , 200 , code: 200 result: url: 'STRING' verifyId: 'STRING' , done describe '发送验证码', -> it '成功', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '20012341234' , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: '130qwerasdf' , 400 , null , done it '超过频率限制', (done) -> this.testPOSTAPI '/user/send_code', region: '86' phone: _global.phoneNumber1 , 200 , code: 5000 , done describe '验证验证码', -> xit '正确', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: code , 200 , code: 200 result: verification_token: 'PI:KEY:<KEY>END_PI' , (body) -> verificationCodeToken = body.result.verification_token done() it '测试环境万能验证码', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '9999' , 200 , code: 200 result: verification_token: 'PI:KEY:<KEY>END_PI' , (body) -> verificationCodeToken = body.result.verification_token done() it '错误', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: this.phoneNumber1 code: '1234' # May be incorrect. , 200 , code: 1000 , done it '验证码为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '' , 400 , null , done xit '过期', (done) -> _global.getVerificationCode '86', _global.phoneNumber1, (code) -> _global.testPOSTAPI '/user/verify_code', region: '86' phone: _global.phoneNumber1 code: code , 200 , code: 2000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '' phone: _global.phoneNumber1 code: '0000' , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '' code: '0000' , 400 , null , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/verify_code', region: '86' phone: '10000000000' code: '0000' , 404 , null , done describe '用户注册', -> it '成功', (done) -> this.testPOSTAPI '/user/register', nickname: _global.xssString # username: _global.username password: PI:PASSWORD:<PASSWORD>END_PI verification_token: verificationCodeToken , 200 , code: 200 result: id: 'STRING' , (body, cookie) -> _global.userId1 = body.result.id _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done # it '用户名已经存在', (done) -> # this.testPOSTAPI '/user/register', # nickname: _global.nickname1 # username: _global.username1 # password: PI:PASSWORD:<PASSWORD>END_PI # verification_token: verificationCodeToken # , 403 # , null # , done it '手机号已经存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 # username: username + 'a' password: PI:PASSWORD:<PASSWORD>END_PI verification_token: verificationCodeToken , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI '/user/register', nickname: '' password: PI:PASSWORD:<PASSWORD>END_PI verification_token: verificationCodeToken , 400 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: 'a'.repeat 33 password: PI:PASSWORD:<PASSWORD>END_PI verification_token: verificationCodeToken , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: '' verification_token: verificationCodeToken , 400 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'PI:PASSWORD:<PASSWORD>END_PI' verification_token: verificationCodeToken , 400 , null , done it '密码长度小于下限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'PI:PASSWORD:<PASSWORD>END_PI'.repeat 5 verification_token: verificationCodeToken , 400 , null , done it '密码长度大于上限', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: 'PI:PASSWORD:<PASSWORD>END_PI'.repeat 21 verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: PI:PASSWORD:<PASSWORD>END_PI verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: _PI:PASSWORD:<PASSWORD>END_PI verification_token: '...' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/register', nickname: _global.nickname1 password: PI:PASSWORD:<PASSWORD>END_PI verification_token: 'PI:PASSWORD:<PASSWORD>END_PI' , 404 , null , done describe '检查手机号', -> it '存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: _global.phoneNumber1 , 200 , code: 200 result: false , done it '不存在', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '13910000000' , 200 , code: 200 result: true , done it '区域号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '' phone: _global.phoneNumber1 , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '' , 400 , null , done it '手机号非法-23412341234', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '23412341234' , 400 , null , done it '手机号非法-130qwerasdf', (done) -> this.testPOSTAPI '/user/check_phone_available', region: '86' phone: '130qwerasdf' , 400 , null , done describe '登录', -> it '成功', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _PI:PASSWORD:<PASSWORD>END_PI , 200 , code: 200 result: token: 'STRING' , (body, cookie) -> _global.userCookie1 = cookie expect(cookie).not.toBeNull() expect(body.result.id).toEqual(_global.userId1) done() it '密码错误', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: _PI:PASSWORD:<PASSWORD>END_PI + 'PI:PASSWORD:<PASSWORD>END_PI' , 200 , code: 1000 , done it '手机号不存在', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '13' + Math.floor(Math.random() * 99999999 + 900000000) password: PI:PASSWORD:<PASSWORD>END_PI , 200 , code: 1000 , done it '区域号为空', (done) -> this.testPOSTAPI '/user/login', region: '' phone: _global.phoneNumber1 password: _PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '手机号为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '' password: _PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '密码为空', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: _global.phoneNumber1 password: '' , 400 , null , done it '手机号不合法-20012341234', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '20012341234' password: PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '手机号不合法-130qwerasdf', (done) -> this.testPOSTAPI '/user/login', region: '86' phone: '130qwerasdf' password: _PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done xdescribe '获取融云 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_token", _global.userCookie1 , 200 , code: 200 result: userId: 'STRING' token: 'STRING' , done describe '获取用户基本信息', -> beforeAll (done) -> this.createUser # username: _global.username2 region: '86' phone: _global.phoneNumber2 nickname: _global.nickname2 password: PI:PASSWORD:<PASSWORD>END_PI , (userId) -> _global.userId2 = userId done() it '成功', (done) -> this.testGETAPI "/user/#{_global.userId2}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户 Id 不存在', (done) -> this.testGETAPI "/user/5Vg2XCh9f", _global.userCookie1 , 404 , null , done describe '批量获取用户基本信息', -> it '成功,数组', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=#{_global.userId2}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(2) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() expect(body.result[1].id).toBeDefined() expect(body.result[1].nickname).toBeDefined() expect(body.result[1].portraitUri).toBeDefined() done() it '成功,单一元素', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() it 'UserId 不存在', (done) -> this.testGETAPI "/user/batch?id=#{_global.userId1}&id=5Vg2XCh9f", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].id).toBeDefined() expect(body.result[0].nickname).toBeDefined() expect(body.result[0].portraitUri).toBeDefined() done() describe '根据手机号查找用户信息', -> it '成功', (done) -> this.testGETAPI "/user/find/86/#{_global.phoneNumber1}", _global.userCookie1 , 200 , code: 200 result: id: 'STRING' nickname: 'STRING' portraitUri: 'STRING' , done it '用户不存在', (done) -> this.testGETAPI "/user/find/86/13912345678", _global.userCookie1 , 404 , null , done it '区号+手机号不合法', (done) -> this.testGETAPI "/user/find/86/1391234567", _global.userCookie1 , 400 , null , done describe '获取当前用户所属群组', -> it '成功', (done) -> this.testGETAPI "/user/groups", _global.userCookie1 , 200 , null , (body) -> expect(body.result.length).toEqual(0) done() describe '通过 Token 修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI '/user/reset_password', password: PI:PASSWORD:<PASSWORD>END_PI verification_token: verificationCodeToken , 200 , code: 200 , done it '密码为空', (done) -> this.testPOSTAPI '/user/reset_password', password: '' verification_token: verificationCodeToken , 400 , null , done it 'Token 为空', (done) -> this.testPOSTAPI '/user/reset_password', password: PI:PASSWORD:<PASSWORD>END_PI verification_token: '' , 400 , null , done it 'Token 格式错误', (done) -> this.testPOSTAPI '/user/reset_password', password: PI:PASSWORD:<PASSWORD>END_PI verification_token: 'PI:PASSWORD:<PASSWORD>END_PI' , 400 , null , done it 'Token 不存在', (done) -> this.testPOSTAPI '/user/reset_password', password: _PI:PASSWORD:<PASSWORD>END_PI verification_token: 'PI:PASSWORD:<PASSWORD>END_PI' , 404 , null , done it '密码不能包含空格', (done) -> this.testPOSTAPI '/user/reset_password', password: 'PI:PASSWORD:<PASSWORD>END_PI' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-少于6位', (done) -> this.testPOSTAPI '/user/reset_password', password: 'PI:PASSWORD:<PASSWORD>END_PI' verification_token: verificationCodeToken , 400 , null , done it '密码长度限制-多于20位', (done) -> this.testPOSTAPI '/user/reset_password', password: 'PI:PASSWORD:<PASSWORD>END_PI' verification_token: verificationCodeToken , 400 , null , done describe '通过旧密码修改密码', -> #成功修改密码之后,群组接口测试将全部失败,因为密码错误登录失败 it '成功', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _PI:PASSWORD:<PASSWORD>END_PI oldPassword: _PI:PASSWORD:<PASSWORD>END_PI , 200 , code: 200 , done it '旧密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _PI:PASSWORD:<PASSWORD>END_PI oldPassword: '' , 400 , null , done it '新密码为空', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: '' oldPassword: _global.PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '新密码不能包含空格', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' oldPassword: _global.PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '新密码长度限制-少于6位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' oldPassword: _global.PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '新密码长度限制-多于20位', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' oldPassword: _PI:PASSWORD:<PASSWORD>END_PI , 400 , null , done it '密码错误', (done) -> this.testPOSTAPI "/user/change_password", _global.userCookie1, newPassword: _PI:PASSWORD:<PASSWORD>END_PI oldPassword: 'PI:PASSWORD:<PASSWORD>END_PI' , 200 , code: 1000 , done describe '修改昵称', -> it '成功', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: _global.xssString , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: nickname: _global.filteredString , done it '昵称包含需要转义的字符,转义后长度超过上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '<'.repeat 32 , 200 , null , done it '昵称长度大于上限', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: 'a'.repeat 33 , 400 , null , done it '昵称为空', (done) -> this.testPOSTAPI "/user/set_nickname", _global.userCookie1, nickname: '' , 400 , null , done describe '设置头像地址', -> it '成功', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.com/new_address' , 200 , code: 200 , -> _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 200 , code: 200 result: portraitUri: 'http://a.com/new_address' , done it '头像地址格式不正确', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'abcd.com/abcdefgh' , 400 , null , done it '头像地址长度大于上限', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: 'http://a.co/' + 'a'.repeat 256 , 400 , null , done it '头像地址为空', (done) -> this.testPOSTAPI "/user/set_portrait_uri", _global.userCookie1, portraitUri: '' , 400 , null , done describe '加入黑名单列表', -> it '成功', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: null , 400 , null , done it '好友 Id 不存在', (done) -> this.testPOSTAPI "/user/add_to_blacklist", _global.userCookie1, friendId: 'SePI:PASSWORD:<PASSWORD>END_PI' , 404 , null , done describe '获取黑名单列表', -> it '成功', (done) -> this.testGETAPI "/user/blacklist", _global.userCookie1 , 200 , code: 200 , (body) -> expect(body.result.length).toEqual(1) if body.result.length > 0 expect(body.result[0].user.id).toBeDefined() expect(body.result[0].user.nickname).toBeDefined() expect(body.result[0].user.portraitUri).toBeDefined() done() describe '从黑名单列表中移除', -> it '成功', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: _global.userId2 , 200 , code: 200 , done it '好友 Id 为空', (done) -> this.testPOSTAPI "/user/remove_from_blacklist", _global.userCookie1, friendId: null , 400 , null , done describe '获取云存储所用 Token', -> it '成功', (done) -> this.testGETAPI "/user/get_image_token", _global.userCookie1 , 200 , code: 200 result: target: 'qiniu' token: 'STRING' , done it '没有登录', (done) -> this.testGETAPI '/user/get_image_token' , 403 , null , done describe '注销', -> it '成功', (done) -> _global.testPOSTAPI "/user/logout", _global.userCookie1 , {} , 200 , null , (body, cookie) -> _global.userCookie1 = cookie _global.testGETAPI "/user/#{_global.userId1}", _global.userCookie1 , 403 , null , done
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.9998884201049805, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/r...
src/Coffixi/renderers/webgl/GLESGraphics.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/webgl/GLESGraphics', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/utils/PolyK' 'Coffixi/primitives/Graphics' 'Coffixi/renderers/webgl/GLESShaders' 'Coffixi/utils/Utils' ], ( Point Matrix PolyK Graphics GLESShaders Utils ) -> ###* A set of functions used by the webGL renderer to draw the primitive graphics data @class CanvasGraphics ### class GLESGraphics ###* Renders the graphics object @static @private @method renderGraphics @param graphics {Graphics} @param projection {Object} ### @renderGraphics: (graphics, projection) -> gl = @gl unless graphics._GL graphics._GL = points: [] indices: [] lastIndex: 0 buffer: gl.createBuffer() indexBuffer: gl.createBuffer() if graphics.dirty graphics.dirty = false if graphics.clearDirty graphics.clearDirty = false graphics._GL.lastIndex = 0 graphics._GL.points = [] graphics._GL.indices = [] GLESGraphics.updateGraphics graphics GLESShaders.activatePrimitiveShader gl m = Matrix.mat3.clone(graphics.worldTransform) Matrix.mat3.transpose m gl.blendFunc gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA gl.uniformMatrix3fv GLESShaders.primitiveShader.translationMatrix, false, m gl.uniform2f GLESShaders.primitiveShader.projectionVector, projection.x, projection.y gl.uniform1f GLESShaders.primitiveShader.alpha, graphics.worldAlpha gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.vertexAttribPointer GLESShaders.defaultShader.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.vertexPositionAttribute, 2, gl.FLOAT, false, 4 * 6, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.colorAttribute, 4, gl.FLOAT, false, 4 * 6, 2 * 4 gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.drawElements gl.TRIANGLE_STRIP, graphics._GL.indices.length, gl.UNSIGNED_SHORT, 0 GLESShaders.activateDefaultShader gl ###* Updates the graphics object @static @private @method updateGraphics @param graphics {Graphics} ### @updateGraphics: (graphics) -> i = graphics._GL.lastIndex while i < graphics.graphicsData.length data = graphics.graphicsData[i] if data.type is Graphics.POLY GLESGraphics.buildPoly data, graphics._GL if data.points.length > 3 if data.fill GLESGraphics.buildLine data, graphics._GL if data.lineWidth > 0 else if data.type is Graphics.RECT GLESGraphics.buildRectangle data, graphics._GL else GLESGraphics.buildCircle data, graphics._GL if data.type is Graphics.CIRC or data.type is Graphics.ELIP i++ graphics._GL.lastIndex = graphics.graphicsData.length gl = @gl graphics._GL.glPoints = new Utils.Float32Array(graphics._GL.points) gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.bufferData gl.ARRAY_BUFFER, graphics._GL.glPoints, gl.STATIC_DRAW graphics._GL.glIndicies = new Utils.Uint16Array(graphics._GL.indices) gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.bufferData gl.ELEMENT_ARRAY_BUFFER, graphics._GL.glIndicies, gl.STATIC_DRAW ###* Builds a rectangle to draw @static @private @method buildRectangle @param graphics {Graphics} @param webGLData {Object} ### @buildRectangle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vertPos = verts.length / 6 verts.push x, y verts.push r, g, b, alpha verts.push x + width, y verts.push r, g, b, alpha verts.push x, y + height verts.push r, g, b, alpha verts.push x + width, y + height verts.push r, g, b, alpha indices.push vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3 if graphicsData.lineWidth graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y] GLESGraphics.buildLine graphicsData, webGLData ###* Builds a circle to draw @static @private @method buildCircle @param graphics {Graphics} @param webGLData {Object} ### @buildCircle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] totalSegs = 40 seg = (Math.PI * 2) / totalSegs if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vecPos = verts.length / 6 indices.push vecPos i = 0 while i < totalSegs + 1 verts.push x, y, r, g, b, alpha verts.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha indices.push vecPos++, vecPos++ i++ indices.push vecPos - 1 if graphicsData.lineWidth graphicsData.points = [] i = 0 while i < totalSegs + 1 graphicsData.points.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height i++ GLESGraphics.buildLine graphicsData, webGLData ###* Builds a line to draw @static @private @method buildLine @param graphics {Graphics} @param webGLData {Object} ### @buildLine: (graphicsData, webGLData) -> wrap = true points = graphicsData.points return if points.length is 0 firstPoint = new Point(points[0], points[1]) lastPoint = new Point(points[points.length - 2], points[points.length - 1]) if firstPoint.x is lastPoint.x and firstPoint.y is lastPoint.y points.pop() points.pop() lastPoint = new Point(points[points.length - 2], points[points.length - 1]) midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5 midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5 points.unshift midPointX, midPointY points.push midPointX, midPointY verts = webGLData.points indices = webGLData.indices length = points.length / 2 indexCount = points.length indexStart = verts.length / 6 width = graphicsData.lineWidth / 2 color = Utils.HEXtoRGB(graphicsData.lineColor) alpha = graphicsData.lineAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha p1x = undefined p1y = undefined p2x = undefined p2y = undefined p3x = undefined p3y = undefined perpx = undefined perpy = undefined perp2x = undefined perp2y = undefined perp3x = undefined perp3y = undefined ipx = undefined ipy = undefined a1 = undefined b1 = undefined c1 = undefined a2 = undefined b2 = undefined c2 = undefined denom = undefined pdist = undefined dist = undefined p1x = points[0] p1y = points[1] p2x = points[2] p2y = points[3] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p1x - perpx, p1y - perpy, r, g, b, alpha verts.push p1x + perpx, p1y + perpy, r, g, b, alpha i = 1 while i < length - 1 p1x = points[(i - 1) * 2] p1y = points[(i - 1) * 2 + 1] p2x = points[(i) * 2] p2y = points[(i) * 2 + 1] p3x = points[(i + 1) * 2] p3y = points[(i + 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width perp2x = -(p2y - p3y) perp2y = p2x - p3x dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y) perp2x /= dist perp2y /= dist perp2x *= width perp2y *= width a1 = (-perpy + p1y) - (-perpy + p2y) b1 = (-perpx + p2x) - (-perpx + p1x) c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y) a2 = (-perp2y + p3y) - (-perp2y + p2y) b2 = (-perp2x + p2x) - (-perp2x + p3x) c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y) denom = a1 * b2 - a2 * b1 denom += 1 if denom is 0 px = (b1 * c2 - b2 * c1) / denom py = (a2 * c1 - a1 * c2) / denom pdist = (px - p2x) * (px - p2x) + (py - p2y) + (py - p2y) if pdist > 140 * 140 perp3x = perpx - perp2x perp3y = perpy - perp2y dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y) perp3x /= dist perp3y /= dist perp3x *= width perp3y *= width verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha verts.push p2x + perp3x, p2y + perp3y verts.push r, g, b, alpha verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha indexCount++ else verts.push px, py verts.push r, g, b, alpha verts.push p2x - (px - p2x), p2y - (py - p2y) verts.push r, g, b, alpha i++ p1x = points[(length - 2) * 2] p1y = points[(length - 2) * 2 + 1] p2x = points[(length - 1) * 2] p2y = points[(length - 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p2x - perpx, p2y - perpy verts.push r, g, b, alpha verts.push p2x + perpx, p2y + perpy verts.push r, g, b, alpha indices.push indexStart i = 0 while i < indexCount indices.push indexStart++ i++ indices.push indexStart - 1 ###* Builds a polygon to draw @static @private @method buildPoly @param graphics {Graphics} @param webGLData {Object} ### @buildPoly: (graphicsData, webGLData) -> points = graphicsData.points return if points.length < 6 verts = webGLData.points indices = webGLData.indices length = points.length / 2 color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha triangles = PolyK.Triangulate(points) vertPos = verts.length / 6 i = 0 while i < triangles.length indices.push triangles[i] + vertPos indices.push triangles[i] + vertPos indices.push triangles[i + 1] + vertPos indices.push triangles[i + 2] + vertPos indices.push triangles[i + 2] + vertPos i += 3 i = 0 while i < length verts.push points[i * 2], points[i * 2 + 1], r, g, b, alpha i++
57383
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/webgl/GLESGraphics', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/utils/PolyK' 'Coffixi/primitives/Graphics' 'Coffixi/renderers/webgl/GLESShaders' 'Coffixi/utils/Utils' ], ( Point Matrix PolyK Graphics GLESShaders Utils ) -> ###* A set of functions used by the webGL renderer to draw the primitive graphics data @class CanvasGraphics ### class GLESGraphics ###* Renders the graphics object @static @private @method renderGraphics @param graphics {Graphics} @param projection {Object} ### @renderGraphics: (graphics, projection) -> gl = @gl unless graphics._GL graphics._GL = points: [] indices: [] lastIndex: 0 buffer: gl.createBuffer() indexBuffer: gl.createBuffer() if graphics.dirty graphics.dirty = false if graphics.clearDirty graphics.clearDirty = false graphics._GL.lastIndex = 0 graphics._GL.points = [] graphics._GL.indices = [] GLESGraphics.updateGraphics graphics GLESShaders.activatePrimitiveShader gl m = Matrix.mat3.clone(graphics.worldTransform) Matrix.mat3.transpose m gl.blendFunc gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA gl.uniformMatrix3fv GLESShaders.primitiveShader.translationMatrix, false, m gl.uniform2f GLESShaders.primitiveShader.projectionVector, projection.x, projection.y gl.uniform1f GLESShaders.primitiveShader.alpha, graphics.worldAlpha gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.vertexAttribPointer GLESShaders.defaultShader.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.vertexPositionAttribute, 2, gl.FLOAT, false, 4 * 6, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.colorAttribute, 4, gl.FLOAT, false, 4 * 6, 2 * 4 gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.drawElements gl.TRIANGLE_STRIP, graphics._GL.indices.length, gl.UNSIGNED_SHORT, 0 GLESShaders.activateDefaultShader gl ###* Updates the graphics object @static @private @method updateGraphics @param graphics {Graphics} ### @updateGraphics: (graphics) -> i = graphics._GL.lastIndex while i < graphics.graphicsData.length data = graphics.graphicsData[i] if data.type is Graphics.POLY GLESGraphics.buildPoly data, graphics._GL if data.points.length > 3 if data.fill GLESGraphics.buildLine data, graphics._GL if data.lineWidth > 0 else if data.type is Graphics.RECT GLESGraphics.buildRectangle data, graphics._GL else GLESGraphics.buildCircle data, graphics._GL if data.type is Graphics.CIRC or data.type is Graphics.ELIP i++ graphics._GL.lastIndex = graphics.graphicsData.length gl = @gl graphics._GL.glPoints = new Utils.Float32Array(graphics._GL.points) gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.bufferData gl.ARRAY_BUFFER, graphics._GL.glPoints, gl.STATIC_DRAW graphics._GL.glIndicies = new Utils.Uint16Array(graphics._GL.indices) gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.bufferData gl.ELEMENT_ARRAY_BUFFER, graphics._GL.glIndicies, gl.STATIC_DRAW ###* Builds a rectangle to draw @static @private @method buildRectangle @param graphics {Graphics} @param webGLData {Object} ### @buildRectangle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vertPos = verts.length / 6 verts.push x, y verts.push r, g, b, alpha verts.push x + width, y verts.push r, g, b, alpha verts.push x, y + height verts.push r, g, b, alpha verts.push x + width, y + height verts.push r, g, b, alpha indices.push vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3 if graphicsData.lineWidth graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y] GLESGraphics.buildLine graphicsData, webGLData ###* Builds a circle to draw @static @private @method buildCircle @param graphics {Graphics} @param webGLData {Object} ### @buildCircle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] totalSegs = 40 seg = (Math.PI * 2) / totalSegs if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vecPos = verts.length / 6 indices.push vecPos i = 0 while i < totalSegs + 1 verts.push x, y, r, g, b, alpha verts.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha indices.push vecPos++, vecPos++ i++ indices.push vecPos - 1 if graphicsData.lineWidth graphicsData.points = [] i = 0 while i < totalSegs + 1 graphicsData.points.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height i++ GLESGraphics.buildLine graphicsData, webGLData ###* Builds a line to draw @static @private @method buildLine @param graphics {Graphics} @param webGLData {Object} ### @buildLine: (graphicsData, webGLData) -> wrap = true points = graphicsData.points return if points.length is 0 firstPoint = new Point(points[0], points[1]) lastPoint = new Point(points[points.length - 2], points[points.length - 1]) if firstPoint.x is lastPoint.x and firstPoint.y is lastPoint.y points.pop() points.pop() lastPoint = new Point(points[points.length - 2], points[points.length - 1]) midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5 midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5 points.unshift midPointX, midPointY points.push midPointX, midPointY verts = webGLData.points indices = webGLData.indices length = points.length / 2 indexCount = points.length indexStart = verts.length / 6 width = graphicsData.lineWidth / 2 color = Utils.HEXtoRGB(graphicsData.lineColor) alpha = graphicsData.lineAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha p1x = undefined p1y = undefined p2x = undefined p2y = undefined p3x = undefined p3y = undefined perpx = undefined perpy = undefined perp2x = undefined perp2y = undefined perp3x = undefined perp3y = undefined ipx = undefined ipy = undefined a1 = undefined b1 = undefined c1 = undefined a2 = undefined b2 = undefined c2 = undefined denom = undefined pdist = undefined dist = undefined p1x = points[0] p1y = points[1] p2x = points[2] p2y = points[3] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p1x - perpx, p1y - perpy, r, g, b, alpha verts.push p1x + perpx, p1y + perpy, r, g, b, alpha i = 1 while i < length - 1 p1x = points[(i - 1) * 2] p1y = points[(i - 1) * 2 + 1] p2x = points[(i) * 2] p2y = points[(i) * 2 + 1] p3x = points[(i + 1) * 2] p3y = points[(i + 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width perp2x = -(p2y - p3y) perp2y = p2x - p3x dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y) perp2x /= dist perp2y /= dist perp2x *= width perp2y *= width a1 = (-perpy + p1y) - (-perpy + p2y) b1 = (-perpx + p2x) - (-perpx + p1x) c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y) a2 = (-perp2y + p3y) - (-perp2y + p2y) b2 = (-perp2x + p2x) - (-perp2x + p3x) c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y) denom = a1 * b2 - a2 * b1 denom += 1 if denom is 0 px = (b1 * c2 - b2 * c1) / denom py = (a2 * c1 - a1 * c2) / denom pdist = (px - p2x) * (px - p2x) + (py - p2y) + (py - p2y) if pdist > 140 * 140 perp3x = perpx - perp2x perp3y = perpy - perp2y dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y) perp3x /= dist perp3y /= dist perp3x *= width perp3y *= width verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha verts.push p2x + perp3x, p2y + perp3y verts.push r, g, b, alpha verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha indexCount++ else verts.push px, py verts.push r, g, b, alpha verts.push p2x - (px - p2x), p2y - (py - p2y) verts.push r, g, b, alpha i++ p1x = points[(length - 2) * 2] p1y = points[(length - 2) * 2 + 1] p2x = points[(length - 1) * 2] p2y = points[(length - 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p2x - perpx, p2y - perpy verts.push r, g, b, alpha verts.push p2x + perpx, p2y + perpy verts.push r, g, b, alpha indices.push indexStart i = 0 while i < indexCount indices.push indexStart++ i++ indices.push indexStart - 1 ###* Builds a polygon to draw @static @private @method buildPoly @param graphics {Graphics} @param webGLData {Object} ### @buildPoly: (graphicsData, webGLData) -> points = graphicsData.points return if points.length < 6 verts = webGLData.points indices = webGLData.indices length = points.length / 2 color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha triangles = PolyK.Triangulate(points) vertPos = verts.length / 6 i = 0 while i < triangles.length indices.push triangles[i] + vertPos indices.push triangles[i] + vertPos indices.push triangles[i + 1] + vertPos indices.push triangles[i + 2] + vertPos indices.push triangles[i + 2] + vertPos i += 3 i = 0 while i < length verts.push points[i * 2], points[i * 2 + 1], r, g, b, alpha i++
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/webgl/GLESGraphics', [ 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/utils/PolyK' 'Coffixi/primitives/Graphics' 'Coffixi/renderers/webgl/GLESShaders' 'Coffixi/utils/Utils' ], ( Point Matrix PolyK Graphics GLESShaders Utils ) -> ###* A set of functions used by the webGL renderer to draw the primitive graphics data @class CanvasGraphics ### class GLESGraphics ###* Renders the graphics object @static @private @method renderGraphics @param graphics {Graphics} @param projection {Object} ### @renderGraphics: (graphics, projection) -> gl = @gl unless graphics._GL graphics._GL = points: [] indices: [] lastIndex: 0 buffer: gl.createBuffer() indexBuffer: gl.createBuffer() if graphics.dirty graphics.dirty = false if graphics.clearDirty graphics.clearDirty = false graphics._GL.lastIndex = 0 graphics._GL.points = [] graphics._GL.indices = [] GLESGraphics.updateGraphics graphics GLESShaders.activatePrimitiveShader gl m = Matrix.mat3.clone(graphics.worldTransform) Matrix.mat3.transpose m gl.blendFunc gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA gl.uniformMatrix3fv GLESShaders.primitiveShader.translationMatrix, false, m gl.uniform2f GLESShaders.primitiveShader.projectionVector, projection.x, projection.y gl.uniform1f GLESShaders.primitiveShader.alpha, graphics.worldAlpha gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.vertexAttribPointer GLESShaders.defaultShader.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.vertexPositionAttribute, 2, gl.FLOAT, false, 4 * 6, 0 gl.vertexAttribPointer GLESShaders.primitiveShader.colorAttribute, 4, gl.FLOAT, false, 4 * 6, 2 * 4 gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.drawElements gl.TRIANGLE_STRIP, graphics._GL.indices.length, gl.UNSIGNED_SHORT, 0 GLESShaders.activateDefaultShader gl ###* Updates the graphics object @static @private @method updateGraphics @param graphics {Graphics} ### @updateGraphics: (graphics) -> i = graphics._GL.lastIndex while i < graphics.graphicsData.length data = graphics.graphicsData[i] if data.type is Graphics.POLY GLESGraphics.buildPoly data, graphics._GL if data.points.length > 3 if data.fill GLESGraphics.buildLine data, graphics._GL if data.lineWidth > 0 else if data.type is Graphics.RECT GLESGraphics.buildRectangle data, graphics._GL else GLESGraphics.buildCircle data, graphics._GL if data.type is Graphics.CIRC or data.type is Graphics.ELIP i++ graphics._GL.lastIndex = graphics.graphicsData.length gl = @gl graphics._GL.glPoints = new Utils.Float32Array(graphics._GL.points) gl.bindBuffer gl.ARRAY_BUFFER, graphics._GL.buffer gl.bufferData gl.ARRAY_BUFFER, graphics._GL.glPoints, gl.STATIC_DRAW graphics._GL.glIndicies = new Utils.Uint16Array(graphics._GL.indices) gl.bindBuffer gl.ELEMENT_ARRAY_BUFFER, graphics._GL.indexBuffer gl.bufferData gl.ELEMENT_ARRAY_BUFFER, graphics._GL.glIndicies, gl.STATIC_DRAW ###* Builds a rectangle to draw @static @private @method buildRectangle @param graphics {Graphics} @param webGLData {Object} ### @buildRectangle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vertPos = verts.length / 6 verts.push x, y verts.push r, g, b, alpha verts.push x + width, y verts.push r, g, b, alpha verts.push x, y + height verts.push r, g, b, alpha verts.push x + width, y + height verts.push r, g, b, alpha indices.push vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3 if graphicsData.lineWidth graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y] GLESGraphics.buildLine graphicsData, webGLData ###* Builds a circle to draw @static @private @method buildCircle @param graphics {Graphics} @param webGLData {Object} ### @buildCircle: (graphicsData, webGLData) -> rectData = graphicsData.points x = rectData[0] y = rectData[1] width = rectData[2] height = rectData[3] totalSegs = 40 seg = (Math.PI * 2) / totalSegs if graphicsData.fill color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha verts = webGLData.points indices = webGLData.indices vecPos = verts.length / 6 indices.push vecPos i = 0 while i < totalSegs + 1 verts.push x, y, r, g, b, alpha verts.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha indices.push vecPos++, vecPos++ i++ indices.push vecPos - 1 if graphicsData.lineWidth graphicsData.points = [] i = 0 while i < totalSegs + 1 graphicsData.points.push x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height i++ GLESGraphics.buildLine graphicsData, webGLData ###* Builds a line to draw @static @private @method buildLine @param graphics {Graphics} @param webGLData {Object} ### @buildLine: (graphicsData, webGLData) -> wrap = true points = graphicsData.points return if points.length is 0 firstPoint = new Point(points[0], points[1]) lastPoint = new Point(points[points.length - 2], points[points.length - 1]) if firstPoint.x is lastPoint.x and firstPoint.y is lastPoint.y points.pop() points.pop() lastPoint = new Point(points[points.length - 2], points[points.length - 1]) midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5 midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5 points.unshift midPointX, midPointY points.push midPointX, midPointY verts = webGLData.points indices = webGLData.indices length = points.length / 2 indexCount = points.length indexStart = verts.length / 6 width = graphicsData.lineWidth / 2 color = Utils.HEXtoRGB(graphicsData.lineColor) alpha = graphicsData.lineAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha p1x = undefined p1y = undefined p2x = undefined p2y = undefined p3x = undefined p3y = undefined perpx = undefined perpy = undefined perp2x = undefined perp2y = undefined perp3x = undefined perp3y = undefined ipx = undefined ipy = undefined a1 = undefined b1 = undefined c1 = undefined a2 = undefined b2 = undefined c2 = undefined denom = undefined pdist = undefined dist = undefined p1x = points[0] p1y = points[1] p2x = points[2] p2y = points[3] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p1x - perpx, p1y - perpy, r, g, b, alpha verts.push p1x + perpx, p1y + perpy, r, g, b, alpha i = 1 while i < length - 1 p1x = points[(i - 1) * 2] p1y = points[(i - 1) * 2 + 1] p2x = points[(i) * 2] p2y = points[(i) * 2 + 1] p3x = points[(i + 1) * 2] p3y = points[(i + 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width perp2x = -(p2y - p3y) perp2y = p2x - p3x dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y) perp2x /= dist perp2y /= dist perp2x *= width perp2y *= width a1 = (-perpy + p1y) - (-perpy + p2y) b1 = (-perpx + p2x) - (-perpx + p1x) c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y) a2 = (-perp2y + p3y) - (-perp2y + p2y) b2 = (-perp2x + p2x) - (-perp2x + p3x) c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y) denom = a1 * b2 - a2 * b1 denom += 1 if denom is 0 px = (b1 * c2 - b2 * c1) / denom py = (a2 * c1 - a1 * c2) / denom pdist = (px - p2x) * (px - p2x) + (py - p2y) + (py - p2y) if pdist > 140 * 140 perp3x = perpx - perp2x perp3y = perpy - perp2y dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y) perp3x /= dist perp3y /= dist perp3x *= width perp3y *= width verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha verts.push p2x + perp3x, p2y + perp3y verts.push r, g, b, alpha verts.push p2x - perp3x, p2y - perp3y verts.push r, g, b, alpha indexCount++ else verts.push px, py verts.push r, g, b, alpha verts.push p2x - (px - p2x), p2y - (py - p2y) verts.push r, g, b, alpha i++ p1x = points[(length - 2) * 2] p1y = points[(length - 2) * 2 + 1] p2x = points[(length - 1) * 2] p2y = points[(length - 1) * 2 + 1] perpx = -(p1y - p2y) perpy = p1x - p2x dist = Math.sqrt(perpx * perpx + perpy * perpy) perpx /= dist perpy /= dist perpx *= width perpy *= width verts.push p2x - perpx, p2y - perpy verts.push r, g, b, alpha verts.push p2x + perpx, p2y + perpy verts.push r, g, b, alpha indices.push indexStart i = 0 while i < indexCount indices.push indexStart++ i++ indices.push indexStart - 1 ###* Builds a polygon to draw @static @private @method buildPoly @param graphics {Graphics} @param webGLData {Object} ### @buildPoly: (graphicsData, webGLData) -> points = graphicsData.points return if points.length < 6 verts = webGLData.points indices = webGLData.indices length = points.length / 2 color = Utils.HEXtoRGB(graphicsData.fillColor) alpha = graphicsData.fillAlpha r = color[0] * alpha g = color[1] * alpha b = color[2] * alpha triangles = PolyK.Triangulate(points) vertPos = verts.length / 6 i = 0 while i < triangles.length indices.push triangles[i] + vertPos indices.push triangles[i] + vertPos indices.push triangles[i + 1] + vertPos indices.push triangles[i + 2] + vertPos indices.push triangles[i + 2] + vertPos i += 3 i = 0 while i < length verts.push points[i * 2], points[i * 2 + 1], r, g, b, alpha i++
[ { "context": "# Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org>\n#\n# Permission is hereby gra", "end": 37, "score": 0.9998683929443359, "start": 21, "tag": "NAME", "value": "Paul Tagliamonte" }, { "context": "# Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org>\n#\n# ...
site/coffee/main.coffee
rwaldron/hy
0
# Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org> # # 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. theme = "elegant" HyCodeMirror = CodeMirror.fromTextArea($('#hython-target')[0], { mode: "clojure", theme: theme, autofocus: true, }) PyCodeMirror = CodeMirror($('#python-repl')[0], { mode: "python", theme: theme, readOnly: true, }) PyCodeMirror.setSize("100%", "100%") HyCodeMirror.setSize("100%", "100%") reload = -> input = HyCodeMirror.getValue() format = "h:mm:ss" $.ajax({ url: "/hy2py", type: "POST", data: {'code': input}, success: (result) -> PyCodeMirror.setValue(result) now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " updated.<br />") $("#repl-root").removeClass("error") $("#repl-root").addClass("ok") statusCode: { 500: (response) -> now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " " + response.responseText + "<br />") $("#repl-root").removeClass("ok") $("#repl-root").addClass("error") } }) $(document).ready(-> count = 0 HyCodeMirror.on("change", (instance, cob) -> count += 1 curcount = count window.setTimeout(-> if curcount == count reload() , 500) ) reload() )
61262
# Copyright (c) 2012 <NAME> <<EMAIL>> # # 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. theme = "elegant" HyCodeMirror = CodeMirror.fromTextArea($('#hython-target')[0], { mode: "clojure", theme: theme, autofocus: true, }) PyCodeMirror = CodeMirror($('#python-repl')[0], { mode: "python", theme: theme, readOnly: true, }) PyCodeMirror.setSize("100%", "100%") HyCodeMirror.setSize("100%", "100%") reload = -> input = HyCodeMirror.getValue() format = "h:mm:ss" $.ajax({ url: "/hy2py", type: "POST", data: {'code': input}, success: (result) -> PyCodeMirror.setValue(result) now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " updated.<br />") $("#repl-root").removeClass("error") $("#repl-root").addClass("ok") statusCode: { 500: (response) -> now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " " + response.responseText + "<br />") $("#repl-root").removeClass("ok") $("#repl-root").addClass("error") } }) $(document).ready(-> count = 0 HyCodeMirror.on("change", (instance, cob) -> count += 1 curcount = count window.setTimeout(-> if curcount == count reload() , 500) ) reload() )
true
# Copyright (c) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. theme = "elegant" HyCodeMirror = CodeMirror.fromTextArea($('#hython-target')[0], { mode: "clojure", theme: theme, autofocus: true, }) PyCodeMirror = CodeMirror($('#python-repl')[0], { mode: "python", theme: theme, readOnly: true, }) PyCodeMirror.setSize("100%", "100%") HyCodeMirror.setSize("100%", "100%") reload = -> input = HyCodeMirror.getValue() format = "h:mm:ss" $.ajax({ url: "/hy2py", type: "POST", data: {'code': input}, success: (result) -> PyCodeMirror.setValue(result) now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " updated.<br />") $("#repl-root").removeClass("error") $("#repl-root").addClass("ok") statusCode: { 500: (response) -> now = Date.parse("now").toString(format) $("#build-msgs").prepend(now + " " + response.responseText + "<br />") $("#repl-root").removeClass("ok") $("#repl-root").addClass("error") } }) $(document).ready(-> count = 0 HyCodeMirror.on("change", (instance, cob) -> count += 1 curcount = count window.setTimeout(-> if curcount == count reload() , 500) ) reload() )
[ { "context": "lender:', ->\n rootLevelKeys =\n name: 'myBundle'\n main: 'myMainLib'\n bundle: # 'bun", "end": 4208, "score": 0.7177014946937561, "start": 4200, "tag": "USERNAME", "value": "myBundle" }, { "context": " result,\n bundle:\n ...
source/spec/config/blendConfigs-spec.coffee
gaybro8777/uRequire
103
blendConfigs = require '../../code/config/blendConfigs' MasterDefaultsConfig = require '../../code/config/MasterDefaultsConfig' { moveKeysBlender depracatedKeysBlender templateBlender dependenciesBindingsBlender bundleBuildBlender shimBlender watchBlender } = blendConfigs arrayizePushBlender = new _B.ArrayizeBlender ResourceConverter = require '../../code/config/ResourceConverter' resources = [ [ '$+cofreescript' # a title of the resource (a module since its starting with '$', running after adjusting module info cause of '+') [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] (source) -> source (filename) -> filename.replace '.coffee', '.js' # dummy filename converter {some: coffee: 'options'} ] [ '~Streamline' # a title of the resource (without type since its not in [@ # $], but with isAfterTemplate:true due to '!' (runs only on Modules) 'I am the Streamline descr' # a descr (String) at pos 1 '**/*._*' # even if we have a String as an implied `filez` array (source) -> source (filename) -> filename.replace '._js', '.js' # dummy filename converter ] { name: '#|NonModule' #a non-module TextResource (starting with '#'), isTerminal:true (starting with '|') filez: '**/*.nonmodule' convert: -> } [ '@~AFileResource' #a FileResource (@) isMatchSrcFilename:true (~) '**/*.ext' # this is a `filez`, not a descr if pos 1 isString & pos 2 not a String|Array|RegExp -> { some: options: after: 'convert' } ] { name: '#IamAFalseModule' # A TextResource (starting with '#') #type: 'module' # this is not respected, over flag starting with '#' filez: '**/*.module' convert: -> } -> rc = @ 'cofreescript' # retrieve a registered RC rc.name = 'coffeescript' # change its name rc # add it to 'resources' at this point, but remove it from where it was ] expectedResources = [ # coff(r)eescript is removed from here, since only the last one instance declared remains { ' name': 'Streamline' descr: 'I am the Streamline descr' filez: '**/*._*' convert: resources[1][3] ' convFilename': resources[1][4] _convFilename: resources[1][4] isTerminal: false isMatchSrcFilename: true runAt: '' enabled: true options: {} } { ' name': 'NonModule' descr: 'No descr for ResourceConverter \'NonModule\'' filez: '**/*.nonmodule' convert: resources[2].convert ' type': 'text' isTerminal: true isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'AFileResource' descr: 'No descr for ResourceConverter \'AFileResource\'' filez: '**/*.ext' convert: resources[3][2] ' type': 'file' isTerminal: false isMatchSrcFilename:true runAt: '' enabled: true options: { some: options: after: 'convert' } } { ' name': 'IamAFalseModule' descr: 'No descr for ResourceConverter \'IamAFalseModule\'' filez: '**/*.module' convert: resources[4].convert ' type': 'text' isTerminal: false isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'coffeescript' # name is changed descr: 'No descr for ResourceConverter \'cofreescript\'', filez: [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] convert: resources[0][2] ' convFilename': resources[0][3] _convFilename: resources[0][3] ' type': 'module' isTerminal: false isMatchSrcFilename: false runAt: 'beforeTemplate' enabled: true options: {some: coffee: 'options'} } ] describe "blendConfigs handles all config nesting / blending / derivation, moving & depracted keys", -> describe '`MasterDefaultsConfig` consistency', -> it "No same name keys in bundle & build ", -> ok _B.isDisjoint _.keys(MasterDefaultsConfig.bundle), _.keys(MasterDefaultsConfig.build) describe 'blendConfigs & its Blenders: ', -> describe 'moveKeysBlender:', -> rootLevelKeys = name: 'myBundle' main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild:-> result = moveKeysBlender.blend rootLevelKeys it "result is NOT the srcObject", -> notEqual result, rootLevelKeys it "Copies keys from the 'root' of src, to either `dst.bundle` or `dst.build`, depending on where keys are on `MasterDefaultsConfig`", -> deepEqual result, bundle: name: 'myBundle' main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} build: dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild: rootLevelKeys.afterBuild it "it gives precedence to items in 'bundle' and 'build' hashes, over root items.", -> deepEqual moveKeysBlender.blend( main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' dstPath: "/some/OTHER/path" build: # 'bundle' and 'build' hashes have precedence over root items dstPath: "/some/path" ) , bundle: main: 'myLib' build: dstPath: "/some/path" it "ignores root keys deemed irrelevant (not exist on `MasterDefaultsConfig`'s `.build` or `.bundle`.)", -> deepEqual moveKeysBlender.blend( iRReLeVaNt_key_is_Ignored: true name: 'myBundle' bundle: # root items have precedence over 'bundle' and 'build' hashes. bundle_iRReLeVaNt_key_is_NOT_Ignored: true path: "/some/path" ) , bundle: bundle_iRReLeVaNt_key_is_NOT_Ignored: true name: 'myBundle' path: "/some/path" describe "depracatedKeysBlender:", -> it "renames DEPRACATED keys to their new name", -> oldCfg = bundle: bundlePath: "source/code" main: "index" filespecs: '*.*' ignore: [/^draft/] # ignore not handled in depracatedKeysBlender dependencies: noWeb: 'util' bundleExports: {lodash:'_'} _knownVariableNames: {jquery:'$'} build: noRootExports: true exportsRoot: ['script', 'AMD'] deepEqual depracatedKeysBlender.blend(oldCfg), bundle: path: 'source/code' main: 'index' filez: '*.*', ignore: [ /^draft/ ] dependencies: node: 'util' imports: { lodash: '_' } _knownDepsVars: { jquery: '$'} build: rootExports: ignore: true runtimes: ['script', 'AMD'] describe "templateBlender:", -> describe "template is a String:", -> it "converts to {name:'TheString'} ", -> deepEqual templateBlender.blend('UMD'), {name: 'UMD'} it "converts & blends to {name:'TheString'} ", -> deepEqual templateBlender.blend( {} # useless {name:'UMD', otherRandomOption: 'someRandomValue'} {} 'UMD' ) , name: 'UMD' otherRandomOption: 'someRandomValue' describe "template is {}:", -> it "blends to existing ", -> deepEqual templateBlender.blend( {} {name: 'UMD', otherRandomOption: 'someRandomValue'} {} {name: 'UMD'} ) , name: 'UMD' otherRandomOption: 'someRandomValue' describe "blending config with ResourceConverters :", -> resultRCsCfg = null rcNames = null before -> resultRCsCfg = blendConfigs [{resources}] rcNames = _.map resultRCsCfg.bundle.resources, (rc) -> rc[' name'] it "converts array of RC-specs' into array of RC-instances:", -> deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-specs can be an array of (registered) RC-names:", -> resultRCsCfg = blendConfigs [{resources:rcNames}] deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-names reversed results to reversed RC-instances:", -> reversedRCs = blendConfigs [{resources: _(rcNames).clone().reverse()}] deepEqual reversedRCs.bundle.resources, _(expectedResources).clone().reverse() describe "dependenciesBindingsBlender converts to proper dependenciesBinding structure:", -> it "converts undefined to an empty {}", -> deepEqual dependenciesBindingsBlender.blend(undefined), {} it "converts String: `'lodash'` ---> `{lodash:[]}`", -> deepEqual dependenciesBindingsBlender.blend('lodash'), {lodash:[]} it "converts Strings, ignoring all other non {}, []: ", -> deepEqual dependenciesBindingsBlender.blend( {knockout:['ko']}, 'lodash', 'jquery', undefined, /./, 123, true, false, null ), knockout:['ko'], lodash:[], jquery:[] it "converts Array<String>: `['lodash', 'jquery']` ---> `{lodash:[], jquery:[]}`", -> deepEqual dependenciesBindingsBlender.blend( ['lodash', 'jquery'] ), {lodash: [], jquery: []} deepEqual dependenciesBindingsBlender.blend( {lodash: '_', knockout:['ko']}, ['lodash', 'jquery'] ), lodash: ['_'], knockout:['ko'], jquery: [] it "converts Object {lodash:['_'], jquery: '$'}` = {lodash:['_'], jquery: ['$']}`", -> deepEqual dependenciesBindingsBlender.blend( lodash: ['_'] #as is jquery: '$' #arrayized ), lodash:['_'] jquery: ['$'] it "blends {lodash:['_'], jquery: ['$']} <-- {knockout:['ko'], jquery: ['jQuery']}`", -> deepEqual dependenciesBindingsBlender.blend( {lodash:'_', jquery: ['jQuery', 'jquery']}, {knockout:['ko', 'Knockout'], jquery: '$'} ), lodash: ['_'] knockout: ['ko', 'Knockout'] jquery: ['$', 'jQuery', 'jquery'] it "converts from all in chain ", -> deepEqual dependenciesBindingsBlender.blend( {}, 'myLib', {lodash:['_'], jquery: 'jQuery'} ['uberscore', 'uderive'] jquery: '$' 'urequire' 'uberscore': ['rules'] ), myLib: [] lodash: ['_'] jquery: ['$', 'jQuery'] uberscore: ['rules'] uderive: [] urequire: [] describe "`blendConfigs`:", -> describe "`bundle: dependencies`:", -> it "imports String depBindings is turned to {dep:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: 'lodash' ] ), bundle: dependencies: imports: 'lodash': [] exports: {} #todo: omit it "exports: bundle Array<String> depBindings is turned to {dep1:[], dep2:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: ['lodash', 'jquery']] ), bundle: dependencies: imports: 'lodash': [] 'jquery': [] exports: {} #todo: omit it "exports: bundle {} - depBindings is `arrayize`d", -> deepEqual blendConfigs( [ dependencies: exports: bundle: {'lodash': '_'} ] ), bundle: dependencies: imports: {'lodash': ['_']} exports: {} #todo: omit it "exports: bundle {} - depBinding reseting its array", -> deepEqual blendConfigs([ {} {dependencies: exports: bundle: {'uberscore': [[null], '_B']}} {} {dependencies: exports: bundle: {'uberscore': ['uberscore', 'uuuuB']}} ] ), bundle: dependencies: imports: {'uberscore': ['_B']} exports: {} #todo: omit describe "`build: watch` & watchBlender :", -> describe "as a Number:", -> it "becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: 123} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend(123), expected describe "as a String:", -> it "parsed as a Number, becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: '123'} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend('123'), expected it "parsed as a Number/String, overwrite debounceDelay", -> deepEqual blendConfigs( [ {watch: '123'}, {watch: 456}, {watch: info: 'grunt'} ]), build: watch: expected = debounceDelay: 123 enabled: true info: 'grunt' deepEqual watchBlender.blend(456, '123', info:'grunt'), expected describe "not parsed as a Number:", -> it "becomes info", -> deepEqual blendConfigs( [ {build: watch: 'not number'} ]), build: watch: expected = info: 'not number' enabled: true deepEqual watchBlender.blend('not number'), expected it "becomes info, blended into existing watch {}", -> deepEqual blendConfigs( [ {build: watch: '123'}, {build: watch: 'not number'} ]), build: watch: expected = debounceDelay: 123 info: 'not number' enabled: true deepEqual watchBlender.blend({}, 'not number', '123'), expected # todo: allow without {} describe "as boolean:", -> it "overwrites enabled", -> deepEqual blendConfigs( [{ build: watch: false }]), build: watch: enabled: false it "overwrites enabled, keeps other keys", -> deepEqual blendConfigs( [{ build: watch: false }, {build: watch: '123'}, {build: watch: 'not number'}]), build: watch: enabled: false debounceDelay: 123 info: 'not number' describe "as Object:", -> it "copies keys and set `enable:true`, if not `enabled: false` is passed", -> deepEqual blendConfigs( [ watch: info: 'grunt' ]), build: watch: info: 'grunt' enabled: true it "copies keys and resets exising `enabled: false` value", -> deepEqual blendConfigs( [ {watch: info: 'some other'} {watch: info: 'grunt', enabled: false} true ]), build: watch: info: 'some other' enabled: true describe "concats arrays of `before` / `after`, having split them if they are strings:", -> input =[ { after: 'da asda' files: ['another/path'] } {info: 'grunt'} { after: ['1','2','3'] files: 'some/path' } ] expected = enabled: true after: [ '1', '2', '3','da', 'asda' ] files: ['some/path', 'another/path'] info: 'grunt' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "shallow copies / overwrites keys", -> anObj = rootKey: nested: key: someValue: 'someValue' aFn: -> input = [ anObj false 'not number' '123' info: 'grunt' ] expected = rootKey: anObj.rootKey enabled: true debounceDelay: 123 info: 'not number' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "`build: optimize`:", -> describe "true:", -> it "becomes `uglify2`", -> deepEqual blendConfigs( [ {build: optimize: true} ]), build: optimize: 'uglify2' describe "an object with `uglify2` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify2': {some: 'options'} } ]), build: optimize: 'uglify2' uglify2: {some: 'options'} describe "an object with `uglify` key:", -> it "becomes `build: uglify: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify': {some: 'options'} } ]), build: optimize: 'uglify' 'uglify': {some: 'options'} describe "an object with `unknown` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'unknown': {some: 'options'} } ]), build: optimize: 'uglify2' describe "`build: rjs: shim` & shimBlender:", -> it.skip "throws with unknown shims", -> #todo: fix throwing while blending breaks RCs expect(-> blendConfigs [ rjs: shim: 'string'] ).to.throw /Unknown shim/ describe "`amodule: ['somedep']` becomes { amodule: { deps:['somedep'] } }", -> input = amodule: ['somedep'] anotherModule: deps: ['someOtherdep'] expected = amodule: deps: ['somedep'] anotherModule: deps: ['someOtherdep'] it "with blendConfig: ", -> deepEqual blendConfigs( [ rjs: shim: input ]),build: rjs: shim: expected it "with shimBlender : ", -> deepEqual shimBlender.blend(input), expected describe "missing deps are added to array if missing:", -> inputs = [ {amodule: {deps: ['somedep'], exports: 'finalExports'}} {amodule: ['someOtherdep', 'somedep', 'missingDep']} { amodule: {deps: ['lastDep'], exports: 'dummy'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} } ] expected = amodule: {deps: ['somedep', 'someOtherdep', 'missingDep', 'lastDep'], exports: 'finalExports'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} it "with blendConfig: ", -> deepEqual blendConfigs( _.map inputs, (s) -> rjs: shim: s), build: rjs: shim: expected it "with shimBlender (in reverse order): ", -> deepEqual shimBlender.blend.apply(null, inputs.reverse()), expected describe "Nested & derived configs:", -> configs = [ {} , dependencies: node: ['fs'] exports: bundle: (parent) -> parent.lodash = ["_"] parent.backbone = ['Backbone', 'BB'] parent filez: (parentArray) -> # [ '**/*.coffee.md', '**/*.ls'] parentArray.push p for p in [ '**/*.coffee.md', '**/*.ls'] parentArray copy: /./ dstPath: "build/code" template: 'UMD' # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-child.js'] bare: true runtimeInfo: ['runtimeInfo-child.js'] optimize: 'uglify2': {some: 'options'} done: -> , bundle: path: "source/code" filez: ['**/*.litcoffee'] # added at pos 1 copy: ['**/*.html'] ignore: [/^draft/] # negated with '!' and added at pos 2 & 3 dependencies: node: 'util' paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js'] # unshifted, not pushed! imports: uberscore: [[null], '_B'] #reseting existing (derived/inherited) array, allowing only '_B' rootExports: 'index': 'globalVal' verbose: true afterBuild: -> derive: debugLevel: 90 , {} , # DEPRACATED keys bundlePath: "sourceSpecDir" main: 'index' filespecs: '**/*' # arrayized and added at pos 0 resources: resources[2..] dependencies: variableNames: uberscore: '_B' bundleExports: chai: 'chai' build: noRootExports: ['some/module/path'] # renamed to `rootExports: ignore` rootExports: runtimes: ['script', 'AMD'] , dependencies: # `exports: bundle:` & `bundleExports:` can't appear together! exports: bundle: uberscore: ['uberscore', 'B', 'B_'] # reset above 'spec-data': 'data' build: rootExports: ignore: ['some/other/module/path'] # preceding the above (deprecated) `noRootExports` runtimes: ['node'] # overwritten above dstPath: "some/useless/default/path" , {dependencies: bundleExports: ['backbone', 'unusedDep']} , {dependencies: imports: 'dummyDep': 'dummyDepVar'} , template: 'AMD' # test arraysConcatOrOverwrite useStrict: true globalWindow: [[null], 'globalWindow-inherited.js'] bare: ['bare-inherited-and-ignored2.js'] runtimeInfo: ['runtimeInfo-inherited.js'] , derive: [ dependencies: exports: bundle: 'spec-data': ['dataInDerive1', 'dataInDerive1-1'] , derive: derive: resources: resources[0..1] derive: copy: (pa) -> pa.push '!**/*'; pa template: name: 'combined' someOption: 'someOption' # value is preserved, even if name changes. dependencies: exports: bundle: 'spec-data': 'dataInDerive2' paths: override: lodash: 'node_modules/lodash/lodash.js' verbose: false # test arraysConcatOrOverwrite globalWindow: ['globalWindow-reseted.js'] bare: ['bare-inherited-and-ignored.js'] runtimeInfo: false ] ] configsClone = _.clone configs, true blended = blendConfigs configs it "blending doesn't mutate source configs:", -> deepEqual configs, configsClone it "correctly derives from many & nested user configs:", -> deepEqual blended, bundle: path: "source/code" main: "index" filez: [ '**/*' # comes from last config with filez '**/*.litcoffee' '!', /^draft/ # comes from DEPRACATED ignore: [/^draft/] '**/*.coffee.md' # comes from first (highest precedence) config '**/*.ls' # as above ] copy: ['!**/*', '**/*.html', /./] resources: expectedResources dependencies: paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js' 'node_modules/lodash/lodash.js'] node: ['util', 'fs'] rootExports: 'index': ['globalVal'] imports: 'spec-data': ['data', 'dataInDerive1', 'dataInDerive1-1', 'dataInDerive2'] chai: ['chai'] uberscore: ['_B'] lodash: ['_'] backbone: ['Backbone', 'BB'] unusedDep: [] dummyDep: ['dummyDepVar'] exports: {} #todo: omit depsVars: uberscore: ['_B'] build: verbose: true dstPath: "build/code" debugLevel: 90 template: name: "UMD" someOption: 'someOption' rootExports: ignore: ['some/other/module/path', 'some/module/path'] runtimes: ['script', 'AMD'] # overwrites ['node'] # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-inherited.js', 'globalWindow-child.js'] bare: true optimize: 'uglify2' uglify2: {some: 'options'} runtimeInfo: ['runtimeInfo-inherited.js', 'runtimeInfo-child.js'] afterBuild: [configs[2].afterBuild, configs[1].done] it "all {} in bundle.resources are instanceof ResourceConverter :", -> for resConv in blended.bundle.resources ok resConv instanceof ResourceConverter it "`bundle.resources` are reset with [null] as 1st item", -> freshResources = blendConfigs [{resources:[ [null], expectedResources[0]]}, blended] blended.bundle.resources = [expectedResources[0]] deepEqual freshResources, blended
131193
blendConfigs = require '../../code/config/blendConfigs' MasterDefaultsConfig = require '../../code/config/MasterDefaultsConfig' { moveKeysBlender depracatedKeysBlender templateBlender dependenciesBindingsBlender bundleBuildBlender shimBlender watchBlender } = blendConfigs arrayizePushBlender = new _B.ArrayizeBlender ResourceConverter = require '../../code/config/ResourceConverter' resources = [ [ '$+cofreescript' # a title of the resource (a module since its starting with '$', running after adjusting module info cause of '+') [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] (source) -> source (filename) -> filename.replace '.coffee', '.js' # dummy filename converter {some: coffee: 'options'} ] [ '~Streamline' # a title of the resource (without type since its not in [@ # $], but with isAfterTemplate:true due to '!' (runs only on Modules) 'I am the Streamline descr' # a descr (String) at pos 1 '**/*._*' # even if we have a String as an implied `filez` array (source) -> source (filename) -> filename.replace '._js', '.js' # dummy filename converter ] { name: '#|NonModule' #a non-module TextResource (starting with '#'), isTerminal:true (starting with '|') filez: '**/*.nonmodule' convert: -> } [ '@~AFileResource' #a FileResource (@) isMatchSrcFilename:true (~) '**/*.ext' # this is a `filez`, not a descr if pos 1 isString & pos 2 not a String|Array|RegExp -> { some: options: after: 'convert' } ] { name: '#IamAFalseModule' # A TextResource (starting with '#') #type: 'module' # this is not respected, over flag starting with '#' filez: '**/*.module' convert: -> } -> rc = @ 'cofreescript' # retrieve a registered RC rc.name = 'coffeescript' # change its name rc # add it to 'resources' at this point, but remove it from where it was ] expectedResources = [ # coff(r)eescript is removed from here, since only the last one instance declared remains { ' name': 'Streamline' descr: 'I am the Streamline descr' filez: '**/*._*' convert: resources[1][3] ' convFilename': resources[1][4] _convFilename: resources[1][4] isTerminal: false isMatchSrcFilename: true runAt: '' enabled: true options: {} } { ' name': 'NonModule' descr: 'No descr for ResourceConverter \'NonModule\'' filez: '**/*.nonmodule' convert: resources[2].convert ' type': 'text' isTerminal: true isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'AFileResource' descr: 'No descr for ResourceConverter \'AFileResource\'' filez: '**/*.ext' convert: resources[3][2] ' type': 'file' isTerminal: false isMatchSrcFilename:true runAt: '' enabled: true options: { some: options: after: 'convert' } } { ' name': 'IamAFalseModule' descr: 'No descr for ResourceConverter \'IamAFalseModule\'' filez: '**/*.module' convert: resources[4].convert ' type': 'text' isTerminal: false isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'coffeescript' # name is changed descr: 'No descr for ResourceConverter \'cofreescript\'', filez: [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] convert: resources[0][2] ' convFilename': resources[0][3] _convFilename: resources[0][3] ' type': 'module' isTerminal: false isMatchSrcFilename: false runAt: 'beforeTemplate' enabled: true options: {some: coffee: 'options'} } ] describe "blendConfigs handles all config nesting / blending / derivation, moving & depracted keys", -> describe '`MasterDefaultsConfig` consistency', -> it "No same name keys in bundle & build ", -> ok _B.isDisjoint _.keys(MasterDefaultsConfig.bundle), _.keys(MasterDefaultsConfig.build) describe 'blendConfigs & its Blenders: ', -> describe 'moveKeysBlender:', -> rootLevelKeys = name: 'myBundle' main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild:-> result = moveKeysBlender.blend rootLevelKeys it "result is NOT the srcObject", -> notEqual result, rootLevelKeys it "Copies keys from the 'root' of src, to either `dst.bundle` or `dst.build`, depending on where keys are on `MasterDefaultsConfig`", -> deepEqual result, bundle: name: '<NAME>Bundle' main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} build: dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild: rootLevelKeys.afterBuild it "it gives precedence to items in 'bundle' and 'build' hashes, over root items.", -> deepEqual moveKeysBlender.blend( main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' dstPath: "/some/OTHER/path" build: # 'bundle' and 'build' hashes have precedence over root items dstPath: "/some/path" ) , bundle: main: 'myLib' build: dstPath: "/some/path" it "ignores root keys deemed irrelevant (not exist on `MasterDefaultsConfig`'s `.build` or `.bundle`.)", -> deepEqual moveKeysBlender.blend( iRReLeVaNt_key_is_Ignored: true name: 'myBundle' bundle: # root items have precedence over 'bundle' and 'build' hashes. bundle_iRReLeVaNt_key_is_NOT_Ignored: true path: "/some/path" ) , bundle: bundle_iRReLeVaNt_key_is_NOT_Ignored: true name: 'myBundle' path: "/some/path" describe "depracatedKeysBlender:", -> it "renames DEPRACATED keys to their new name", -> oldCfg = bundle: bundlePath: "source/code" main: "index" filespecs: '*.*' ignore: [/^draft/] # ignore not handled in depracatedKeysBlender dependencies: noWeb: 'util' bundleExports: {lodash:'_'} _knownVariableNames: {jquery:'$'} build: noRootExports: true exportsRoot: ['script', 'AMD'] deepEqual depracatedKeysBlender.blend(oldCfg), bundle: path: 'source/code' main: 'index' filez: '*.*', ignore: [ /^draft/ ] dependencies: node: 'util' imports: { lodash: '_' } _knownDepsVars: { jquery: '$'} build: rootExports: ignore: true runtimes: ['script', 'AMD'] describe "templateBlender:", -> describe "template is a String:", -> it "converts to {name:'TheString'} ", -> deepEqual templateBlender.blend('UMD'), {name: 'UMD'} it "converts & blends to {name:'TheString'} ", -> deepEqual templateBlender.blend( {} # useless {name:'<NAME>D', otherRandomOption: 'someRandomValue'} {} 'UMD' ) , name: '<NAME>D' otherRandomOption: 'someRandomValue' describe "template is {}:", -> it "blends to existing ", -> deepEqual templateBlender.blend( {} {name: '<NAME>D', otherRandomOption: 'someRandomValue'} {} {name: '<NAME>D'} ) , name: '<NAME>D' otherRandomOption: 'someRandomValue' describe "blending config with ResourceConverters :", -> resultRCsCfg = null rcNames = null before -> resultRCsCfg = blendConfigs [{resources}] rcNames = _.map resultRCsCfg.bundle.resources, (rc) -> rc[' name'] it "converts array of RC-specs' into array of RC-instances:", -> deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-specs can be an array of (registered) RC-names:", -> resultRCsCfg = blendConfigs [{resources:rcNames}] deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-names reversed results to reversed RC-instances:", -> reversedRCs = blendConfigs [{resources: _(rcNames).clone().reverse()}] deepEqual reversedRCs.bundle.resources, _(expectedResources).clone().reverse() describe "dependenciesBindingsBlender converts to proper dependenciesBinding structure:", -> it "converts undefined to an empty {}", -> deepEqual dependenciesBindingsBlender.blend(undefined), {} it "converts String: `'lodash'` ---> `{lodash:[]}`", -> deepEqual dependenciesBindingsBlender.blend('lodash'), {lodash:[]} it "converts Strings, ignoring all other non {}, []: ", -> deepEqual dependenciesBindingsBlender.blend( {knockout:['ko']}, 'lodash', 'jquery', undefined, /./, 123, true, false, null ), knockout:['ko'], lodash:[], jquery:[] it "converts Array<String>: `['lodash', 'jquery']` ---> `{lodash:[], jquery:[]}`", -> deepEqual dependenciesBindingsBlender.blend( ['lodash', 'jquery'] ), {lodash: [], jquery: []} deepEqual dependenciesBindingsBlender.blend( {lodash: '_', knockout:['ko']}, ['lodash', 'jquery'] ), lodash: ['_'], knockout:['ko'], jquery: [] it "converts Object {lodash:['_'], jquery: '$'}` = {lodash:['_'], jquery: ['$']}`", -> deepEqual dependenciesBindingsBlender.blend( lodash: ['_'] #as is jquery: '$' #arrayized ), lodash:['_'] jquery: ['$'] it "blends {lodash:['_'], jquery: ['$']} <-- {knockout:['ko'], jquery: ['jQuery']}`", -> deepEqual dependenciesBindingsBlender.blend( {lodash:'_', jquery: ['jQuery', 'jquery']}, {knockout:['ko', 'Knockout'], jquery: '$'} ), lodash: ['_'] knockout: ['ko', 'Knockout'] jquery: ['$', 'jQuery', 'jquery'] it "converts from all in chain ", -> deepEqual dependenciesBindingsBlender.blend( {}, 'myLib', {lodash:['_'], jquery: 'jQuery'} ['uberscore', 'uderive'] jquery: '$' 'urequire' 'uberscore': ['rules'] ), myLib: [] lodash: ['_'] jquery: ['$', 'jQuery'] uberscore: ['rules'] uderive: [] urequire: [] describe "`blendConfigs`:", -> describe "`bundle: dependencies`:", -> it "imports String depBindings is turned to {dep:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: 'lodash' ] ), bundle: dependencies: imports: 'lodash': [] exports: {} #todo: omit it "exports: bundle Array<String> depBindings is turned to {dep1:[], dep2:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: ['lodash', 'jquery']] ), bundle: dependencies: imports: 'lodash': [] 'jquery': [] exports: {} #todo: omit it "exports: bundle {} - depBindings is `arrayize`d", -> deepEqual blendConfigs( [ dependencies: exports: bundle: {'lodash': '_'} ] ), bundle: dependencies: imports: {'lodash': ['_']} exports: {} #todo: omit it "exports: bundle {} - depBinding reseting its array", -> deepEqual blendConfigs([ {} {dependencies: exports: bundle: {'uberscore': [[null], '_B']}} {} {dependencies: exports: bundle: {'uberscore': ['uberscore', 'uuuuB']}} ] ), bundle: dependencies: imports: {'uberscore': ['_B']} exports: {} #todo: omit describe "`build: watch` & watchBlender :", -> describe "as a Number:", -> it "becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: 123} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend(123), expected describe "as a String:", -> it "parsed as a Number, becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: '123'} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend('123'), expected it "parsed as a Number/String, overwrite debounceDelay", -> deepEqual blendConfigs( [ {watch: '123'}, {watch: 456}, {watch: info: 'grunt'} ]), build: watch: expected = debounceDelay: 123 enabled: true info: 'grunt' deepEqual watchBlender.blend(456, '123', info:'grunt'), expected describe "not parsed as a Number:", -> it "becomes info", -> deepEqual blendConfigs( [ {build: watch: 'not number'} ]), build: watch: expected = info: 'not number' enabled: true deepEqual watchBlender.blend('not number'), expected it "becomes info, blended into existing watch {}", -> deepEqual blendConfigs( [ {build: watch: '123'}, {build: watch: 'not number'} ]), build: watch: expected = debounceDelay: 123 info: 'not number' enabled: true deepEqual watchBlender.blend({}, 'not number', '123'), expected # todo: allow without {} describe "as boolean:", -> it "overwrites enabled", -> deepEqual blendConfigs( [{ build: watch: false }]), build: watch: enabled: false it "overwrites enabled, keeps other keys", -> deepEqual blendConfigs( [{ build: watch: false }, {build: watch: '123'}, {build: watch: 'not number'}]), build: watch: enabled: false debounceDelay: 123 info: 'not number' describe "as Object:", -> it "copies keys and set `enable:true`, if not `enabled: false` is passed", -> deepEqual blendConfigs( [ watch: info: 'grunt' ]), build: watch: info: 'grunt' enabled: true it "copies keys and resets exising `enabled: false` value", -> deepEqual blendConfigs( [ {watch: info: 'some other'} {watch: info: 'grunt', enabled: false} true ]), build: watch: info: 'some other' enabled: true describe "concats arrays of `before` / `after`, having split them if they are strings:", -> input =[ { after: 'da asda' files: ['another/path'] } {info: 'grunt'} { after: ['1','2','3'] files: 'some/path' } ] expected = enabled: true after: [ '1', '2', '3','da', 'asda' ] files: ['some/path', 'another/path'] info: 'grunt' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "shallow copies / overwrites keys", -> anObj = rootKey: nested: key: someValue: 'someValue' aFn: -> input = [ anObj false 'not number' '123' info: 'grunt' ] expected = rootKey: anObj.rootKey enabled: true debounceDelay: 123 info: 'not number' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "`build: optimize`:", -> describe "true:", -> it "becomes `uglify2`", -> deepEqual blendConfigs( [ {build: optimize: true} ]), build: optimize: 'uglify2' describe "an object with `uglify2` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify2': {some: 'options'} } ]), build: optimize: 'uglify2' uglify2: {some: 'options'} describe "an object with `uglify` key:", -> it "becomes `build: uglify: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify': {some: 'options'} } ]), build: optimize: 'uglify' 'uglify': {some: 'options'} describe "an object with `unknown` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'unknown': {some: 'options'} } ]), build: optimize: 'uglify2' describe "`build: rjs: shim` & shimBlender:", -> it.skip "throws with unknown shims", -> #todo: fix throwing while blending breaks RCs expect(-> blendConfigs [ rjs: shim: 'string'] ).to.throw /Unknown shim/ describe "`amodule: ['somedep']` becomes { amodule: { deps:['somedep'] } }", -> input = amodule: ['somedep'] anotherModule: deps: ['someOtherdep'] expected = amodule: deps: ['somedep'] anotherModule: deps: ['someOtherdep'] it "with blendConfig: ", -> deepEqual blendConfigs( [ rjs: shim: input ]),build: rjs: shim: expected it "with shimBlender : ", -> deepEqual shimBlender.blend(input), expected describe "missing deps are added to array if missing:", -> inputs = [ {amodule: {deps: ['somedep'], exports: 'finalExports'}} {amodule: ['someOtherdep', 'somedep', 'missingDep']} { amodule: {deps: ['lastDep'], exports: 'dummy'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} } ] expected = amodule: {deps: ['somedep', 'someOtherdep', 'missingDep', 'lastDep'], exports: 'finalExports'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} it "with blendConfig: ", -> deepEqual blendConfigs( _.map inputs, (s) -> rjs: shim: s), build: rjs: shim: expected it "with shimBlender (in reverse order): ", -> deepEqual shimBlender.blend.apply(null, inputs.reverse()), expected describe "Nested & derived configs:", -> configs = [ {} , dependencies: node: ['fs'] exports: bundle: (parent) -> parent.lodash = ["_"] parent.backbone = ['Backbone', 'BB'] parent filez: (parentArray) -> # [ '**/*.coffee.md', '**/*.ls'] parentArray.push p for p in [ '**/*.coffee.md', '**/*.ls'] parentArray copy: /./ dstPath: "build/code" template: 'UMD' # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-child.js'] bare: true runtimeInfo: ['runtimeInfo-child.js'] optimize: 'uglify2': {some: 'options'} done: -> , bundle: path: "source/code" filez: ['**/*.litcoffee'] # added at pos 1 copy: ['**/*.html'] ignore: [/^draft/] # negated with '!' and added at pos 2 & 3 dependencies: node: 'util' paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js'] # unshifted, not pushed! imports: uberscore: [[null], '_B'] #reseting existing (derived/inherited) array, allowing only '_B' rootExports: 'index': 'globalVal' verbose: true afterBuild: -> derive: debugLevel: 90 , {} , # DEPRACATED keys bundlePath: "sourceSpecDir" main: 'index' filespecs: '**/*' # arrayized and added at pos 0 resources: resources[2..] dependencies: variableNames: uberscore: '_B' bundleExports: chai: 'chai' build: noRootExports: ['some/module/path'] # renamed to `rootExports: ignore` rootExports: runtimes: ['script', 'AMD'] , dependencies: # `exports: bundle:` & `bundleExports:` can't appear together! exports: bundle: uberscore: ['uberscore', 'B', 'B_'] # reset above 'spec-data': 'data' build: rootExports: ignore: ['some/other/module/path'] # preceding the above (deprecated) `noRootExports` runtimes: ['node'] # overwritten above dstPath: "some/useless/default/path" , {dependencies: bundleExports: ['backbone', 'unusedDep']} , {dependencies: imports: 'dummyDep': 'dummyDepVar'} , template: 'AMD' # test arraysConcatOrOverwrite useStrict: true globalWindow: [[null], 'globalWindow-inherited.js'] bare: ['bare-inherited-and-ignored2.js'] runtimeInfo: ['runtimeInfo-inherited.js'] , derive: [ dependencies: exports: bundle: 'spec-data': ['dataInDerive1', 'dataInDerive1-1'] , derive: derive: resources: resources[0..1] derive: copy: (pa) -> pa.push '!**/*'; pa template: name: 'combined' someOption: 'someOption' # value is preserved, even if name changes. dependencies: exports: bundle: 'spec-data': 'dataInDerive2' paths: override: lodash: 'node_modules/lodash/lodash.js' verbose: false # test arraysConcatOrOverwrite globalWindow: ['globalWindow-reseted.js'] bare: ['bare-inherited-and-ignored.js'] runtimeInfo: false ] ] configsClone = _.clone configs, true blended = blendConfigs configs it "blending doesn't mutate source configs:", -> deepEqual configs, configsClone it "correctly derives from many & nested user configs:", -> deepEqual blended, bundle: path: "source/code" main: "index" filez: [ '**/*' # comes from last config with filez '**/*.litcoffee' '!', /^draft/ # comes from DEPRACATED ignore: [/^draft/] '**/*.coffee.md' # comes from first (highest precedence) config '**/*.ls' # as above ] copy: ['!**/*', '**/*.html', /./] resources: expectedResources dependencies: paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js' 'node_modules/lodash/lodash.js'] node: ['util', 'fs'] rootExports: 'index': ['globalVal'] imports: 'spec-data': ['data', 'dataInDerive1', 'dataInDerive1-1', 'dataInDerive2'] chai: ['chai'] uberscore: ['_B'] lodash: ['_'] backbone: ['Backbone', 'BB'] unusedDep: [] dummyDep: ['dummyDepVar'] exports: {} #todo: omit depsVars: uberscore: ['_B'] build: verbose: true dstPath: "build/code" debugLevel: 90 template: name: "UMD" someOption: 'someOption' rootExports: ignore: ['some/other/module/path', 'some/module/path'] runtimes: ['script', 'AMD'] # overwrites ['node'] # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-inherited.js', 'globalWindow-child.js'] bare: true optimize: 'uglify2' uglify2: {some: 'options'} runtimeInfo: ['runtimeInfo-inherited.js', 'runtimeInfo-child.js'] afterBuild: [configs[2].afterBuild, configs[1].done] it "all {} in bundle.resources are instanceof ResourceConverter :", -> for resConv in blended.bundle.resources ok resConv instanceof ResourceConverter it "`bundle.resources` are reset with [null] as 1st item", -> freshResources = blendConfigs [{resources:[ [null], expectedResources[0]]}, blended] blended.bundle.resources = [expectedResources[0]] deepEqual freshResources, blended
true
blendConfigs = require '../../code/config/blendConfigs' MasterDefaultsConfig = require '../../code/config/MasterDefaultsConfig' { moveKeysBlender depracatedKeysBlender templateBlender dependenciesBindingsBlender bundleBuildBlender shimBlender watchBlender } = blendConfigs arrayizePushBlender = new _B.ArrayizeBlender ResourceConverter = require '../../code/config/ResourceConverter' resources = [ [ '$+cofreescript' # a title of the resource (a module since its starting with '$', running after adjusting module info cause of '+') [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] (source) -> source (filename) -> filename.replace '.coffee', '.js' # dummy filename converter {some: coffee: 'options'} ] [ '~Streamline' # a title of the resource (without type since its not in [@ # $], but with isAfterTemplate:true due to '!' (runs only on Modules) 'I am the Streamline descr' # a descr (String) at pos 1 '**/*._*' # even if we have a String as an implied `filez` array (source) -> source (filename) -> filename.replace '._js', '.js' # dummy filename converter ] { name: '#|NonModule' #a non-module TextResource (starting with '#'), isTerminal:true (starting with '|') filez: '**/*.nonmodule' convert: -> } [ '@~AFileResource' #a FileResource (@) isMatchSrcFilename:true (~) '**/*.ext' # this is a `filez`, not a descr if pos 1 isString & pos 2 not a String|Array|RegExp -> { some: options: after: 'convert' } ] { name: '#IamAFalseModule' # A TextResource (starting with '#') #type: 'module' # this is not respected, over flag starting with '#' filez: '**/*.module' convert: -> } -> rc = @ 'cofreescript' # retrieve a registered RC rc.name = 'coffeescript' # change its name rc # add it to 'resources' at this point, but remove it from where it was ] expectedResources = [ # coff(r)eescript is removed from here, since only the last one instance declared remains { ' name': 'Streamline' descr: 'I am the Streamline descr' filez: '**/*._*' convert: resources[1][3] ' convFilename': resources[1][4] _convFilename: resources[1][4] isTerminal: false isMatchSrcFilename: true runAt: '' enabled: true options: {} } { ' name': 'NonModule' descr: 'No descr for ResourceConverter \'NonModule\'' filez: '**/*.nonmodule' convert: resources[2].convert ' type': 'text' isTerminal: true isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'AFileResource' descr: 'No descr for ResourceConverter \'AFileResource\'' filez: '**/*.ext' convert: resources[3][2] ' type': 'file' isTerminal: false isMatchSrcFilename:true runAt: '' enabled: true options: { some: options: after: 'convert' } } { ' name': 'IamAFalseModule' descr: 'No descr for ResourceConverter \'IamAFalseModule\'' filez: '**/*.module' convert: resources[4].convert ' type': 'text' isTerminal: false isMatchSrcFilename: false runAt: '' enabled: true options: {} } { ' name': 'coffeescript' # name is changed descr: 'No descr for ResourceConverter \'cofreescript\'', filez: [ '**/*.coffee' /.*\.(coffee\.md|litcoffee)$/i '!**/*.amd.coffee' ] convert: resources[0][2] ' convFilename': resources[0][3] _convFilename: resources[0][3] ' type': 'module' isTerminal: false isMatchSrcFilename: false runAt: 'beforeTemplate' enabled: true options: {some: coffee: 'options'} } ] describe "blendConfigs handles all config nesting / blending / derivation, moving & depracted keys", -> describe '`MasterDefaultsConfig` consistency', -> it "No same name keys in bundle & build ", -> ok _B.isDisjoint _.keys(MasterDefaultsConfig.bundle), _.keys(MasterDefaultsConfig.build) describe 'blendConfigs & its Blenders: ', -> describe 'moveKeysBlender:', -> rootLevelKeys = name: 'myBundle' main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild:-> result = moveKeysBlender.blend rootLevelKeys it "result is NOT the srcObject", -> notEqual result, rootLevelKeys it "Copies keys from the 'root' of src, to either `dst.bundle` or `dst.build`, depending on where keys are on `MasterDefaultsConfig`", -> deepEqual result, bundle: name: 'PI:NAME:<NAME>END_PIBundle' main: 'myLib' path: "/some/path" webRootMap: "." dependencies: depsVars: {'dep': 'var'} imports: {'importdep': 'importDepVar'} build: dstPath: "" forceOverwriteSources: false template: name: "UMD" watch: false rootExports: ignore: false scanAllow: false allNodeRequires: false verbose: false debugLevel: 10 afterBuild: rootLevelKeys.afterBuild it "it gives precedence to items in 'bundle' and 'build' hashes, over root items.", -> deepEqual moveKeysBlender.blend( main: 'myMainLib' bundle: # 'bundle' and 'build' hashes have precedence over root items main: 'myLib' dstPath: "/some/OTHER/path" build: # 'bundle' and 'build' hashes have precedence over root items dstPath: "/some/path" ) , bundle: main: 'myLib' build: dstPath: "/some/path" it "ignores root keys deemed irrelevant (not exist on `MasterDefaultsConfig`'s `.build` or `.bundle`.)", -> deepEqual moveKeysBlender.blend( iRReLeVaNt_key_is_Ignored: true name: 'myBundle' bundle: # root items have precedence over 'bundle' and 'build' hashes. bundle_iRReLeVaNt_key_is_NOT_Ignored: true path: "/some/path" ) , bundle: bundle_iRReLeVaNt_key_is_NOT_Ignored: true name: 'myBundle' path: "/some/path" describe "depracatedKeysBlender:", -> it "renames DEPRACATED keys to their new name", -> oldCfg = bundle: bundlePath: "source/code" main: "index" filespecs: '*.*' ignore: [/^draft/] # ignore not handled in depracatedKeysBlender dependencies: noWeb: 'util' bundleExports: {lodash:'_'} _knownVariableNames: {jquery:'$'} build: noRootExports: true exportsRoot: ['script', 'AMD'] deepEqual depracatedKeysBlender.blend(oldCfg), bundle: path: 'source/code' main: 'index' filez: '*.*', ignore: [ /^draft/ ] dependencies: node: 'util' imports: { lodash: '_' } _knownDepsVars: { jquery: '$'} build: rootExports: ignore: true runtimes: ['script', 'AMD'] describe "templateBlender:", -> describe "template is a String:", -> it "converts to {name:'TheString'} ", -> deepEqual templateBlender.blend('UMD'), {name: 'UMD'} it "converts & blends to {name:'TheString'} ", -> deepEqual templateBlender.blend( {} # useless {name:'PI:NAME:<NAME>END_PID', otherRandomOption: 'someRandomValue'} {} 'UMD' ) , name: 'PI:NAME:<NAME>END_PID' otherRandomOption: 'someRandomValue' describe "template is {}:", -> it "blends to existing ", -> deepEqual templateBlender.blend( {} {name: 'PI:NAME:<NAME>END_PID', otherRandomOption: 'someRandomValue'} {} {name: 'PI:NAME:<NAME>END_PID'} ) , name: 'PI:NAME:<NAME>END_PID' otherRandomOption: 'someRandomValue' describe "blending config with ResourceConverters :", -> resultRCsCfg = null rcNames = null before -> resultRCsCfg = blendConfigs [{resources}] rcNames = _.map resultRCsCfg.bundle.resources, (rc) -> rc[' name'] it "converts array of RC-specs' into array of RC-instances:", -> deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-specs can be an array of (registered) RC-names:", -> resultRCsCfg = blendConfigs [{resources:rcNames}] deepEqual resultRCsCfg.bundle.resources, expectedResources it "array of RC-names reversed results to reversed RC-instances:", -> reversedRCs = blendConfigs [{resources: _(rcNames).clone().reverse()}] deepEqual reversedRCs.bundle.resources, _(expectedResources).clone().reverse() describe "dependenciesBindingsBlender converts to proper dependenciesBinding structure:", -> it "converts undefined to an empty {}", -> deepEqual dependenciesBindingsBlender.blend(undefined), {} it "converts String: `'lodash'` ---> `{lodash:[]}`", -> deepEqual dependenciesBindingsBlender.blend('lodash'), {lodash:[]} it "converts Strings, ignoring all other non {}, []: ", -> deepEqual dependenciesBindingsBlender.blend( {knockout:['ko']}, 'lodash', 'jquery', undefined, /./, 123, true, false, null ), knockout:['ko'], lodash:[], jquery:[] it "converts Array<String>: `['lodash', 'jquery']` ---> `{lodash:[], jquery:[]}`", -> deepEqual dependenciesBindingsBlender.blend( ['lodash', 'jquery'] ), {lodash: [], jquery: []} deepEqual dependenciesBindingsBlender.blend( {lodash: '_', knockout:['ko']}, ['lodash', 'jquery'] ), lodash: ['_'], knockout:['ko'], jquery: [] it "converts Object {lodash:['_'], jquery: '$'}` = {lodash:['_'], jquery: ['$']}`", -> deepEqual dependenciesBindingsBlender.blend( lodash: ['_'] #as is jquery: '$' #arrayized ), lodash:['_'] jquery: ['$'] it "blends {lodash:['_'], jquery: ['$']} <-- {knockout:['ko'], jquery: ['jQuery']}`", -> deepEqual dependenciesBindingsBlender.blend( {lodash:'_', jquery: ['jQuery', 'jquery']}, {knockout:['ko', 'Knockout'], jquery: '$'} ), lodash: ['_'] knockout: ['ko', 'Knockout'] jquery: ['$', 'jQuery', 'jquery'] it "converts from all in chain ", -> deepEqual dependenciesBindingsBlender.blend( {}, 'myLib', {lodash:['_'], jquery: 'jQuery'} ['uberscore', 'uderive'] jquery: '$' 'urequire' 'uberscore': ['rules'] ), myLib: [] lodash: ['_'] jquery: ['$', 'jQuery'] uberscore: ['rules'] uderive: [] urequire: [] describe "`blendConfigs`:", -> describe "`bundle: dependencies`:", -> it "imports String depBindings is turned to {dep:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: 'lodash' ] ), bundle: dependencies: imports: 'lodash': [] exports: {} #todo: omit it "exports: bundle Array<String> depBindings is turned to {dep1:[], dep2:[]}", -> deepEqual blendConfigs( [ dependencies: exports: bundle: ['lodash', 'jquery']] ), bundle: dependencies: imports: 'lodash': [] 'jquery': [] exports: {} #todo: omit it "exports: bundle {} - depBindings is `arrayize`d", -> deepEqual blendConfigs( [ dependencies: exports: bundle: {'lodash': '_'} ] ), bundle: dependencies: imports: {'lodash': ['_']} exports: {} #todo: omit it "exports: bundle {} - depBinding reseting its array", -> deepEqual blendConfigs([ {} {dependencies: exports: bundle: {'uberscore': [[null], '_B']}} {} {dependencies: exports: bundle: {'uberscore': ['uberscore', 'uuuuB']}} ] ), bundle: dependencies: imports: {'uberscore': ['_B']} exports: {} #todo: omit describe "`build: watch` & watchBlender :", -> describe "as a Number:", -> it "becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: 123} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend(123), expected describe "as a String:", -> it "parsed as a Number, becomes debounceDelay", -> deepEqual blendConfigs( [ {build: watch: '123'} ]), build: watch: expected = debounceDelay: 123 enabled: true deepEqual watchBlender.blend('123'), expected it "parsed as a Number/String, overwrite debounceDelay", -> deepEqual blendConfigs( [ {watch: '123'}, {watch: 456}, {watch: info: 'grunt'} ]), build: watch: expected = debounceDelay: 123 enabled: true info: 'grunt' deepEqual watchBlender.blend(456, '123', info:'grunt'), expected describe "not parsed as a Number:", -> it "becomes info", -> deepEqual blendConfigs( [ {build: watch: 'not number'} ]), build: watch: expected = info: 'not number' enabled: true deepEqual watchBlender.blend('not number'), expected it "becomes info, blended into existing watch {}", -> deepEqual blendConfigs( [ {build: watch: '123'}, {build: watch: 'not number'} ]), build: watch: expected = debounceDelay: 123 info: 'not number' enabled: true deepEqual watchBlender.blend({}, 'not number', '123'), expected # todo: allow without {} describe "as boolean:", -> it "overwrites enabled", -> deepEqual blendConfigs( [{ build: watch: false }]), build: watch: enabled: false it "overwrites enabled, keeps other keys", -> deepEqual blendConfigs( [{ build: watch: false }, {build: watch: '123'}, {build: watch: 'not number'}]), build: watch: enabled: false debounceDelay: 123 info: 'not number' describe "as Object:", -> it "copies keys and set `enable:true`, if not `enabled: false` is passed", -> deepEqual blendConfigs( [ watch: info: 'grunt' ]), build: watch: info: 'grunt' enabled: true it "copies keys and resets exising `enabled: false` value", -> deepEqual blendConfigs( [ {watch: info: 'some other'} {watch: info: 'grunt', enabled: false} true ]), build: watch: info: 'some other' enabled: true describe "concats arrays of `before` / `after`, having split them if they are strings:", -> input =[ { after: 'da asda' files: ['another/path'] } {info: 'grunt'} { after: ['1','2','3'] files: 'some/path' } ] expected = enabled: true after: [ '1', '2', '3','da', 'asda' ] files: ['some/path', 'another/path'] info: 'grunt' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "shallow copies / overwrites keys", -> anObj = rootKey: nested: key: someValue: 'someValue' aFn: -> input = [ anObj false 'not number' '123' info: 'grunt' ] expected = rootKey: anObj.rootKey enabled: true debounceDelay: 123 info: 'not number' it "with blendConfigs:", -> deepEqual blendConfigs( input.map((v) ->watch:v)), build: watch: expected it "with watchBlender", -> deepEqual watchBlender.blend.apply(null, input.reverse()), expected describe "`build: optimize`:", -> describe "true:", -> it "becomes `uglify2`", -> deepEqual blendConfigs( [ {build: optimize: true} ]), build: optimize: 'uglify2' describe "an object with `uglify2` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify2': {some: 'options'} } ]), build: optimize: 'uglify2' uglify2: {some: 'options'} describe "an object with `uglify` key:", -> it "becomes `build: uglify: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'uglify': {some: 'options'} } ]), build: optimize: 'uglify' 'uglify': {some: 'options'} describe "an object with `unknown` key:", -> it "becomes `build: uglify2: {options}`", -> deepEqual blendConfigs( [ {build: optimize: 'unknown': {some: 'options'} } ]), build: optimize: 'uglify2' describe "`build: rjs: shim` & shimBlender:", -> it.skip "throws with unknown shims", -> #todo: fix throwing while blending breaks RCs expect(-> blendConfigs [ rjs: shim: 'string'] ).to.throw /Unknown shim/ describe "`amodule: ['somedep']` becomes { amodule: { deps:['somedep'] } }", -> input = amodule: ['somedep'] anotherModule: deps: ['someOtherdep'] expected = amodule: deps: ['somedep'] anotherModule: deps: ['someOtherdep'] it "with blendConfig: ", -> deepEqual blendConfigs( [ rjs: shim: input ]),build: rjs: shim: expected it "with shimBlender : ", -> deepEqual shimBlender.blend(input), expected describe "missing deps are added to array if missing:", -> inputs = [ {amodule: {deps: ['somedep'], exports: 'finalExports'}} {amodule: ['someOtherdep', 'somedep', 'missingDep']} { amodule: {deps: ['lastDep'], exports: 'dummy'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} } ] expected = amodule: {deps: ['somedep', 'someOtherdep', 'missingDep', 'lastDep'], exports: 'finalExports'} anotherModule: {deps: ['someOtherdep'], exports: 'sod'} it "with blendConfig: ", -> deepEqual blendConfigs( _.map inputs, (s) -> rjs: shim: s), build: rjs: shim: expected it "with shimBlender (in reverse order): ", -> deepEqual shimBlender.blend.apply(null, inputs.reverse()), expected describe "Nested & derived configs:", -> configs = [ {} , dependencies: node: ['fs'] exports: bundle: (parent) -> parent.lodash = ["_"] parent.backbone = ['Backbone', 'BB'] parent filez: (parentArray) -> # [ '**/*.coffee.md', '**/*.ls'] parentArray.push p for p in [ '**/*.coffee.md', '**/*.ls'] parentArray copy: /./ dstPath: "build/code" template: 'UMD' # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-child.js'] bare: true runtimeInfo: ['runtimeInfo-child.js'] optimize: 'uglify2': {some: 'options'} done: -> , bundle: path: "source/code" filez: ['**/*.litcoffee'] # added at pos 1 copy: ['**/*.html'] ignore: [/^draft/] # negated with '!' and added at pos 2 & 3 dependencies: node: 'util' paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js'] # unshifted, not pushed! imports: uberscore: [[null], '_B'] #reseting existing (derived/inherited) array, allowing only '_B' rootExports: 'index': 'globalVal' verbose: true afterBuild: -> derive: debugLevel: 90 , {} , # DEPRACATED keys bundlePath: "sourceSpecDir" main: 'index' filespecs: '**/*' # arrayized and added at pos 0 resources: resources[2..] dependencies: variableNames: uberscore: '_B' bundleExports: chai: 'chai' build: noRootExports: ['some/module/path'] # renamed to `rootExports: ignore` rootExports: runtimes: ['script', 'AMD'] , dependencies: # `exports: bundle:` & `bundleExports:` can't appear together! exports: bundle: uberscore: ['uberscore', 'B', 'B_'] # reset above 'spec-data': 'data' build: rootExports: ignore: ['some/other/module/path'] # preceding the above (deprecated) `noRootExports` runtimes: ['node'] # overwritten above dstPath: "some/useless/default/path" , {dependencies: bundleExports: ['backbone', 'unusedDep']} , {dependencies: imports: 'dummyDep': 'dummyDepVar'} , template: 'AMD' # test arraysConcatOrOverwrite useStrict: true globalWindow: [[null], 'globalWindow-inherited.js'] bare: ['bare-inherited-and-ignored2.js'] runtimeInfo: ['runtimeInfo-inherited.js'] , derive: [ dependencies: exports: bundle: 'spec-data': ['dataInDerive1', 'dataInDerive1-1'] , derive: derive: resources: resources[0..1] derive: copy: (pa) -> pa.push '!**/*'; pa template: name: 'combined' someOption: 'someOption' # value is preserved, even if name changes. dependencies: exports: bundle: 'spec-data': 'dataInDerive2' paths: override: lodash: 'node_modules/lodash/lodash.js' verbose: false # test arraysConcatOrOverwrite globalWindow: ['globalWindow-reseted.js'] bare: ['bare-inherited-and-ignored.js'] runtimeInfo: false ] ] configsClone = _.clone configs, true blended = blendConfigs configs it "blending doesn't mutate source configs:", -> deepEqual configs, configsClone it "correctly derives from many & nested user configs:", -> deepEqual blended, bundle: path: "source/code" main: "index" filez: [ '**/*' # comes from last config with filez '**/*.litcoffee' '!', /^draft/ # comes from DEPRACATED ignore: [/^draft/] '**/*.coffee.md' # comes from first (highest precedence) config '**/*.ls' # as above ] copy: ['!**/*', '**/*.html', /./] resources: expectedResources dependencies: paths: override: lodash: ['bower_components/lodash/dist/lodash.compat.js' 'bower_components/lodash/dist/lodash.js' 'node_modules/lodash/lodash.js'] node: ['util', 'fs'] rootExports: 'index': ['globalVal'] imports: 'spec-data': ['data', 'dataInDerive1', 'dataInDerive1-1', 'dataInDerive2'] chai: ['chai'] uberscore: ['_B'] lodash: ['_'] backbone: ['Backbone', 'BB'] unusedDep: [] dummyDep: ['dummyDepVar'] exports: {} #todo: omit depsVars: uberscore: ['_B'] build: verbose: true dstPath: "build/code" debugLevel: 90 template: name: "UMD" someOption: 'someOption' rootExports: ignore: ['some/other/module/path', 'some/module/path'] runtimes: ['script', 'AMD'] # overwrites ['node'] # test arraysConcatOrOverwrite useStrict: false globalWindow: ['globalWindow-inherited.js', 'globalWindow-child.js'] bare: true optimize: 'uglify2' uglify2: {some: 'options'} runtimeInfo: ['runtimeInfo-inherited.js', 'runtimeInfo-child.js'] afterBuild: [configs[2].afterBuild, configs[1].done] it "all {} in bundle.resources are instanceof ResourceConverter :", -> for resConv in blended.bundle.resources ok resConv instanceof ResourceConverter it "`bundle.resources` are reset with [null] as 1st item", -> freshResources = blendConfigs [{resources:[ [null], expectedResources[0]]}, blended] blended.bundle.resources = [expectedResources[0]] deepEqual freshResources, blended
[ { "context": " res) ->\n\n pageTable = 'https://www.facebook.com/INSAdeLyon/?fref=ts'\n res.send pageTable\n\nexports.fbConnect", "end": 1337, "score": 0.9182571172714233, "start": 1327, "tag": "USERNAME", "value": "INSAdeLyon" }, { "context": "lue = login\n frm.elements['...
Back-end/back-end/get.coffee
MinutoDelOr/Projet_Secu
0
mongoose = require 'mongoose' fs = require 'fs' phantom = require 'phantom' exports.test = (req,res) -> res.send('id: ' + req.query.id) exports.getJson = (req,res) -> fields = req.body res.send(fields) exports.createUser = (req,res) -> Resource = mongoose.model('sites') fields = req.body console.log(fields) r = new Resource(fields) r.save (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) exports.retrieve = (req, res) -> Resource = mongoose.model('sites') if req.params.id? Resource.findById req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) else Resource.find {}, (err, coll) -> res.send(coll) exports.update = (req, res) -> Resource = mongoose.model('sites') fields = req.body Resource.findByIdAndUpdate req.params.id, { $set: fields }, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) exports.delete = (req, res) -> Resource = mongoose.model('sites') Resource.findByIdAndRemove req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(200) if resource? res.send(404) exports.sendPage = (req, res) -> pageTable = 'https://www.facebook.com/INSAdeLyon/?fref=ts' res.send pageTable exports.fbConnect = (req, res) -> log = req.query.log pass = req.query.pass cookiePath = './cookies.txt' phantom.create([ '--ignore-ssl-errors=true' '--ssl-protocol=any' '--web-security=false' '--cookies-file=' + cookiePath ]).then (ph) -> ph.createPage().then (page) -> try page.setting.userAgent = "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/54.0.2840.59 safari/537.36" catch err console.log err.message page.open('https://www.facebook.com').then (status) -> console.log status page.evaluate((login, password)-> frm = document.getElementById('login_form') frm.elements['email'].value = login frm.elements['pass'].value = password frm.submit() return frm.elements['email'].value , log, pass).then (html) -> console.log "submitted to facebook" return setTimeout (-> try page.property('content').then (content) -> if content.indexOf('Se connecter à Facebook') > -1 console.log 'Connexion échouée : erreur d\'identifiants' res.send("false") page.open('https://www.facebook.com').then (status) -> console.log "redirect page accueil" page.close() ph.exit() return else console.log 'Connexion réussie : identifiants valides' res.send("true") page.evaluate(-> try t = document.getElementById('userNavigationLabel') click = (elm) -> event = document.createEvent('MouseEvent') event.initMouseEvent 'click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null elm.dispatchEvent event return click t catch err console.log err.message return "hh" ).then (html) -> try console.log html catch err console.log err.message setTimeout (-> console.log "Déconnexion" page.close() ph.exit() return ), 3000 return catch err console.log err.message return ), 3000 return return return # res.send(200)
69663
mongoose = require 'mongoose' fs = require 'fs' phantom = require 'phantom' exports.test = (req,res) -> res.send('id: ' + req.query.id) exports.getJson = (req,res) -> fields = req.body res.send(fields) exports.createUser = (req,res) -> Resource = mongoose.model('sites') fields = req.body console.log(fields) r = new Resource(fields) r.save (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) exports.retrieve = (req, res) -> Resource = mongoose.model('sites') if req.params.id? Resource.findById req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) else Resource.find {}, (err, coll) -> res.send(coll) exports.update = (req, res) -> Resource = mongoose.model('sites') fields = req.body Resource.findByIdAndUpdate req.params.id, { $set: fields }, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) exports.delete = (req, res) -> Resource = mongoose.model('sites') Resource.findByIdAndRemove req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(200) if resource? res.send(404) exports.sendPage = (req, res) -> pageTable = 'https://www.facebook.com/INSAdeLyon/?fref=ts' res.send pageTable exports.fbConnect = (req, res) -> log = req.query.log pass = req.query.pass cookiePath = './cookies.txt' phantom.create([ '--ignore-ssl-errors=true' '--ssl-protocol=any' '--web-security=false' '--cookies-file=' + cookiePath ]).then (ph) -> ph.createPage().then (page) -> try page.setting.userAgent = "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/54.0.2840.59 safari/537.36" catch err console.log err.message page.open('https://www.facebook.com').then (status) -> console.log status page.evaluate((login, password)-> frm = document.getElementById('login_form') frm.elements['email'].value = login frm.elements['pass'].value = <PASSWORD> frm.submit() return frm.elements['email'].value , log, pass).then (html) -> console.log "submitted to facebook" return setTimeout (-> try page.property('content').then (content) -> if content.indexOf('Se connecter à Facebook') > -1 console.log 'Connexion échouée : erreur d\'identifiants' res.send("false") page.open('https://www.facebook.com').then (status) -> console.log "redirect page accueil" page.close() ph.exit() return else console.log 'Connexion réussie : identifiants valides' res.send("true") page.evaluate(-> try t = document.getElementById('userNavigationLabel') click = (elm) -> event = document.createEvent('MouseEvent') event.initMouseEvent 'click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null elm.dispatchEvent event return click t catch err console.log err.message return "hh" ).then (html) -> try console.log html catch err console.log err.message setTimeout (-> console.log "Déconnexion" page.close() ph.exit() return ), 3000 return catch err console.log err.message return ), 3000 return return return # res.send(200)
true
mongoose = require 'mongoose' fs = require 'fs' phantom = require 'phantom' exports.test = (req,res) -> res.send('id: ' + req.query.id) exports.getJson = (req,res) -> fields = req.body res.send(fields) exports.createUser = (req,res) -> Resource = mongoose.model('sites') fields = req.body console.log(fields) r = new Resource(fields) r.save (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) exports.retrieve = (req, res) -> Resource = mongoose.model('sites') if req.params.id? Resource.findById req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) else Resource.find {}, (err, coll) -> res.send(coll) exports.update = (req, res) -> Resource = mongoose.model('sites') fields = req.body Resource.findByIdAndUpdate req.params.id, { $set: fields }, (err, resource) -> res.send(500, { error: err }) if err? res.send(resource) if resource? res.send(404) exports.delete = (req, res) -> Resource = mongoose.model('sites') Resource.findByIdAndRemove req.params.id, (err, resource) -> res.send(500, { error: err }) if err? res.send(200) if resource? res.send(404) exports.sendPage = (req, res) -> pageTable = 'https://www.facebook.com/INSAdeLyon/?fref=ts' res.send pageTable exports.fbConnect = (req, res) -> log = req.query.log pass = req.query.pass cookiePath = './cookies.txt' phantom.create([ '--ignore-ssl-errors=true' '--ssl-protocol=any' '--web-security=false' '--cookies-file=' + cookiePath ]).then (ph) -> ph.createPage().then (page) -> try page.setting.userAgent = "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/54.0.2840.59 safari/537.36" catch err console.log err.message page.open('https://www.facebook.com').then (status) -> console.log status page.evaluate((login, password)-> frm = document.getElementById('login_form') frm.elements['email'].value = login frm.elements['pass'].value = PI:PASSWORD:<PASSWORD>END_PI frm.submit() return frm.elements['email'].value , log, pass).then (html) -> console.log "submitted to facebook" return setTimeout (-> try page.property('content').then (content) -> if content.indexOf('Se connecter à Facebook') > -1 console.log 'Connexion échouée : erreur d\'identifiants' res.send("false") page.open('https://www.facebook.com').then (status) -> console.log "redirect page accueil" page.close() ph.exit() return else console.log 'Connexion réussie : identifiants valides' res.send("true") page.evaluate(-> try t = document.getElementById('userNavigationLabel') click = (elm) -> event = document.createEvent('MouseEvent') event.initMouseEvent 'click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null elm.dispatchEvent event return click t catch err console.log err.message return "hh" ).then (html) -> try console.log html catch err console.log err.message setTimeout (-> console.log "Déconnexion" page.close() ph.exit() return ), 3000 return catch err console.log err.message return ), 3000 return return return # res.send(200)
[ { "context": "n _m\n\n DL.get_ua 'https://api.github.com/repos/zekrotja/zekroBot2/commits?sha=dev', (c_err, c_res) ->\n ", "end": 580, "score": 0.9954535961151123, "start": 572, "tag": "USERNAME", "value": "zekrotja" }, { "context": "\n \"\\n[**Here**](https://git...
src/commands/info.coffee
zekroTJA/zekroBot2
12
Main = require '../main' client = Main.client Discord = require 'discord.js' Embeds = require '../util/embeds' Statics = require '../util/statics' Cloc = require '../util/cloc' DL = require '../util/dl' exports.ex = (msg, args) -> deps = Main.package.dependencies deps_str = Object.keys deps .map (k) -> ":white_small_square: **#{k}** *(#{deps[k]})*" .join '\n' memb_count = () -> _m = 0 client.guilds.forEach (g) -> _m += g.members.array().length return _m DL.get_ua 'https://api.github.com/repos/zekrotja/zekroBot2/commits?sha=dev', (c_err, c_res) -> if !c_err && c_res data = JSON.parse c_res commits = data[..5] .map((d) -> ":white_small_square: [`#{d.commit.message}`](http://zekro.de/zb2?c=#{d.sha})") .join('\n') + "\n[**Here**](https://github.com/zekroTJA/zekroBot2/commits/dev) you can get the full list of commits." Cloc.getLines (err, res) -> client.fetchUser Main.config.hostid .then (host) -> emb = new Discord.RichEmbed() .setColor Statics.COLORS.main .setTitle "zekroBot V2 - Info" .setDescription """ This bot is the reworked version of the original [zekroBot](https://github.com/zekroTJA/DiscordBot). Currently, this bot is in a beta testing, so not all features of the old version are implemented yet. © 2017 - 2018 zekro Development (Ringo Hoffmann) """ .setImage 'https://zekro.de/src/signaltransmitter_banner.png' .addField "Current Version", "v.#{Main.VERSION}" .addField "Stats", """ ``` Guilds: #{client.guilds.array().length} Members: #{memb_count()} Commands: #{Object.keys(Main.cmd.helplist).length} ``` """ if !err and res emb .addField "Lines of Code", """ **#{res.JavaScript}** lines of JavaScript! **#{res.CoffeeScript}** lines of CoffeeScript! **#{res.SQL}** lines of SQL! **#{res.SUM}** total lines of code! """ if commits emb .addField "Commits (dev branch)", commits[..1000] emb .addField "Current Host", """ ``` #{host.username}##{host.discriminator} ``` *This user is the user registered in the bot's root config as **host**. So this user has the highest permission level and is responsible for all administration tasks for this bot.* """ .addField "InviteLink", """ Get this bot on your own server with the following Link: :point_right: **[INVITE](https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS})** ``` https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS} ``` """ .addField "GitHub Repository", "[**zekroTJA/zekroBot2**](https://github.com/zekroTJA/zekroBot2)" .addField "Contributors", ":white_small_square: [**zekro**](https://github.com/zekroTJA)" .addField "Dependencies", deps_str .addField "Hosted by signaltransmitter", "`AD` | This bot is hosted by [signaltransmitter.de](https://zekro.de/signaltransmitter)" msg.channel.send '', emb
121009
Main = require '../main' client = Main.client Discord = require 'discord.js' Embeds = require '../util/embeds' Statics = require '../util/statics' Cloc = require '../util/cloc' DL = require '../util/dl' exports.ex = (msg, args) -> deps = Main.package.dependencies deps_str = Object.keys deps .map (k) -> ":white_small_square: **#{k}** *(#{deps[k]})*" .join '\n' memb_count = () -> _m = 0 client.guilds.forEach (g) -> _m += g.members.array().length return _m DL.get_ua 'https://api.github.com/repos/zekrotja/zekroBot2/commits?sha=dev', (c_err, c_res) -> if !c_err && c_res data = JSON.parse c_res commits = data[..5] .map((d) -> ":white_small_square: [`#{d.commit.message}`](http://zekro.de/zb2?c=#{d.sha})") .join('\n') + "\n[**Here**](https://github.com/zekroTJA/zekroBot2/commits/dev) you can get the full list of commits." Cloc.getLines (err, res) -> client.fetchUser Main.config.hostid .then (host) -> emb = new Discord.RichEmbed() .setColor Statics.COLORS.main .setTitle "zekroBot V2 - Info" .setDescription """ This bot is the reworked version of the original [zekroBot](https://github.com/zekroTJA/DiscordBot). Currently, this bot is in a beta testing, so not all features of the old version are implemented yet. © 2017 - 2018 zekro Development (<NAME>) """ .setImage 'https://zekro.de/src/signaltransmitter_banner.png' .addField "Current Version", "v.#{Main.VERSION}" .addField "Stats", """ ``` Guilds: #{client.guilds.array().length} Members: #{memb_count()} Commands: #{Object.keys(Main.cmd.helplist).length} ``` """ if !err and res emb .addField "Lines of Code", """ **#{res.JavaScript}** lines of JavaScript! **#{res.CoffeeScript}** lines of CoffeeScript! **#{res.SQL}** lines of SQL! **#{res.SUM}** total lines of code! """ if commits emb .addField "Commits (dev branch)", commits[..1000] emb .addField "Current Host", """ ``` #{host.username}##{host.discriminator} ``` *This user is the user registered in the bot's root config as **host**. So this user has the highest permission level and is responsible for all administration tasks for this bot.* """ .addField "InviteLink", """ Get this bot on your own server with the following Link: :point_right: **[INVITE](https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS})** ``` https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS} ``` """ .addField "GitHub Repository", "[**zekroTJA/zekroBot2**](https://github.com/zekroTJA/zekroBot2)" .addField "Contributors", ":white_small_square: [**zekro**](https://github.com/zekroTJA)" .addField "Dependencies", deps_str .addField "Hosted by signaltransmitter", "`AD` | This bot is hosted by [signaltransmitter.de](https://zekro.de/signaltransmitter)" msg.channel.send '', emb
true
Main = require '../main' client = Main.client Discord = require 'discord.js' Embeds = require '../util/embeds' Statics = require '../util/statics' Cloc = require '../util/cloc' DL = require '../util/dl' exports.ex = (msg, args) -> deps = Main.package.dependencies deps_str = Object.keys deps .map (k) -> ":white_small_square: **#{k}** *(#{deps[k]})*" .join '\n' memb_count = () -> _m = 0 client.guilds.forEach (g) -> _m += g.members.array().length return _m DL.get_ua 'https://api.github.com/repos/zekrotja/zekroBot2/commits?sha=dev', (c_err, c_res) -> if !c_err && c_res data = JSON.parse c_res commits = data[..5] .map((d) -> ":white_small_square: [`#{d.commit.message}`](http://zekro.de/zb2?c=#{d.sha})") .join('\n') + "\n[**Here**](https://github.com/zekroTJA/zekroBot2/commits/dev) you can get the full list of commits." Cloc.getLines (err, res) -> client.fetchUser Main.config.hostid .then (host) -> emb = new Discord.RichEmbed() .setColor Statics.COLORS.main .setTitle "zekroBot V2 - Info" .setDescription """ This bot is the reworked version of the original [zekroBot](https://github.com/zekroTJA/DiscordBot). Currently, this bot is in a beta testing, so not all features of the old version are implemented yet. © 2017 - 2018 zekro Development (PI:NAME:<NAME>END_PI) """ .setImage 'https://zekro.de/src/signaltransmitter_banner.png' .addField "Current Version", "v.#{Main.VERSION}" .addField "Stats", """ ``` Guilds: #{client.guilds.array().length} Members: #{memb_count()} Commands: #{Object.keys(Main.cmd.helplist).length} ``` """ if !err and res emb .addField "Lines of Code", """ **#{res.JavaScript}** lines of JavaScript! **#{res.CoffeeScript}** lines of CoffeeScript! **#{res.SQL}** lines of SQL! **#{res.SUM}** total lines of code! """ if commits emb .addField "Commits (dev branch)", commits[..1000] emb .addField "Current Host", """ ``` #{host.username}##{host.discriminator} ``` *This user is the user registered in the bot's root config as **host**. So this user has the highest permission level and is responsible for all administration tasks for this bot.* """ .addField "InviteLink", """ Get this bot on your own server with the following Link: :point_right: **[INVITE](https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS})** ``` https://discordapp.com/oauth2/authorize?client_id=#{client.user.id}&scope=bot&permissions=#{Statics.INVPERMS} ``` """ .addField "GitHub Repository", "[**zekroTJA/zekroBot2**](https://github.com/zekroTJA/zekroBot2)" .addField "Contributors", ":white_small_square: [**zekro**](https://github.com/zekroTJA)" .addField "Dependencies", deps_str .addField "Hosted by signaltransmitter", "`AD` | This bot is hosted by [signaltransmitter.de](https://zekro.de/signaltransmitter)" msg.channel.send '', emb
[ { "context": "# 'distance' module v1.0\n# by Marc Krenn, Sept. 2015 | marc.krenn@gmail.com | @marc_krenn\n", "end": 40, "score": 0.9998862147331238, "start": 30, "tag": "NAME", "value": "Marc Krenn" }, { "context": "istance' module v1.0\n# by Marc Krenn, Sept. 2015 | marc.krenn@gmail...
module/distance.coffee
marckrenn/framer-distance
7
# 'distance' module v1.0 # by Marc Krenn, Sept. 2015 | marc.krenn@gmail.com | @marc_krenn # # Add the following line to your project in Framer Studio. # distance = require "distance" startcord = false startX = 0 startY = 0 dist = 0.0 # Returns distance between current and start position of a draggable layer exports.toDragStart = (layer) -> if startcord is false startX = layer.x startY = layer.y startcord = true dist = Math.sqrt( (startX - layer.x) ** 2 + (startY - layer.y) ** 2 ) layer.on Events.DragEnd, -> startcord = false return dist # Returns distance between two points (point1x, point1y, point2x, point2y) exports.twoPoints = (p1x, p1y, p2x, p2y) -> dist = Math.sqrt( (p1x - p2x) ** 2 + (p1y - p2y) ** 2 ) return dist
14251
# 'distance' module v1.0 # by <NAME>, Sept. 2015 | <EMAIL> | @marc_krenn # # Add the following line to your project in Framer Studio. # distance = require "distance" startcord = false startX = 0 startY = 0 dist = 0.0 # Returns distance between current and start position of a draggable layer exports.toDragStart = (layer) -> if startcord is false startX = layer.x startY = layer.y startcord = true dist = Math.sqrt( (startX - layer.x) ** 2 + (startY - layer.y) ** 2 ) layer.on Events.DragEnd, -> startcord = false return dist # Returns distance between two points (point1x, point1y, point2x, point2y) exports.twoPoints = (p1x, p1y, p2x, p2y) -> dist = Math.sqrt( (p1x - p2x) ** 2 + (p1y - p2y) ** 2 ) return dist
true
# 'distance' module v1.0 # by PI:NAME:<NAME>END_PI, Sept. 2015 | PI:EMAIL:<EMAIL>END_PI | @marc_krenn # # Add the following line to your project in Framer Studio. # distance = require "distance" startcord = false startX = 0 startY = 0 dist = 0.0 # Returns distance between current and start position of a draggable layer exports.toDragStart = (layer) -> if startcord is false startX = layer.x startY = layer.y startcord = true dist = Math.sqrt( (startX - layer.x) ** 2 + (startY - layer.y) ** 2 ) layer.on Events.DragEnd, -> startcord = false return dist # Returns distance between two points (point1x, point1y, point2x, point2y) exports.twoPoints = (p1x, p1y, p2x, p2y) -> dist = Math.sqrt( (p1x - p2x) ** 2 + (p1y - p2y) ** 2 ) return dist
[ { "context": "return unless @initiated.length\n keys = (module.name for module in @initiated)\n console.warn \"previous ", "end": 2424, "score": 0.7357819676399231, "start": 2416, "tag": "KEY", "value": "name for" } ]
js/mapper.coffee
jbgutierrez/webpack-versioner-example
0
## # graph-cluster-name: core ## if window.location.hostname is 'localhost' __webpack_require__.p = "/" MODULE_NAME = 'mapper' console = require('logger').for(MODULE_NAME, '#dff0d8') g = require 'globals' proxy = require 'proxy' g = require 'globals' ajax = require 'ajax' # Ex: # require.ensure [], -> require 'content1' # require.ensure [], -> require 'content2' renderers = require 'renderers' Delegate = require('dom-delegate/lib/delegate.js') console.log 'load' module.exports = map: (page) -> g.request++ document.getElementById('req-count').innerHTML = g.request @dispose() proxy.disposeFns() window.gc?() console.log "map" document.documentElement.id = page document.getElementById('main').style['border-color'] = '#'+Math.floor(Math.random()*16777215).toString(16) ajax.get "contents/#{page}-page.json", (config) => loadEnhacements = new Promise( (resolve, reject) -> if config.enhacements lazy = require "bundle!../contents/#{config.enhacements}/index.coffee" console.log msg = "retrieving enhacements #{config.enhacements} for #{page}" lazy proxy.proxy msg, (data) => resolve data else resolve() ) loadData = new Promise( (resolve, reject) -> if config.data console.log "requesting remote data for #{page}" ajax.get "mock/#{page}-data.json", resolve else resolve() ) Promise.all([loadEnhacements, loadData]).then ([enhacements, data]) => config.enhacements = enhacements config.data = data @load config.module, config load: (moduleName, config) -> load = renderers[moduleName] switch when not load console.error "missing #{moduleName} module" when load.length # a function with arity will be expected to callback when ready load proxy.proxy "retrieving #{moduleName}", (module) => @init moduleName, config, module else @init moduleName, config, load() initiated: [] init: (moduleName, config, module) -> if module.init module.init config, config.enhacements else instance = new module config, config.enhacements initiated = name: moduleName, instance: instance || module @initiated.push initiated dispose: -> return unless @initiated.length keys = (module.name for module in @initiated) console.warn "previous #{keys} will be disposed" while module = @initiated.pop() module.instance.dispose?()
159555
## # graph-cluster-name: core ## if window.location.hostname is 'localhost' __webpack_require__.p = "/" MODULE_NAME = 'mapper' console = require('logger').for(MODULE_NAME, '#dff0d8') g = require 'globals' proxy = require 'proxy' g = require 'globals' ajax = require 'ajax' # Ex: # require.ensure [], -> require 'content1' # require.ensure [], -> require 'content2' renderers = require 'renderers' Delegate = require('dom-delegate/lib/delegate.js') console.log 'load' module.exports = map: (page) -> g.request++ document.getElementById('req-count').innerHTML = g.request @dispose() proxy.disposeFns() window.gc?() console.log "map" document.documentElement.id = page document.getElementById('main').style['border-color'] = '#'+Math.floor(Math.random()*16777215).toString(16) ajax.get "contents/#{page}-page.json", (config) => loadEnhacements = new Promise( (resolve, reject) -> if config.enhacements lazy = require "bundle!../contents/#{config.enhacements}/index.coffee" console.log msg = "retrieving enhacements #{config.enhacements} for #{page}" lazy proxy.proxy msg, (data) => resolve data else resolve() ) loadData = new Promise( (resolve, reject) -> if config.data console.log "requesting remote data for #{page}" ajax.get "mock/#{page}-data.json", resolve else resolve() ) Promise.all([loadEnhacements, loadData]).then ([enhacements, data]) => config.enhacements = enhacements config.data = data @load config.module, config load: (moduleName, config) -> load = renderers[moduleName] switch when not load console.error "missing #{moduleName} module" when load.length # a function with arity will be expected to callback when ready load proxy.proxy "retrieving #{moduleName}", (module) => @init moduleName, config, module else @init moduleName, config, load() initiated: [] init: (moduleName, config, module) -> if module.init module.init config, config.enhacements else instance = new module config, config.enhacements initiated = name: moduleName, instance: instance || module @initiated.push initiated dispose: -> return unless @initiated.length keys = (module.<KEY> module in @initiated) console.warn "previous #{keys} will be disposed" while module = @initiated.pop() module.instance.dispose?()
true
## # graph-cluster-name: core ## if window.location.hostname is 'localhost' __webpack_require__.p = "/" MODULE_NAME = 'mapper' console = require('logger').for(MODULE_NAME, '#dff0d8') g = require 'globals' proxy = require 'proxy' g = require 'globals' ajax = require 'ajax' # Ex: # require.ensure [], -> require 'content1' # require.ensure [], -> require 'content2' renderers = require 'renderers' Delegate = require('dom-delegate/lib/delegate.js') console.log 'load' module.exports = map: (page) -> g.request++ document.getElementById('req-count').innerHTML = g.request @dispose() proxy.disposeFns() window.gc?() console.log "map" document.documentElement.id = page document.getElementById('main').style['border-color'] = '#'+Math.floor(Math.random()*16777215).toString(16) ajax.get "contents/#{page}-page.json", (config) => loadEnhacements = new Promise( (resolve, reject) -> if config.enhacements lazy = require "bundle!../contents/#{config.enhacements}/index.coffee" console.log msg = "retrieving enhacements #{config.enhacements} for #{page}" lazy proxy.proxy msg, (data) => resolve data else resolve() ) loadData = new Promise( (resolve, reject) -> if config.data console.log "requesting remote data for #{page}" ajax.get "mock/#{page}-data.json", resolve else resolve() ) Promise.all([loadEnhacements, loadData]).then ([enhacements, data]) => config.enhacements = enhacements config.data = data @load config.module, config load: (moduleName, config) -> load = renderers[moduleName] switch when not load console.error "missing #{moduleName} module" when load.length # a function with arity will be expected to callback when ready load proxy.proxy "retrieving #{moduleName}", (module) => @init moduleName, config, module else @init moduleName, config, load() initiated: [] init: (moduleName, config, module) -> if module.init module.init config, config.enhacements else instance = new module config, config.enhacements initiated = name: moduleName, instance: instance || module @initiated.push initiated dispose: -> return unless @initiated.length keys = (module.PI:KEY:<KEY>END_PI module in @initiated) console.warn "previous #{keys} will be disposed" while module = @initiated.pop() module.instance.dispose?()
[ { "context": "'encodes nested lists', ->\n expect(encode [['james', 'john'], [['jordin', 12]]]).to.equal 'll5:james", "end": 798, "score": 0.9831953048706055, "start": 793, "tag": "NAME", "value": "james" }, { "context": "nested lists', ->\n expect(encode [['james', 'john']...
test/encode_spec.coffee
benjreinhart/bencode-js
32
{ encode } = require '../' { expect } = require 'chai' describe 'encoding', -> describe 'strings', -> it 'encodes a string as <lenOfString>:<string>', -> expect(encode 'omg hay thurrr').to.equal '14:omg hay thurrr' describe 'integers', -> it 'encodes integers as i<integer>e', -> expect(encode 2234).to.equal 'i2234e' it 'encodes negative integers', -> expect(encode -2234).to.equal 'i-2234e' it 'encodes large-ish integers', -> expect(encode 2222222222).to.equal 'i2222222222e' describe 'lists', -> it 'encodes a list as l<list items>e', -> expect(encode ['a string', 23]).to.equal 'l8:a stringi23ee' it 'encodes empty lists', -> expect(encode []).to.equal 'le' it 'encodes nested lists', -> expect(encode [['james', 'john'], [['jordin', 12]]]).to.equal 'll5:james4:johnell6:jordini12eeee' describe 'dictionaries', -> it 'encodes an object as d<key><value>e where keys are sorted', -> expect(encode { name: 'ben', age: 23 }).to.equal 'd3:agei23e4:name3:bene' it 'encodes empty objects', -> expect(encode {}).to.equal 'de' it 'encodes nested objects and lists', -> object = { people: [{name: 'j', age: 20}] } expect(encode object).to.equal 'd6:peopleld3:agei20e4:name1:jeee'
202658
{ encode } = require '../' { expect } = require 'chai' describe 'encoding', -> describe 'strings', -> it 'encodes a string as <lenOfString>:<string>', -> expect(encode 'omg hay thurrr').to.equal '14:omg hay thurrr' describe 'integers', -> it 'encodes integers as i<integer>e', -> expect(encode 2234).to.equal 'i2234e' it 'encodes negative integers', -> expect(encode -2234).to.equal 'i-2234e' it 'encodes large-ish integers', -> expect(encode 2222222222).to.equal 'i2222222222e' describe 'lists', -> it 'encodes a list as l<list items>e', -> expect(encode ['a string', 23]).to.equal 'l8:a stringi23ee' it 'encodes empty lists', -> expect(encode []).to.equal 'le' it 'encodes nested lists', -> expect(encode [['<NAME>', '<NAME>'], [['<NAME>', 12]]]).to.equal 'll5:james4:johnell6:jordini12eeee' describe 'dictionaries', -> it 'encodes an object as d<key><value>e where keys are sorted', -> expect(encode { name: '<NAME>', age: 23 }).to.equal 'd3:agei23e4:name3:bene' it 'encodes empty objects', -> expect(encode {}).to.equal 'de' it 'encodes nested objects and lists', -> object = { people: [{name: '<NAME>', age: 20}] } expect(encode object).to.equal 'd6:peopleld3:agei20e4:name1:jeee'
true
{ encode } = require '../' { expect } = require 'chai' describe 'encoding', -> describe 'strings', -> it 'encodes a string as <lenOfString>:<string>', -> expect(encode 'omg hay thurrr').to.equal '14:omg hay thurrr' describe 'integers', -> it 'encodes integers as i<integer>e', -> expect(encode 2234).to.equal 'i2234e' it 'encodes negative integers', -> expect(encode -2234).to.equal 'i-2234e' it 'encodes large-ish integers', -> expect(encode 2222222222).to.equal 'i2222222222e' describe 'lists', -> it 'encodes a list as l<list items>e', -> expect(encode ['a string', 23]).to.equal 'l8:a stringi23ee' it 'encodes empty lists', -> expect(encode []).to.equal 'le' it 'encodes nested lists', -> expect(encode [['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'], [['PI:NAME:<NAME>END_PI', 12]]]).to.equal 'll5:james4:johnell6:jordini12eeee' describe 'dictionaries', -> it 'encodes an object as d<key><value>e where keys are sorted', -> expect(encode { name: 'PI:NAME:<NAME>END_PI', age: 23 }).to.equal 'd3:agei23e4:name3:bene' it 'encodes empty objects', -> expect(encode {}).to.equal 'de' it 'encodes nested objects and lists', -> object = { people: [{name: 'PI:NAME:<NAME>END_PI', age: 20}] } expect(encode object).to.equal 'd6:peopleld3:agei20e4:name1:jeee'
[ { "context": "uld validate matching strings', ->\n { name: 'Sanjuro' }.should.respect { name: /^[TS].*j.r/ }\n\n itS", "end": 299, "score": 0.9996743202209473, "start": 292, "tag": "NAME", "value": "Sanjuro" }, { "context": " missing non-matching strings', ->\n { name: '...
test/regex.test.coffee
sabiwara/hikaku.js
4
should = null respect = require '..' describe 'Regex comparison', -> before -> delete Object::should chai = require 'chai' chai.use respect.chaiPlugin() should = chai.should() describe 'Regex literal', -> it 'should validate matching strings', -> { name: 'Sanjuro' }.should.respect { name: /^[TS].*j.r/ } itShouldNot 'validate missing non-matching strings', -> { name: 'Saburo' }.should.respect { name: /^[TS].*j.r/ } , 'expected { name: \'Saburo\' } to respect { name: /^[TS].*j.r/ }' it 'should validate an equal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/ } itShouldNot 'validate an unequal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/i } , 'expected { pattern: /^[TS].*j.r/ } to respect { pattern: /^[TS].*j.r/i }' itShouldNot 'validate non-strings', -> { name: 5 }.should.respect { name: /5/ } , 'expected { name: 5 } to respect { name: /5/ }' itShouldNot 'not validate null values', -> { name: null }.should.respect { name: /null/ } , 'expected { name: null } to respect { name: /null/ }' itShouldNot 'validate missing absent values', -> { }.should.respect { name: /undefined/ } , 'expected {} to respect { name: /undefined/ }' describe 'Regex object', -> it 'should validate matching strings', -> { name: 'Sanjuro' }.should.respect { name: new RegExp('^[TS].*j.r') } itShouldNot 'validate missing non-matching strings', -> { name: 'Saburo' }.should.respect { name: new RegExp('^[TS].*j.r') } , 'expected { name: \'Saburo\' } to respect { name: /^[TS].*j.r/ }' describe 'when `types` option is disabled', -> itShouldNot 'validate validate matching strings when `regex` is false', -> { name: 'Sanjuro' }.should.respect { name: /^[TS].*j.r/ }, regex: false , 'expected { name: \'Sanjuro\' } to respect { name: /^[TS].*j.r/ }'
162694
should = null respect = require '..' describe 'Regex comparison', -> before -> delete Object::should chai = require 'chai' chai.use respect.chaiPlugin() should = chai.should() describe 'Regex literal', -> it 'should validate matching strings', -> { name: '<NAME>' }.should.respect { name: /^[TS].*j.r/ } itShouldNot 'validate missing non-matching strings', -> { name: '<NAME>' }.should.respect { name: /^[TS].*j.r/ } , 'expected { name: \'<NAME>\' } to respect { name: /^[TS].*j.r/ }' it 'should validate an equal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/ } itShouldNot 'validate an unequal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/i } , 'expected { pattern: /^[TS].*j.r/ } to respect { pattern: /^[TS].*j.r/i }' itShouldNot 'validate non-strings', -> { name: 5 }.should.respect { name: /5/ } , 'expected { name: 5 } to respect { name: /5/ }' itShouldNot 'not validate null values', -> { name: null }.should.respect { name: /null/ } , 'expected { name: null } to respect { name: /null/ }' itShouldNot 'validate missing absent values', -> { }.should.respect { name: /undefined/ } , 'expected {} to respect { name: /undefined/ }' describe 'Regex object', -> it 'should validate matching strings', -> { name: '<NAME>' }.should.respect { name: new RegExp('^[TS].*j.r') } itShouldNot 'validate missing non-matching strings', -> { name: '<NAME>' }.should.respect { name: new RegExp('^[TS].*j.r') } , 'expected { name: \'<NAME>\' } to respect { name: /^[TS].*j.r/ }' describe 'when `types` option is disabled', -> itShouldNot 'validate validate matching strings when `regex` is false', -> { name: '<NAME>' }.should.respect { name: /^[TS].*j.r/ }, regex: false , 'expected { name: \'<NAME>\' } to respect { name: /^[TS].*j.r/ }'
true
should = null respect = require '..' describe 'Regex comparison', -> before -> delete Object::should chai = require 'chai' chai.use respect.chaiPlugin() should = chai.should() describe 'Regex literal', -> it 'should validate matching strings', -> { name: 'PI:NAME:<NAME>END_PI' }.should.respect { name: /^[TS].*j.r/ } itShouldNot 'validate missing non-matching strings', -> { name: 'PI:NAME:<NAME>END_PI' }.should.respect { name: /^[TS].*j.r/ } , 'expected { name: \'PI:NAME:<NAME>END_PI\' } to respect { name: /^[TS].*j.r/ }' it 'should validate an equal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/ } itShouldNot 'validate an unequal RegExp', -> { pattern: /^[TS].*j.r/ }.should.respect { pattern: /^[TS].*j.r/i } , 'expected { pattern: /^[TS].*j.r/ } to respect { pattern: /^[TS].*j.r/i }' itShouldNot 'validate non-strings', -> { name: 5 }.should.respect { name: /5/ } , 'expected { name: 5 } to respect { name: /5/ }' itShouldNot 'not validate null values', -> { name: null }.should.respect { name: /null/ } , 'expected { name: null } to respect { name: /null/ }' itShouldNot 'validate missing absent values', -> { }.should.respect { name: /undefined/ } , 'expected {} to respect { name: /undefined/ }' describe 'Regex object', -> it 'should validate matching strings', -> { name: 'PI:NAME:<NAME>END_PI' }.should.respect { name: new RegExp('^[TS].*j.r') } itShouldNot 'validate missing non-matching strings', -> { name: 'PI:NAME:<NAME>END_PI' }.should.respect { name: new RegExp('^[TS].*j.r') } , 'expected { name: \'PI:NAME:<NAME>END_PI\' } to respect { name: /^[TS].*j.r/ }' describe 'when `types` option is disabled', -> itShouldNot 'validate validate matching strings when `regex` is false', -> { name: 'PI:NAME:<NAME>END_PI' }.should.respect { name: /^[TS].*j.r/ }, regex: false , 'expected { name: \'PI:NAME:<NAME>END_PI\' } to respect { name: /^[TS].*j.r/ }'
[ { "context": "# This has a fork list and manages it.\n#\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 144, "score": 0.9998915791511536, "start": 130, "tag": "NAME", "value": "Toru Nagashima" } ]
src/code-path-analysis/fork-context.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview A class to operate forking. # # This is state of forking. # This has a fork list and manages it. # # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' CodePathSegment = require './code-path-segment' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets whether or not a given segment is reachable. # # @param {CodePathSegment} segment - A segment to get. # @returns {boolean} `true` if the segment is reachable. ### isReachable = (segment) -> segment.reachable ###* # Creates new segments from the specific range of `context.segmentsList`. # # When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and # `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. # This `h` is from `b`, `d`, and `f`. # # @param {ForkContext} context - An instance. # @param {number} begin - The first index of the previous segments. # @param {number} end - The last index of the previous segments. # @param {Function} create - A factory function of new segments. # @returns {CodePathSegment[]} New segments. ### makeSegments = ({segmentsList: list, count, idGenerator}, begin, end, create) -> normalizedBegin = if begin >= 0 then begin else list.length + begin normalizedEnd = if end >= 0 then end else list.length + end create( idGenerator.next() (list[j][i] for j in [normalizedBegin..normalizedEnd]) ) for i in [0...count] ###* # `segments` becomes doubly in a `finally` block. Then if a code path exits by a # control statement (such as `break`, `continue`) from the `finally` block, the # destination's segments may be half of the source segments. In that case, this # merges segments. # # @param {ForkContext} context - An instance. # @param {CodePathSegment[]} segments - Segments to merge. # @returns {CodePathSegment[]} The merged segments. ### mergeExtraSegments = ({count, idGenerator}, segments) -> currentSegments = segments while currentSegments.length > count merged = [] length = (currentSegments.length / 2) | 0 for i in [0...length] merged.push( CodePathSegment.newNext idGenerator.next(), [ currentSegments[i] currentSegments[i + length] ] ) currentSegments = merged currentSegments #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ ###* # A class to manage forking. ### class ForkContext ###* # @param {IdGenerator} idGenerator - An identifier generator for segments. # @param {ForkContext|null} upper - An upper fork context. # @param {number} count - A number of parallel segments. ### constructor: (@idGenerator, @upper, @count) -> @segmentsList = [] ###* # Creates new segments from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeNext: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newNext ###* # Creates new segments from this context. # The new segments is always unreachable. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeUnreachable: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newUnreachable ###* # Creates new segments from this context. # The new segments don't have connections for previous segments. # But these inherit the reachable flag from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeDisconnected: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newDisconnected ###* # Adds segments into this context. # The added segments become the head. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### add: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.push mergeExtraSegments @, segments ###* # Replaces the head segments with given segments. # The current head segments are removed. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### replaceHead: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.splice -1, 1, mergeExtraSegments @, segments ###* # Adds all segments of a given fork context into this context. # # @param {ForkContext} context - A fork context to add. # @returns {void} ### addAll: ({count, segmentsList: source}) -> assert count is @count @segmentsList.push source... ###* # Clears all secments in this context. # # @returns {void} ### clear: -> @segmentsList = [] ###* # Creates the root fork context. # # @param {IdGenerator} idGenerator - An identifier generator for segments. # @returns {ForkContext} New fork context. ### @newRoot: (idGenerator) -> context = new ForkContext idGenerator, null, 1 context.add [CodePathSegment.newRoot idGenerator.next()] context ###* # Creates an empty fork context preceded by a given context. # # @param {ForkContext} parentContext - The parent fork context. # @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. # @returns {ForkContext} New fork context. ### @newEmpty: (parentContext, forkLeavingPath) -> new ForkContext( parentContext.idGenerator parentContext (if forkLeavingPath then 2 else 1) * parentContext.count ) ###* # The head segments. # @type {CodePathSegment[]} ### Object.defineProperty ForkContext::, 'head', get: -> list = @segmentsList if list.length is 0 then [] else list[list.length - 1] ###* # A flag which shows empty. # @type {boolean} ### Object.defineProperty ForkContext::, 'empty', get: -> @segmentsList.length is 0 ###* # A flag which shows reachable. # @type {boolean} ### Object.defineProperty ForkContext::, 'reachable', get: -> segments = @head segments.length > 0 and segments.some isReachable module.exports = ForkContext
10571
###* # @fileoverview A class to operate forking. # # This is state of forking. # This has a fork list and manages it. # # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' CodePathSegment = require './code-path-segment' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets whether or not a given segment is reachable. # # @param {CodePathSegment} segment - A segment to get. # @returns {boolean} `true` if the segment is reachable. ### isReachable = (segment) -> segment.reachable ###* # Creates new segments from the specific range of `context.segmentsList`. # # When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and # `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. # This `h` is from `b`, `d`, and `f`. # # @param {ForkContext} context - An instance. # @param {number} begin - The first index of the previous segments. # @param {number} end - The last index of the previous segments. # @param {Function} create - A factory function of new segments. # @returns {CodePathSegment[]} New segments. ### makeSegments = ({segmentsList: list, count, idGenerator}, begin, end, create) -> normalizedBegin = if begin >= 0 then begin else list.length + begin normalizedEnd = if end >= 0 then end else list.length + end create( idGenerator.next() (list[j][i] for j in [normalizedBegin..normalizedEnd]) ) for i in [0...count] ###* # `segments` becomes doubly in a `finally` block. Then if a code path exits by a # control statement (such as `break`, `continue`) from the `finally` block, the # destination's segments may be half of the source segments. In that case, this # merges segments. # # @param {ForkContext} context - An instance. # @param {CodePathSegment[]} segments - Segments to merge. # @returns {CodePathSegment[]} The merged segments. ### mergeExtraSegments = ({count, idGenerator}, segments) -> currentSegments = segments while currentSegments.length > count merged = [] length = (currentSegments.length / 2) | 0 for i in [0...length] merged.push( CodePathSegment.newNext idGenerator.next(), [ currentSegments[i] currentSegments[i + length] ] ) currentSegments = merged currentSegments #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ ###* # A class to manage forking. ### class ForkContext ###* # @param {IdGenerator} idGenerator - An identifier generator for segments. # @param {ForkContext|null} upper - An upper fork context. # @param {number} count - A number of parallel segments. ### constructor: (@idGenerator, @upper, @count) -> @segmentsList = [] ###* # Creates new segments from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeNext: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newNext ###* # Creates new segments from this context. # The new segments is always unreachable. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeUnreachable: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newUnreachable ###* # Creates new segments from this context. # The new segments don't have connections for previous segments. # But these inherit the reachable flag from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeDisconnected: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newDisconnected ###* # Adds segments into this context. # The added segments become the head. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### add: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.push mergeExtraSegments @, segments ###* # Replaces the head segments with given segments. # The current head segments are removed. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### replaceHead: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.splice -1, 1, mergeExtraSegments @, segments ###* # Adds all segments of a given fork context into this context. # # @param {ForkContext} context - A fork context to add. # @returns {void} ### addAll: ({count, segmentsList: source}) -> assert count is @count @segmentsList.push source... ###* # Clears all secments in this context. # # @returns {void} ### clear: -> @segmentsList = [] ###* # Creates the root fork context. # # @param {IdGenerator} idGenerator - An identifier generator for segments. # @returns {ForkContext} New fork context. ### @newRoot: (idGenerator) -> context = new ForkContext idGenerator, null, 1 context.add [CodePathSegment.newRoot idGenerator.next()] context ###* # Creates an empty fork context preceded by a given context. # # @param {ForkContext} parentContext - The parent fork context. # @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. # @returns {ForkContext} New fork context. ### @newEmpty: (parentContext, forkLeavingPath) -> new ForkContext( parentContext.idGenerator parentContext (if forkLeavingPath then 2 else 1) * parentContext.count ) ###* # The head segments. # @type {CodePathSegment[]} ### Object.defineProperty ForkContext::, 'head', get: -> list = @segmentsList if list.length is 0 then [] else list[list.length - 1] ###* # A flag which shows empty. # @type {boolean} ### Object.defineProperty ForkContext::, 'empty', get: -> @segmentsList.length is 0 ###* # A flag which shows reachable. # @type {boolean} ### Object.defineProperty ForkContext::, 'reachable', get: -> segments = @head segments.length > 0 and segments.some isReachable module.exports = ForkContext
true
###* # @fileoverview A class to operate forking. # # This is state of forking. # This has a fork list and manages it. # # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' CodePathSegment = require './code-path-segment' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets whether or not a given segment is reachable. # # @param {CodePathSegment} segment - A segment to get. # @returns {boolean} `true` if the segment is reachable. ### isReachable = (segment) -> segment.reachable ###* # Creates new segments from the specific range of `context.segmentsList`. # # When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and # `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. # This `h` is from `b`, `d`, and `f`. # # @param {ForkContext} context - An instance. # @param {number} begin - The first index of the previous segments. # @param {number} end - The last index of the previous segments. # @param {Function} create - A factory function of new segments. # @returns {CodePathSegment[]} New segments. ### makeSegments = ({segmentsList: list, count, idGenerator}, begin, end, create) -> normalizedBegin = if begin >= 0 then begin else list.length + begin normalizedEnd = if end >= 0 then end else list.length + end create( idGenerator.next() (list[j][i] for j in [normalizedBegin..normalizedEnd]) ) for i in [0...count] ###* # `segments` becomes doubly in a `finally` block. Then if a code path exits by a # control statement (such as `break`, `continue`) from the `finally` block, the # destination's segments may be half of the source segments. In that case, this # merges segments. # # @param {ForkContext} context - An instance. # @param {CodePathSegment[]} segments - Segments to merge. # @returns {CodePathSegment[]} The merged segments. ### mergeExtraSegments = ({count, idGenerator}, segments) -> currentSegments = segments while currentSegments.length > count merged = [] length = (currentSegments.length / 2) | 0 for i in [0...length] merged.push( CodePathSegment.newNext idGenerator.next(), [ currentSegments[i] currentSegments[i + length] ] ) currentSegments = merged currentSegments #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ ###* # A class to manage forking. ### class ForkContext ###* # @param {IdGenerator} idGenerator - An identifier generator for segments. # @param {ForkContext|null} upper - An upper fork context. # @param {number} count - A number of parallel segments. ### constructor: (@idGenerator, @upper, @count) -> @segmentsList = [] ###* # Creates new segments from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeNext: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newNext ###* # Creates new segments from this context. # The new segments is always unreachable. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeUnreachable: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newUnreachable ###* # Creates new segments from this context. # The new segments don't have connections for previous segments. # But these inherit the reachable flag from this context. # # @param {number} begin - The first index of previous segments. # @param {number} end - The last index of previous segments. # @returns {CodePathSegment[]} New segments. ### makeDisconnected: (begin, end) -> makeSegments @, begin, end, CodePathSegment.newDisconnected ###* # Adds segments into this context. # The added segments become the head. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### add: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.push mergeExtraSegments @, segments ###* # Replaces the head segments with given segments. # The current head segments are removed. # # @param {CodePathSegment[]} segments - Segments to add. # @returns {void} ### replaceHead: (segments) -> assert segments.length >= @count, "#{segments.length} >= #{@count}" @segmentsList.splice -1, 1, mergeExtraSegments @, segments ###* # Adds all segments of a given fork context into this context. # # @param {ForkContext} context - A fork context to add. # @returns {void} ### addAll: ({count, segmentsList: source}) -> assert count is @count @segmentsList.push source... ###* # Clears all secments in this context. # # @returns {void} ### clear: -> @segmentsList = [] ###* # Creates the root fork context. # # @param {IdGenerator} idGenerator - An identifier generator for segments. # @returns {ForkContext} New fork context. ### @newRoot: (idGenerator) -> context = new ForkContext idGenerator, null, 1 context.add [CodePathSegment.newRoot idGenerator.next()] context ###* # Creates an empty fork context preceded by a given context. # # @param {ForkContext} parentContext - The parent fork context. # @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. # @returns {ForkContext} New fork context. ### @newEmpty: (parentContext, forkLeavingPath) -> new ForkContext( parentContext.idGenerator parentContext (if forkLeavingPath then 2 else 1) * parentContext.count ) ###* # The head segments. # @type {CodePathSegment[]} ### Object.defineProperty ForkContext::, 'head', get: -> list = @segmentsList if list.length is 0 then [] else list[list.length - 1] ###* # A flag which shows empty. # @type {boolean} ### Object.defineProperty ForkContext::, 'empty', get: -> @segmentsList.length is 0 ###* # A flag which shows reachable. # @type {boolean} ### Object.defineProperty ForkContext::, 'reachable', get: -> segments = @head segments.length > 0 and segments.some isReachable module.exports = ForkContext
[ { "context": ":\n#\n# Configuration:\n#\n# Commands:\n#\n# Author:\n# Thomas Howe - ghostofbasho@gmail.com\n#\n\n_ = require('undersco", "end": 128, "score": 0.9998682141304016, "start": 117, "tag": "NAME", "value": "Thomas Howe" }, { "context": "ation:\n#\n# Commands:\n#\n# Author...
src/scripts/session.coffee
green-bot/hubot-session
1
# Description: # Handles session aware dialogs. # # Dependencies: # # Configuration: # # Commands: # # Author: # Thomas Howe - ghostofbasho@gmail.com # _ = require('underscore') Async = require('async') Bluebird = require('bluebird') ChildProcess = require("child_process") Events = require('events') LanguageFilter = require('watson-translate-stream') Mailer = require("nodemailer") Os = require("os") Pipe = require("multipipe") Promise = require('node-promise') Redis = require('redis') ShortUUID = require 'shortid' Stream = require('stream') Url = require("url") Us = require("underscore.string") Util = require('util') # Setup the connection to the database connectionString = process.env.MONGO_URL or 'localhost/greenbot' Db = require('monk')(connectionString) Rooms = Db.get('Rooms') Sessions = Db.get('Sessions') # Setup the connect to Redis Bluebird.promisifyAll(Redis.RedisClient.prototype) Bluebird.promisifyAll(Redis.Multi.prototype) client = Redis.createClient() egressClient = Redis.createClient() sessionClient = Redis.createClient() INGRESS_MSGS_FEED = 'INGRESS_MSGS' EGRESS_MSGS_FEED = 'EGRESS_MSGS' SESSION_NAME = process.env.SESSION_NAME || 'BASH' NEW_SESSIONS_FEED = SESSION_NAME + '.NEW_SESSIONS' SESSION_ENDED_FEED = 'COMPLETED_SESSIONS' # Set the default directory for scripts DEF_SCRIPT_DIR = process.env.DEF_SCRIPT_DIR || '.' module.exports = (robot) -> # Helper functions info = (text) -> console.log text genSessionKey = (msg) -> msg.src + "_" + msg.dst cleanText = (text) -> return "" unless text text.trim().toLowerCase() msg_text = (msg) -> msg.txt visitor_name = (msg) -> msg.src.toLowerCase() isJson = (str) -> # When a text message comes from a session, if it's a valid JSON # string, we will treat it as a command or data. This function # allows us to figure that out. try JSON.parse str catch e return false true ingressList = (sessionKey) -> sessionKey + '.ingress' egressList = (sessionKey) -> sessionKey + '.egress' sessionUpdate = Async.queue (session, callback) -> information = session.information() sessionId = session.sessionId cb = (err, session) -> info "Threw error on database update #{err}" if err callback() Sessions.findOne {sessionId: sessionId}, (err, session) -> if session? Sessions.findAndModify { query: sessionId: sessionId update: information options: new: true }, cb else info 'Creating a new session' information.createdAt = Date.now() Sessions.insert information, cb class Session @active = [] @findOrCreate: (msg, cb) -> # All messages that come from the network end up here. session_name = genSessionKey(msg) session = @active[session_name] if session # We already have a session, so send it off. session.ingressMsg(msg.txt) else # No session active. Kick one off. name = process.env.DEV_ROOM_NAME or msg.dst.toLowerCase() keyword = cleanText(msg.txt) info "Looking for #{name}:#{keyword}" Rooms.findOne {name: name, keyword: keyword}, (err, room) -> info "Can't find #{name}:#{keyword}" if err if room info "Found room #{name}:#{room.keyword}:#{room.default_cmd}" new Session(msg, room, cb) return if room or err # No room and keyword combination matched # Return the default if there's one. info 'No room/keyword found. Check for default' Rooms.findOne {name: name, default: true}, (err, room) -> if room info "Found room #{name}, starting session" new Session(msg, room, cb) else info 'No default room, no matching keyword. Fail.' @complete: (sessionId) -> # All messages that come from the network end up here. info "Notification of script complete for session #{sessionId}" for s of @active if @active[s].sessionId is sessionId @active[s].endSession() constructor: (@msg, @room, @cb) -> # The variables that make up a Session @transcript = [] @src = @msg.src @dst = @msg.dst.toLowerCase() @sessionKey = genSessionKey(@msg) @sessionId = ShortUUID.generate() Session.active[@sessionKey] = @ @automated = true @processStack = [] # Assemble the @command, @arguments, @opts @createSessionEnv() langQ = Sessions.findOne({src: @src}, {sort: {updatedAt: -1}}) langQ.error = (err) -> info 'Mongo error in fetch language : ' + err langQ.then (session) => if session?.lang? @lang = session.lang else @lang = process.env.DEFAULT_LANG or 'en' info 'Kicking off process with lang ' + @lang @kickOffProcess(@command, @arguments, @opts, @lang) kickOffProcess : (command, args, opts, lang) -> # Start the process, connect the pipes info 'Kicking off process ' + command sess = command: command args: args opts: opts sessionId: @sessionId newSessionRequest = JSON.stringify sess client.lpush NEW_SESSIONS_FEED, newSessionRequest client.publish NEW_SESSIONS_FEED, newSessionRequest @language = new LanguageFilter('en', lang) jsonFilter = @createJsonFilter() @egressProcessStream = Pipe(jsonFilter, @language.egressStream) egressClient.on 'message', (chan, sessionKey) => popped = (txt) => info('Popped a ' + txt) if txt lines = txt.toString().split("\n") else lines = [] for line in lines @egressProcessStream.write(line) if (line) errored = (err) -> info('Popping message returns ' + err) redisList = egressList(sessionKey) client.lpopAsync(redisList).then(popped, errored) egressClient.subscribe(EGRESS_MSGS_FEED) sessionClient.on 'message', (chan, sessionKey) -> Session.complete(sessionKey) sessionClient.subscribe(SESSION_ENDED_FEED) # Start the subscriber for the bash_process pub/sub @ingressProcessStream = @language.ingressStream @ingressProcessStream.on 'readable', () => redisList = ingressList(@sessionId) client.lpush redisList, @ingressProcessStream.read() client.publish INGRESS_MSGS_FEED, @sessionId @egressProcessStream.on "readable", () => # Send the output of the egress stream off to the network info 'Data available for reading' @egressMsg @egressProcessStream.read() @egressProcessStream.on "error", (err) -> info "Error thrown from session" info err @language.on "langChanged", (oldLang, newLang) => info "Language changed, restarting : #{oldLang} to #{newLang}" @egressProcessStream.write("Language changed, restarting conversation.") info "Restarting session." @lang = newLang nextProcess = command: @command args: @arguments opts: @opts lang: @lang @processStack.push nextProcess # @process.kill() info "New process started : #{@process.pid}" createSessionEnv: () -> if @isOwner() info "Running as the owner" if @room.test_mode is true @room.test_mode = false Db.update 'Rooms', @room.objectId, { test_mode: false }, (err, response) -> if err info "Error trying to turn off test mode : #{err}" @arguments = @room.default_cmd.split(" ") else @arguments = @room.owner_cmd.split(" ") else info "Running as a visitor" @arguments = @room.default_cmd.split(" ") @command = @arguments[0] @arguments.shift() @env = @cmdSettings() @env.INITIAL_MSG = @msg.txt @opts = cwd: DEF_SCRIPT_DIR env: @env # Now save it in the database updateDb: () -> info "Updating session #{@sessionId}" sessionUpdate.push @ information: () -> transcript: @transcript src: @src dst: @dst sessionKey: @sessionKey sessionId: @sessionId roomId: @room.objectId collectedData: @collectedData updatedAt: Date.now() lang: @lang endSession: () -> nextProcess = @processStack.shift() # If process stack has element, run that. if nextProcess? info 'Process ended. Starting a new one.' {command, args, opts, lang} = nextProcess @kickOffProcess(command, args, opts, lang) else info "Ending and recording session #{@sessionId}" robot.emit 'session:ended', @sessionId delete Session.active[@sessionKey] cmdSettings: () -> env_settings = _.clone(process.env) env_settings.SESSION_ID = @sessionId env_settings.SRC = @src env_settings.DST = @dst env_settings.ROOM_OBJECT_ID = @room.objectId for attrname of @room.settings env_settings[attrname] = @room.settings[attrname] return env_settings isOwner: () -> if @room.owners? and @src in @room.owners info "Running session #{@sessionId} as the owner" true else info "Running session #{@sessionId} as a visitor" false egressMsg: (text) => if text lines = text.toString().split("\n") else lines = [] for line in lines line = line.trim() if line.length > 0 @cb @src, line info "#{@sessionId}: #{@room.name}: #{line}" @transcript.push { direction: 'egress', text: line} @updateDb() ingressMsg: (text) => if cleanText(text) == '/human' @automated = false robot.emit 'livechat:newsession', @information() if @automated @ingressProcessStream.write("#{text}\n") else robot.emit 'livechat:ingress', @information(), text @transcript.push { direction: 'ingress', text: text} info "#{@sessionId}: #{@src}: #{text}" @updateDb() createJsonFilter: () -> # Filter out JSON as it goes through the system jsonFilter = new Stream.Transform() jsonFilter._transform = (chunk, encoding, done) -> info "Filtering JSON" lines = chunk.toString().split("\n") for line in lines do (line) -> if isJson(line) jsonFilter.emit 'json', line else jsonFilter.push(line) done() # If the message is JSON, treat it as if it were collected data jsonFilter.on 'json', (line) => info "Remembering #{line}" @collectedData = JSON.parse line @updateDb() return jsonFilter robot.on 'telnet:ingress', (msg) -> info 'Ingress message for telnet ' + JSON.stringify msg Session.findOrCreate msg, (dst, txt) -> info 'Egress message for telnet ' + txt robot.emit "telnet:egress:telnet", txt robot.on 'slack:ingress', (msg) -> Session.findOrCreate msg, (dst, txt) -> robot.emit "slack:egress", dst, txt robot.hear /(.*)/i, (hubotMsg) -> dst = hubotMsg.message.room.toLowerCase() src = hubotMsg.message.user.name.toLowerCase() msg = dst: dst src: src txt: hubotMsg.message.text Session.findOrCreate msg, (src, txt) -> user = robot.brain.userForId dst, name: src robot.send user, txt robot.on 'livechat:egress', (sessionKey, text) -> console.log "Received #{text} for #{sessionKey}"
65318
# Description: # Handles session aware dialogs. # # Dependencies: # # Configuration: # # Commands: # # Author: # <NAME> - <EMAIL> # _ = require('underscore') Async = require('async') Bluebird = require('bluebird') ChildProcess = require("child_process") Events = require('events') LanguageFilter = require('watson-translate-stream') Mailer = require("nodemailer") Os = require("os") Pipe = require("multipipe") Promise = require('node-promise') Redis = require('redis') ShortUUID = require 'shortid' Stream = require('stream') Url = require("url") Us = require("underscore.string") Util = require('util') # Setup the connection to the database connectionString = process.env.MONGO_URL or 'localhost/greenbot' Db = require('monk')(connectionString) Rooms = Db.get('Rooms') Sessions = Db.get('Sessions') # Setup the connect to Redis Bluebird.promisifyAll(Redis.RedisClient.prototype) Bluebird.promisifyAll(Redis.Multi.prototype) client = Redis.createClient() egressClient = Redis.createClient() sessionClient = Redis.createClient() INGRESS_MSGS_FEED = 'INGRESS_MSGS' EGRESS_MSGS_FEED = 'EGRESS_MSGS' SESSION_NAME = process.env.SESSION_NAME || 'BASH' NEW_SESSIONS_FEED = SESSION_NAME + '.NEW_SESSIONS' SESSION_ENDED_FEED = 'COMPLETED_SESSIONS' # Set the default directory for scripts DEF_SCRIPT_DIR = process.env.DEF_SCRIPT_DIR || '.' module.exports = (robot) -> # Helper functions info = (text) -> console.log text genSessionKey = (msg) -> msg.src + "_" + msg.dst cleanText = (text) -> return "" unless text text.trim().toLowerCase() msg_text = (msg) -> msg.txt visitor_name = (msg) -> msg.src.toLowerCase() isJson = (str) -> # When a text message comes from a session, if it's a valid JSON # string, we will treat it as a command or data. This function # allows us to figure that out. try JSON.parse str catch e return false true ingressList = (sessionKey) -> sessionKey + '.ingress' egressList = (sessionKey) -> sessionKey + '.egress' sessionUpdate = Async.queue (session, callback) -> information = session.information() sessionId = session.sessionId cb = (err, session) -> info "Threw error on database update #{err}" if err callback() Sessions.findOne {sessionId: sessionId}, (err, session) -> if session? Sessions.findAndModify { query: sessionId: sessionId update: information options: new: true }, cb else info 'Creating a new session' information.createdAt = Date.now() Sessions.insert information, cb class Session @active = [] @findOrCreate: (msg, cb) -> # All messages that come from the network end up here. session_name = genSessionKey(msg) session = @active[session_name] if session # We already have a session, so send it off. session.ingressMsg(msg.txt) else # No session active. Kick one off. name = process.env.DEV_ROOM_NAME or msg.dst.toLowerCase() keyword = cleanText(msg.txt) info "Looking for #{name}:#{keyword}" Rooms.findOne {name: name, keyword: keyword}, (err, room) -> info "Can't find #{name}:#{keyword}" if err if room info "Found room #{name}:#{room.keyword}:#{room.default_cmd}" new Session(msg, room, cb) return if room or err # No room and keyword combination matched # Return the default if there's one. info 'No room/keyword found. Check for default' Rooms.findOne {name: name, default: true}, (err, room) -> if room info "Found room #{name}, starting session" new Session(msg, room, cb) else info 'No default room, no matching keyword. Fail.' @complete: (sessionId) -> # All messages that come from the network end up here. info "Notification of script complete for session #{sessionId}" for s of @active if @active[s].sessionId is sessionId @active[s].endSession() constructor: (@msg, @room, @cb) -> # The variables that make up a Session @transcript = [] @src = @msg.src @dst = @msg.dst.toLowerCase() @sessionKey = genSessionKey(@msg) @sessionId = ShortUUID.generate() Session.active[@sessionKey] = @ @automated = true @processStack = [] # Assemble the @command, @arguments, @opts @createSessionEnv() langQ = Sessions.findOne({src: @src}, {sort: {updatedAt: -1}}) langQ.error = (err) -> info 'Mongo error in fetch language : ' + err langQ.then (session) => if session?.lang? @lang = session.lang else @lang = process.env.DEFAULT_LANG or 'en' info 'Kicking off process with lang ' + @lang @kickOffProcess(@command, @arguments, @opts, @lang) kickOffProcess : (command, args, opts, lang) -> # Start the process, connect the pipes info 'Kicking off process ' + command sess = command: command args: args opts: opts sessionId: @sessionId newSessionRequest = JSON.stringify sess client.lpush NEW_SESSIONS_FEED, newSessionRequest client.publish NEW_SESSIONS_FEED, newSessionRequest @language = new LanguageFilter('en', lang) jsonFilter = @createJsonFilter() @egressProcessStream = Pipe(jsonFilter, @language.egressStream) egressClient.on 'message', (chan, sessionKey) => popped = (txt) => info('Popped a ' + txt) if txt lines = txt.toString().split("\n") else lines = [] for line in lines @egressProcessStream.write(line) if (line) errored = (err) -> info('Popping message returns ' + err) redisList = egressList(sessionKey) client.lpopAsync(redisList).then(popped, errored) egressClient.subscribe(EGRESS_MSGS_FEED) sessionClient.on 'message', (chan, sessionKey) -> Session.complete(sessionKey) sessionClient.subscribe(SESSION_ENDED_FEED) # Start the subscriber for the bash_process pub/sub @ingressProcessStream = @language.ingressStream @ingressProcessStream.on 'readable', () => redisList = ingressList(@sessionId) client.lpush redisList, @ingressProcessStream.read() client.publish INGRESS_MSGS_FEED, @sessionId @egressProcessStream.on "readable", () => # Send the output of the egress stream off to the network info 'Data available for reading' @egressMsg @egressProcessStream.read() @egressProcessStream.on "error", (err) -> info "Error thrown from session" info err @language.on "langChanged", (oldLang, newLang) => info "Language changed, restarting : #{oldLang} to #{newLang}" @egressProcessStream.write("Language changed, restarting conversation.") info "Restarting session." @lang = newLang nextProcess = command: @command args: @arguments opts: @opts lang: @lang @processStack.push nextProcess # @process.kill() info "New process started : #{@process.pid}" createSessionEnv: () -> if @isOwner() info "Running as the owner" if @room.test_mode is true @room.test_mode = false Db.update 'Rooms', @room.objectId, { test_mode: false }, (err, response) -> if err info "Error trying to turn off test mode : #{err}" @arguments = @room.default_cmd.split(" ") else @arguments = @room.owner_cmd.split(" ") else info "Running as a visitor" @arguments = @room.default_cmd.split(" ") @command = @arguments[0] @arguments.shift() @env = @cmdSettings() @env.INITIAL_MSG = @msg.txt @opts = cwd: DEF_SCRIPT_DIR env: @env # Now save it in the database updateDb: () -> info "Updating session #{@sessionId}" sessionUpdate.push @ information: () -> transcript: @transcript src: @src dst: @dst sessionKey: @sessionKey sessionId: @sessionId roomId: @room.objectId collectedData: @collectedData updatedAt: Date.now() lang: @lang endSession: () -> nextProcess = @processStack.shift() # If process stack has element, run that. if nextProcess? info 'Process ended. Starting a new one.' {command, args, opts, lang} = nextProcess @kickOffProcess(command, args, opts, lang) else info "Ending and recording session #{@sessionId}" robot.emit 'session:ended', @sessionId delete Session.active[@sessionKey] cmdSettings: () -> env_settings = _.clone(process.env) env_settings.SESSION_ID = @sessionId env_settings.SRC = @src env_settings.DST = @dst env_settings.ROOM_OBJECT_ID = @room.objectId for attrname of @room.settings env_settings[attrname] = @room.settings[attrname] return env_settings isOwner: () -> if @room.owners? and @src in @room.owners info "Running session #{@sessionId} as the owner" true else info "Running session #{@sessionId} as a visitor" false egressMsg: (text) => if text lines = text.toString().split("\n") else lines = [] for line in lines line = line.trim() if line.length > 0 @cb @src, line info "#{@sessionId}: #{@room.name}: #{line}" @transcript.push { direction: 'egress', text: line} @updateDb() ingressMsg: (text) => if cleanText(text) == '/human' @automated = false robot.emit 'livechat:newsession', @information() if @automated @ingressProcessStream.write("#{text}\n") else robot.emit 'livechat:ingress', @information(), text @transcript.push { direction: 'ingress', text: text} info "#{@sessionId}: #{@src}: #{text}" @updateDb() createJsonFilter: () -> # Filter out JSON as it goes through the system jsonFilter = new Stream.Transform() jsonFilter._transform = (chunk, encoding, done) -> info "Filtering JSON" lines = chunk.toString().split("\n") for line in lines do (line) -> if isJson(line) jsonFilter.emit 'json', line else jsonFilter.push(line) done() # If the message is JSON, treat it as if it were collected data jsonFilter.on 'json', (line) => info "Remembering #{line}" @collectedData = JSON.parse line @updateDb() return jsonFilter robot.on 'telnet:ingress', (msg) -> info 'Ingress message for telnet ' + JSON.stringify msg Session.findOrCreate msg, (dst, txt) -> info 'Egress message for telnet ' + txt robot.emit "telnet:egress:telnet", txt robot.on 'slack:ingress', (msg) -> Session.findOrCreate msg, (dst, txt) -> robot.emit "slack:egress", dst, txt robot.hear /(.*)/i, (hubotMsg) -> dst = hubotMsg.message.room.toLowerCase() src = hubotMsg.message.user.name.toLowerCase() msg = dst: dst src: src txt: hubotMsg.message.text Session.findOrCreate msg, (src, txt) -> user = robot.brain.userForId dst, name: src robot.send user, txt robot.on 'livechat:egress', (sessionKey, text) -> console.log "Received #{text} for #{sessionKey}"
true
# Description: # Handles session aware dialogs. # # Dependencies: # # Configuration: # # Commands: # # Author: # PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI # _ = require('underscore') Async = require('async') Bluebird = require('bluebird') ChildProcess = require("child_process") Events = require('events') LanguageFilter = require('watson-translate-stream') Mailer = require("nodemailer") Os = require("os") Pipe = require("multipipe") Promise = require('node-promise') Redis = require('redis') ShortUUID = require 'shortid' Stream = require('stream') Url = require("url") Us = require("underscore.string") Util = require('util') # Setup the connection to the database connectionString = process.env.MONGO_URL or 'localhost/greenbot' Db = require('monk')(connectionString) Rooms = Db.get('Rooms') Sessions = Db.get('Sessions') # Setup the connect to Redis Bluebird.promisifyAll(Redis.RedisClient.prototype) Bluebird.promisifyAll(Redis.Multi.prototype) client = Redis.createClient() egressClient = Redis.createClient() sessionClient = Redis.createClient() INGRESS_MSGS_FEED = 'INGRESS_MSGS' EGRESS_MSGS_FEED = 'EGRESS_MSGS' SESSION_NAME = process.env.SESSION_NAME || 'BASH' NEW_SESSIONS_FEED = SESSION_NAME + '.NEW_SESSIONS' SESSION_ENDED_FEED = 'COMPLETED_SESSIONS' # Set the default directory for scripts DEF_SCRIPT_DIR = process.env.DEF_SCRIPT_DIR || '.' module.exports = (robot) -> # Helper functions info = (text) -> console.log text genSessionKey = (msg) -> msg.src + "_" + msg.dst cleanText = (text) -> return "" unless text text.trim().toLowerCase() msg_text = (msg) -> msg.txt visitor_name = (msg) -> msg.src.toLowerCase() isJson = (str) -> # When a text message comes from a session, if it's a valid JSON # string, we will treat it as a command or data. This function # allows us to figure that out. try JSON.parse str catch e return false true ingressList = (sessionKey) -> sessionKey + '.ingress' egressList = (sessionKey) -> sessionKey + '.egress' sessionUpdate = Async.queue (session, callback) -> information = session.information() sessionId = session.sessionId cb = (err, session) -> info "Threw error on database update #{err}" if err callback() Sessions.findOne {sessionId: sessionId}, (err, session) -> if session? Sessions.findAndModify { query: sessionId: sessionId update: information options: new: true }, cb else info 'Creating a new session' information.createdAt = Date.now() Sessions.insert information, cb class Session @active = [] @findOrCreate: (msg, cb) -> # All messages that come from the network end up here. session_name = genSessionKey(msg) session = @active[session_name] if session # We already have a session, so send it off. session.ingressMsg(msg.txt) else # No session active. Kick one off. name = process.env.DEV_ROOM_NAME or msg.dst.toLowerCase() keyword = cleanText(msg.txt) info "Looking for #{name}:#{keyword}" Rooms.findOne {name: name, keyword: keyword}, (err, room) -> info "Can't find #{name}:#{keyword}" if err if room info "Found room #{name}:#{room.keyword}:#{room.default_cmd}" new Session(msg, room, cb) return if room or err # No room and keyword combination matched # Return the default if there's one. info 'No room/keyword found. Check for default' Rooms.findOne {name: name, default: true}, (err, room) -> if room info "Found room #{name}, starting session" new Session(msg, room, cb) else info 'No default room, no matching keyword. Fail.' @complete: (sessionId) -> # All messages that come from the network end up here. info "Notification of script complete for session #{sessionId}" for s of @active if @active[s].sessionId is sessionId @active[s].endSession() constructor: (@msg, @room, @cb) -> # The variables that make up a Session @transcript = [] @src = @msg.src @dst = @msg.dst.toLowerCase() @sessionKey = genSessionKey(@msg) @sessionId = ShortUUID.generate() Session.active[@sessionKey] = @ @automated = true @processStack = [] # Assemble the @command, @arguments, @opts @createSessionEnv() langQ = Sessions.findOne({src: @src}, {sort: {updatedAt: -1}}) langQ.error = (err) -> info 'Mongo error in fetch language : ' + err langQ.then (session) => if session?.lang? @lang = session.lang else @lang = process.env.DEFAULT_LANG or 'en' info 'Kicking off process with lang ' + @lang @kickOffProcess(@command, @arguments, @opts, @lang) kickOffProcess : (command, args, opts, lang) -> # Start the process, connect the pipes info 'Kicking off process ' + command sess = command: command args: args opts: opts sessionId: @sessionId newSessionRequest = JSON.stringify sess client.lpush NEW_SESSIONS_FEED, newSessionRequest client.publish NEW_SESSIONS_FEED, newSessionRequest @language = new LanguageFilter('en', lang) jsonFilter = @createJsonFilter() @egressProcessStream = Pipe(jsonFilter, @language.egressStream) egressClient.on 'message', (chan, sessionKey) => popped = (txt) => info('Popped a ' + txt) if txt lines = txt.toString().split("\n") else lines = [] for line in lines @egressProcessStream.write(line) if (line) errored = (err) -> info('Popping message returns ' + err) redisList = egressList(sessionKey) client.lpopAsync(redisList).then(popped, errored) egressClient.subscribe(EGRESS_MSGS_FEED) sessionClient.on 'message', (chan, sessionKey) -> Session.complete(sessionKey) sessionClient.subscribe(SESSION_ENDED_FEED) # Start the subscriber for the bash_process pub/sub @ingressProcessStream = @language.ingressStream @ingressProcessStream.on 'readable', () => redisList = ingressList(@sessionId) client.lpush redisList, @ingressProcessStream.read() client.publish INGRESS_MSGS_FEED, @sessionId @egressProcessStream.on "readable", () => # Send the output of the egress stream off to the network info 'Data available for reading' @egressMsg @egressProcessStream.read() @egressProcessStream.on "error", (err) -> info "Error thrown from session" info err @language.on "langChanged", (oldLang, newLang) => info "Language changed, restarting : #{oldLang} to #{newLang}" @egressProcessStream.write("Language changed, restarting conversation.") info "Restarting session." @lang = newLang nextProcess = command: @command args: @arguments opts: @opts lang: @lang @processStack.push nextProcess # @process.kill() info "New process started : #{@process.pid}" createSessionEnv: () -> if @isOwner() info "Running as the owner" if @room.test_mode is true @room.test_mode = false Db.update 'Rooms', @room.objectId, { test_mode: false }, (err, response) -> if err info "Error trying to turn off test mode : #{err}" @arguments = @room.default_cmd.split(" ") else @arguments = @room.owner_cmd.split(" ") else info "Running as a visitor" @arguments = @room.default_cmd.split(" ") @command = @arguments[0] @arguments.shift() @env = @cmdSettings() @env.INITIAL_MSG = @msg.txt @opts = cwd: DEF_SCRIPT_DIR env: @env # Now save it in the database updateDb: () -> info "Updating session #{@sessionId}" sessionUpdate.push @ information: () -> transcript: @transcript src: @src dst: @dst sessionKey: @sessionKey sessionId: @sessionId roomId: @room.objectId collectedData: @collectedData updatedAt: Date.now() lang: @lang endSession: () -> nextProcess = @processStack.shift() # If process stack has element, run that. if nextProcess? info 'Process ended. Starting a new one.' {command, args, opts, lang} = nextProcess @kickOffProcess(command, args, opts, lang) else info "Ending and recording session #{@sessionId}" robot.emit 'session:ended', @sessionId delete Session.active[@sessionKey] cmdSettings: () -> env_settings = _.clone(process.env) env_settings.SESSION_ID = @sessionId env_settings.SRC = @src env_settings.DST = @dst env_settings.ROOM_OBJECT_ID = @room.objectId for attrname of @room.settings env_settings[attrname] = @room.settings[attrname] return env_settings isOwner: () -> if @room.owners? and @src in @room.owners info "Running session #{@sessionId} as the owner" true else info "Running session #{@sessionId} as a visitor" false egressMsg: (text) => if text lines = text.toString().split("\n") else lines = [] for line in lines line = line.trim() if line.length > 0 @cb @src, line info "#{@sessionId}: #{@room.name}: #{line}" @transcript.push { direction: 'egress', text: line} @updateDb() ingressMsg: (text) => if cleanText(text) == '/human' @automated = false robot.emit 'livechat:newsession', @information() if @automated @ingressProcessStream.write("#{text}\n") else robot.emit 'livechat:ingress', @information(), text @transcript.push { direction: 'ingress', text: text} info "#{@sessionId}: #{@src}: #{text}" @updateDb() createJsonFilter: () -> # Filter out JSON as it goes through the system jsonFilter = new Stream.Transform() jsonFilter._transform = (chunk, encoding, done) -> info "Filtering JSON" lines = chunk.toString().split("\n") for line in lines do (line) -> if isJson(line) jsonFilter.emit 'json', line else jsonFilter.push(line) done() # If the message is JSON, treat it as if it were collected data jsonFilter.on 'json', (line) => info "Remembering #{line}" @collectedData = JSON.parse line @updateDb() return jsonFilter robot.on 'telnet:ingress', (msg) -> info 'Ingress message for telnet ' + JSON.stringify msg Session.findOrCreate msg, (dst, txt) -> info 'Egress message for telnet ' + txt robot.emit "telnet:egress:telnet", txt robot.on 'slack:ingress', (msg) -> Session.findOrCreate msg, (dst, txt) -> robot.emit "slack:egress", dst, txt robot.hear /(.*)/i, (hubotMsg) -> dst = hubotMsg.message.room.toLowerCase() src = hubotMsg.message.user.name.toLowerCase() msg = dst: dst src: src txt: hubotMsg.message.text Session.findOrCreate msg, (src, txt) -> user = robot.brain.userForId dst, name: src robot.send user, txt robot.on 'livechat:egress', (sessionKey, text) -> console.log "Received #{text} for #{sessionKey}"
[ { "context": " team = { _id: uuid, name: 'Tukeq Team', authorId: userId, members: [userId1, userId2, ... ], createdAt: Da", "end": 58, "score": 0.9792311191558838, "start": 52, "tag": "USERNAME", "value": "userId" }, { "context": "n 'profiles'\n\n# project = {\n# _id: uuid, name: '...
collections/models.coffee
tyrchen/teamspark
21
# team = { _id: uuid, name: 'Tukeq Team', authorId: userId, members: [userId1, userId2, ... ], createdAt: Date(), abbr: 'tkq', nextIssueId: 0} @Teams = new Meteor.Collection 'teams' # profile = { # _id: uuid, userId: userId, online: true/false, teamId: teamId, # lastActive: new Date(), totalSeconds: integer # totalSubmitted: 0, totalUnfinished: 0, totalFinished: 0 # } @Profiles = new Meteor.Collection 'profiles' # project = { # _id: uuid, name: 'cayman', description: 'cayman is a project', authorId: null, # parent: null, teamId: teamId, createdAt: Date() # unfinished: 0, finished: 0, verified: 0 # } @Projects = new Meteor.Collection 'projects' # spark = { # _id: uuid, type: 'idea', authorId: userId, auditTrails: [], # owners: [userId, ...], finishers: [userId, ...], verified: false, progress: 10, # title: 'blabla', content: 'blabla', priority: 1, supporters: [userId1, userId2, ...], # finished: false, projects: [projectId, ...], deadline: Date(), createdAt: Date(), # updatedAt: Date(), finishedAt: Date(), positionedAt: Date(), teamId: teamId, points: 16, totalPoints: 64 # tags: [], issueId: 'tkq1' # } @Sparks = new Meteor.Collection 'sparks' # auditTrail = { _id: uuid, userId: userId, content: 'bla bla', teamId: teamId, projectId: projectId, sparkId: sparkId, createdAt: Date()} @AuditTrails = new Meteor.Collection 'auditTrails' # notification = { # _id: uuid, recipientId: userId, level: 1-5|debug|info|warning|important|urgent # type: 1-5 | user | spark | project | team | site # title: 'bla', content: 'html bla', url: 'url', createdAt: new Date(), readAt: new Date(), visitedAt: new Date() } @Notifications = new Meteor.Collection 'notifications' # dayStat = { # _id: uuid, date: new Date(), teamId: teamId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as created} # } @DayStats = new Meteor.Collection 'dayStats' # weekStat = { # _id: uuid, date: new Date(), teamId: teamId, projectId: projectId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as create } # burned: [79, 56, 40, 32, 24, 12, 3] # } @WeekStats = new Meteor.Collection 'weekStats' # tag = { _id: uuid, name: '剪辑器', teamId: teamId, projectId: projectId, sparks: 0, createdAt: new Date()} @Tags = new Meteor.Collection 'tags'
95418
# team = { _id: uuid, name: 'Tukeq Team', authorId: userId, members: [userId1, userId2, ... ], createdAt: Date(), abbr: 'tkq', nextIssueId: 0} @Teams = new Meteor.Collection 'teams' # profile = { # _id: uuid, userId: userId, online: true/false, teamId: teamId, # lastActive: new Date(), totalSeconds: integer # totalSubmitted: 0, totalUnfinished: 0, totalFinished: 0 # } @Profiles = new Meteor.Collection 'profiles' # project = { # _id: uuid, name: '<NAME>', description: '<NAME> is a project', authorId: null, # parent: null, teamId: teamId, createdAt: Date() # unfinished: 0, finished: 0, verified: 0 # } @Projects = new Meteor.Collection 'projects' # spark = { # _id: uuid, type: 'idea', authorId: userId, auditTrails: [], # owners: [userId, ...], finishers: [userId, ...], verified: false, progress: 10, # title: 'blabla', content: 'blabla', priority: 1, supporters: [userId1, userId2, ...], # finished: false, projects: [projectId, ...], deadline: Date(), createdAt: Date(), # updatedAt: Date(), finishedAt: Date(), positionedAt: Date(), teamId: teamId, points: 16, totalPoints: 64 # tags: [], issueId: 'tkq1' # } @Sparks = new Meteor.Collection 'sparks' # auditTrail = { _id: uuid, userId: userId, content: 'bla bla', teamId: teamId, projectId: projectId, sparkId: sparkId, createdAt: Date()} @AuditTrails = new Meteor.Collection 'auditTrails' # notification = { # _id: uuid, recipientId: userId, level: 1-5|debug|info|warning|important|urgent # type: 1-5 | user | spark | project | team | site # title: 'bla', content: 'html bla', url: 'url', createdAt: new Date(), readAt: new Date(), visitedAt: new Date() } @Notifications = new Meteor.Collection 'notifications' # dayStat = { # _id: uuid, date: new Date(), teamId: teamId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as created} # } @DayStats = new Meteor.Collection 'dayStats' # weekStat = { # _id: uuid, date: new Date(), teamId: teamId, projectId: projectId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as create } # burned: [79, 56, 40, 32, 24, 12, 3] # } @WeekStats = new Meteor.Collection 'weekStats' # tag = { _id: uuid, name: '剪辑器', teamId: teamId, projectId: projectId, sparks: 0, createdAt: new Date()} @Tags = new Meteor.Collection 'tags'
true
# team = { _id: uuid, name: 'Tukeq Team', authorId: userId, members: [userId1, userId2, ... ], createdAt: Date(), abbr: 'tkq', nextIssueId: 0} @Teams = new Meteor.Collection 'teams' # profile = { # _id: uuid, userId: userId, online: true/false, teamId: teamId, # lastActive: new Date(), totalSeconds: integer # totalSubmitted: 0, totalUnfinished: 0, totalFinished: 0 # } @Profiles = new Meteor.Collection 'profiles' # project = { # _id: uuid, name: 'PI:NAME:<NAME>END_PI', description: 'PI:NAME:<NAME>END_PI is a project', authorId: null, # parent: null, teamId: teamId, createdAt: Date() # unfinished: 0, finished: 0, verified: 0 # } @Projects = new Meteor.Collection 'projects' # spark = { # _id: uuid, type: 'idea', authorId: userId, auditTrails: [], # owners: [userId, ...], finishers: [userId, ...], verified: false, progress: 10, # title: 'blabla', content: 'blabla', priority: 1, supporters: [userId1, userId2, ...], # finished: false, projects: [projectId, ...], deadline: Date(), createdAt: Date(), # updatedAt: Date(), finishedAt: Date(), positionedAt: Date(), teamId: teamId, points: 16, totalPoints: 64 # tags: [], issueId: 'tkq1' # } @Sparks = new Meteor.Collection 'sparks' # auditTrail = { _id: uuid, userId: userId, content: 'bla bla', teamId: teamId, projectId: projectId, sparkId: sparkId, createdAt: Date()} @AuditTrails = new Meteor.Collection 'auditTrails' # notification = { # _id: uuid, recipientId: userId, level: 1-5|debug|info|warning|important|urgent # type: 1-5 | user | spark | project | team | site # title: 'bla', content: 'html bla', url: 'url', createdAt: new Date(), readAt: new Date(), visitedAt: new Date() } @Notifications = new Meteor.Collection 'notifications' # dayStat = { # _id: uuid, date: new Date(), teamId: teamId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as created} # } @DayStats = new Meteor.Collection 'dayStats' # weekStat = { # _id: uuid, date: new Date(), teamId: teamId, projectId: projectId, # positioned: { total: 1], userId2: [0, 0,0,0,0,0], ... } # index 0 is total[15, 1,2,3,4,5], userId1: [3, 1, 0, 0, 1, # finished: { the same as create } # burned: [79, 56, 40, 32, 24, 12, 3] # } @WeekStats = new Meteor.Collection 'weekStats' # tag = { _id: uuid, name: '剪辑器', teamId: teamId, projectId: projectId, sparks: 0, createdAt: new Date()} @Tags = new Meteor.Collection 'tags'
[ { "context": "uide/jentiks-duiker-1.jpg\"]\n credit: \"Credit: Brent Huffman - Ultimate Ungulate Images.\"\n },\n\n {\n ", "end": 8179, "score": 0.9998499155044556, "start": 8166, "tag": "NAME", "value": "Brent Huffman" }, { "context": "/guide/zebra-duiker-1.jpg\"]\n ...
app/lib/guide.coffee
zooniverse/chimpandsee
2
guideDetails = { animals: [{ header: 'bird' subHeader: '<em>Aves</em> class' description: ''' <p>All birds can be classified using this option. Birds have wings, feathers, and beaks; most are capable of flight. A wide variety of birds can be found throughout Africa. Examples of birds seen on Chimp & See include guineafowl, ibis, hornbills, and rails. Usually seen during the day or at dawn/dusk.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':bat'] exampleImages: ["./assets/guide/bird-1.jpg", "./assets/guide/bird-2.jpg", "./assets/guide/bird-3.jpg"] }, { header: 'cattle' subHeader: '<em>Bos taurus</em>' description: ''' <p>Domestic cattle (cows, bulls, and steers) can sometimes be seen in these videos. Cattle are large ungulates typically raised as livestock. Often horned, they can vary in color, but are most often brown, black, tan, and/or white. Branding may be visible on side/flank. Usually seen during the day.</p> ''' confusions: ['forest buffalo'] exampleImages: ["./assets/guide/cattle-1.jpg"] }, { header: 'chimpanzee' subHeader: '<em>Pan</em> genus' description: ''' <p>This large primate, a close relative of humans, has no tail and is usually seen on the ground. The hair is most often black, though it can appear grey or yellow-grey, especially on the lower back. The face, ears, palms, and soles are hairless and skin color varies from peachy-pink to black. They most often travel by knuckle-walking on all fours, and are occasionally seen in trees. Males are slightly larger than females; infants have a white spot on rear. Almost always seen during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000002/discussions/DCP0000bwy" target="_blank">Youth or adult?</a></p> ''' confusions: ['gorilla', 'other (primate)', 'human'] exampleImages: ["./assets/guide/chimp-1.jpg", "./assets/guide/chimp-2.jpg", "./assets/guide/chimp-3.jpg"] }, { header: 'dark duiker' subHeader: '<em>Cephalophus</em> genus' description: ''' <p>Use this option to mark any duikers that are dark grey, black, or dark brown in color. Dark duikers include the yellow-backed duiker, a large duiker notable for a bright yellowish stripe on the back of a brown coat with a partially yellow muzzle, and the black duiker, which is medium-sized, solid black on the body, fading into red on the head, and with a white tail tip. Like other duikers, they have arched backs, stocky bodies and slender legs. Yellow-backed duikers are more often seen at night, while black duikers are seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate', 'small antelope'] exampleImages: ["./assets/guide/dark-duiker-1.jpg", "./assets/guide/dark-duiker-2.jpg", "./assets/guide/dark-duiker-3.jpg"] }, { header: 'elephant' subHeader: '<em>Loxodonta</em> genus' description: '<p>This massive, grey, thick-skinned animal is famous for its very large ears, long trunk, and ivory tusks. When not fully in frame, it can still be identified by its powerful, vertically positioned legs and its leathery, wrinkled skin. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/elephant-1.jpg", "./assets/guide/elephant-2.jpg", "./assets/guide/elephant-3.jpg"] }, { header: 'forest buffalo' subHeader: '<em>Syncerus caffer nanus</em>' description: ''' <p>Smaller (250-320 kg) subspecies of the African buffalo. Reddish-brown hide darkens to black around the face and lower legs, with a black dorsal stripe. Horns curl straight backwards in a C shape, with large, sometimes tufted ears. Solid, robust build with relatively short and thickset legs; typically carries head low. More often seen at night, but sometimes active during the day.</p> ''' confusions: ['cattle'] exampleImages: ["./assets/guide/forest-buffalo-1.jpg", "./assets/guide/forest-buffalo-2.jpg", "./assets/guide/forest-buffalo-3.jpg"] }, { header: 'giant forest hog' subHeader: '<em>Hylochoerus meinertzhageni</em>' description: ''' <p>The largest species of wild pig. Most identifiable by its size, coat of very long black hairs (thinner in older hogs), and upward-curved tusks that are proportionally smaller than a warthog’s. Skin color is dark brown. Males have large protruding swellings under each eye. Almost always seen during the day or at dawn/dusk.</p> ''' confusions: ['red river hog', 'warthog'] exampleImages: ["./assets/guide/giant-forest-hog-1.jpg", "./assets/guide/giant-forest-hog-2.jpg"] }, { header: 'gorilla' subHeader: '<em>Gorilla genus</em>' description: ''' <p>Like chimpanzees, gorillas are apes, but much bigger and more powerfully built. Gorillas also have black skin and faces throughout their lives, while chimpanzees are born with pink skin. Gorillas have black/brown coats, extremely muscular arms, and large heads. Males are larger, have silver-colored backs, and large domed crests on top of their heads. Almost always seen during the day. Gorillas are not found at any sites in Region A (West Africa).</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> ''' confusions: ['chimpanzee'] exampleImages: ["./assets/guide/gorilla-1.jpg", "./assets/guide/gorilla-2.jpg", "./assets/guide/gorilla-3.jpg"] }, { header: 'hippopotamus' subHeader: '<em>Hippopotamus amphibius</em>' description: ''' <p>Large and round with short legs and smooth, shiny skin that appears dark grey to pink. Small ears and a massive, wide mouth. Short, thick tail is trimmed with black bristles. Mostly seen at night.</p> ''' exampleImages: ["./assets/guide/hippos-1.jpg", "./assets/guide/hippos-2.jpg", "./assets/guide/hippos-3.jpg"] }, { header: 'human' subHeader: '<em>Homo sapiens</em>' description: '<p>Human beings may occasionally be seen in the videos: researchers, local residents, or even poachers. Mark any humans with this tag. When the camera is being methodically adjusted by the field team, but they are not in view, you can mark human too.</p>' exampleImages: ["./assets/guide/humans-1.jpg", "./assets/guide/humans-2.jpg", "./assets/guide/humans-3.jpg"] }, { header: 'hyena' subHeader: '<em>Hyaenidae</em> family' description: ''' <p>Looks dog-like. Broad head, with large pointed ears; body slopes dramatically from shoulder to hip. Two species in study range: spotted and striped. Spotted hyenas have speckled gray-red coats. Striped hyenas are slightly smaller, with dirty-gray, striped coats.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':viverrid'] exampleImages: ["./assets/guide/hyenas-1.jpg", "./assets/guide/hyenas-2.jpg", "./assets/guide/hyenas-3.jpg"] }, { header: 'Jentink\'s duiker' subHeader: '<em>Cephalophus jentinki</em>' description: ''' <p>Duiker with unique coloration: black head and shoulders, thin white band behind shoulders, and gray rest of body. Longer horns angling straight back from head. One of the largest species of duikers, with an extremely solid body. Almost always seen at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate'] exampleImages: ["./assets/guide/jentiks-duiker-1.jpg"] credit: "Credit: Brent Huffman - Ultimate Ungulate Images." }, { header: 'large ungulate' subHeader: '<em>Ungulata</em> superorder' description: ''' <p>Use this option to mark any large hooved mammal other than those with separate categories; for instance, sitatungas, bongos, okapi, roan antelope, etc. Water chevrotains are medium-sized, but get marked in this category. Some species are more likely to be seen during the day, and others at night.</p> ''' confusions: ['duiker', 'small antelope'] exampleImages: ["./assets/guide/large-ungulate-1.jpg", "./assets/guide/large-ungulate-2.jpg", "./assets/guide/large-ungulate-3.jpg"] }, { header: 'leopard' subHeader: '<em>Panthera pardus</em>' description: '<p>Muscular golden big cat with black rosettes. Spotted face, no black lines, with small, round ears. Long, spotted tail has bright white fur underneath the tip, which is easy to see when they curl their tails upward. Melanistic variant has mostly (or fully) black coat. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/leopard-1.jpg", "./assets/guide/leopard-2.jpg", "./assets/guide/leopard-3.jpg"] }, { header: 'lion' subHeader: '<em>Panthera leo</em>' description: '<p>Massive, muscular cats. They are tawny coloured with paler underparts; cubs show some spots, especially on their bellies and legs. They have a long tail with smooth fur and a dark tuft on its tip. Males have manes that get darker and thicker with age.</p>' exampleImages: ["./assets/guide/lion-1.jpg", "./assets/guide/lion-2.jpg", "./assets/guide/lion-3.jpg"] }, { header: 'other (non-primate)' subHeader: null description: ''' <p>Mark any animal that does not fall into the other categories as "other non-primate." This includes cat-like viverrids like the civet and genet (almost always seen at night), as well as honey badgers (night and day), hyrax (night and day), hares (night), and bats (night). Hyrax can be distinguished from rodents by their lack of a tail. Domestic animals other than cattle (e.g. dogs, goats, sheep) should be marked in this category as well. Please mark “Nothing here” for insects and fires, but feel free to tag them on the talk page!</p> ''' confusions: ['small cat', 'rodent', 'bird'] confusionsDetail: [' (for civets and genets)', ' (for hyrax and hares)', ' (for bats)'] exampleImages: ["./assets/guide/other-1.jpg", "./assets/guide/other-2.jpg", "./assets/guide/other-3.jpg", "./assets/guide/other-4.jpg"] }, { header: 'other (primate)' subHeader: '<em>Cercopithecidae</em> family and <em>Lorisoidea</em> superfamily' description: ''' <p>Non-ape primates are different from apes in several ways. They typically are smaller, with tails, less broad chests, and less upright posture. African monkeys have non-prehensile tails, hind legs longer than forearms, and downward-pointing nostrils. Coloration varies between species. Africa is also home to galagos (sometimes called bushbabies) and pottos, two kinds of small primitive primate. Monkeys are frequently seen in groups and during the day or at dawn/dusk. Galagos and pottos are usually seen alone and at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP00007sb" target="_blank">Monkey Guide</a></p> ''' confusions: ['chimpanzee', 'rodent'] confusionsDetail: [null, ' (for galagos/pottos)'] exampleImages: ["./assets/guide/small-primates-1.jpg", "./assets/guide/small-primates-2.jpg", "./assets/guide/small-primates-3.jpg"] }, { header: 'pangolin' subHeader: '<em>Manis</em> genus' description: '<p>Also called “scaly anteater,” this unique creature’s body is covered from snout to long tail in overlapping earth-toned plates. Multiple species of pangolin are native to Africa, ranging in size from around 2 kg to over 30 kg. Almost always seen at night.</p>' exampleImages: ["./assets/guide/pangolin-1.jpg", "./assets/guide/pangolin-2.jpg", "./assets/guide/pangolin-3.jpg"] }, { header: 'porcupine' subHeader: '<em>Hystricidae</em> family' description: ''' <p>Porcupines are short, rounded creatures covered from head to tail with long quills. Two species of porcupine are found in the study area: the crested porcupine with long quills on the back and sides that are raised into a crest, and the smaller brush-tailed porcupine, which has a small tuft of quills at the end of its thin tail. Both species are almost always seen at night.</p> ''' confusions: ['rodent'] confusionsDetail: [' (although porcupines are rodents, please mark them separately)'] exampleImages: ["./assets/guide/porcupine-1.jpg", "./assets/guide/porcupine-2.jpg", "./assets/guide/porcupine-3.jpg"] }, { header: 'red duiker' subHeader: '<em>Sylvicapra</em> and <em>Cephalophus</em> genuses' description: ''' <p>Use this option to mark small to medium duikers with chestnut-red fur; for example: the bush duiker which is small and reddish-brown, or the Bay duiker, notable for its red body colour and black stripe down its back. Like other duikers, they have arched backs, stocky bodies and slender legs. Some species are seen mainly at night, and others during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope', 'large ungulate'] exampleImages: ["./assets/guide/red-duiker-1.jpg", "./assets/guide/red-duiker-2.jpg", "./assets/guide/red-duiker-3.jpg"] }, { header: 'red river hog' subHeader: '<em>Potamochoerus porcus</em>' description: ''' <p>Pudgy pig-like animal notable for its bright red fur and its curled, pointed, elfin ears with white ear-tufts. The large muzzle is black with two small tusks and white markings around the eyes. Longer fur on flanks and underbelly. Has a line of spiky blonde hair down the spine. Seen both at night and during the day. Bushpigs, close relatives of red river hogs, should also be marked using this classifications. </p> ''' confusions: ['giant forest hog', 'warthog'] exampleImages: ["./assets/guide/red-river-hog-1.jpg", "./assets/guide/red-river-hog-2.jpg", "./assets/guide/red-river-hog-3.jpg"] }, { header: 'reptile' subHeader: '<em>Reptilia</em> class' description: '<p>Reptiles that may be found in Africa include lizards, snakes, turtles, and crocodiles. Reptiles typically have shells or scales, and are often colored in earthtones (though some snakes may have vibrant coloration). Mark all reptiles as "reptile."</p>' exampleImages: ["./assets/guide/reptiles-1.jpg", "./assets/guide/reptiles-2.jpg", "./assets/guide/reptiles-3.jpg"] }, { header: 'rodent' subHeader: '<em>Rodentia</em> order' description: ''' <p>Rodents of Africa include mice, squirrels, gerbils, and rats, but not hares, which should be marked other non-primate. These animals are typically small, with short limbs, thick bodies, and long tails. Rats and mice are almost always seen at night, while squirrels are almost always seen during the day or at dawn/dusk. (Note: please mark porcupines separately.)</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':hyrax or hare'] exampleImages: ["./assets/guide/rodent-1.jpg", "./assets/guide/rodent-2.jpg", "./assets/guide/rodent-3.jpg"] }, { header: 'small antelope' subHeader: '<em>Bovidae</em> family' description: ''' <p>Use this option to mark any small antelope other than a listed type of duiker; for instance: bushbuck, royal antelope, dik-dik, oribi, pygmy antelope, reedbuck, etc.</p> ''' confusions: ['duiker', 'large ungulate'] exampleImages: ["./assets/guide/sm-antelope-1.jpg", "./assets/guide/sm-antelope-2.jpg", "./assets/guide/sm-antelope-3.jpg"] }, { header: 'small grey duiker' subHeader: '<em>Cephalophus monticola</em> and <em>Cephalophus maxwelli</em>' description: ''' <p>Some of the smallest antelopes. Coat ranges from light brown to blue-grey with paler chest and underbelly. Small spiky horns in most males and some females. Stocky body, arched back, large hindquarters and thin legs. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope'] exampleImages: ["./assets/guide/sm-gray-duiker-1.jpg", "./assets/guide/sm-gray-duiker-2.jpg"] }, { header: 'small cat' subHeader: '<em>Felinae</em> subfamily' description: '<p>Several species of small felines can be found in Africa, including the caracal, the serval, the African golden cat, and the African wildcat. Any cat smaller than a leopard or a cheetah can be classified as a "small cat." Please note that viverrids, like civets and genets, are not cats, and should be marked as "other (non-primate)."</p>' exampleImages: ["./assets/guide/small-cat-1.jpg", "./assets/guide/small-cat-2.jpg", "./assets/guide/small-cat-3.jpg"] }, { header: 'warthog' subHeader: '<em>Phacochoerus africanus</em>' description: ''' <p>This pig-like animal has a grey body covered sparsely with darker hairs, and mane of long, wiry hairs along its neck and back. Its tail is thick with a black tassel. It has tusks that curve up around its snout. More often seen during the day, but sometimes seen at night.</p> ''' confusions: ['red river hog', 'giant forest hog'] exampleImages: ["./assets/guide/warthog-1.jpg", "./assets/guide/warthog-2.jpg", "./assets/guide/warthog-3.jpg"] }, { header: 'wild dog' subHeader: '<em>Lycaon pictus</em>' description: '<p>Social pack canine with tall, solid build and mottled coat of blacks, browns, reds, and whites. Muzzle is black and tail is typically white-tipped. Build is similar to domestic dogs and lacks hyenas\' sloped backs.</p>' exampleImages: ["./assets/guide/wild-dog-1.jpg", "./assets/guide/wild-dog-2.jpg", "./assets/guide/wild-dog-3.jpg"] }, { header: 'zebra duiker' subHeader: '<em>Cephalophus zebra</em>' description: ''' <p>Easily identifiable by the unique dark zebra-like stripes that cover its chestnut-colored back. Like other duikers, it has an arched back and stocky body with slender legs. The head has conical horns, the muzzle is black, and the lower jaw and undersides white. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' exampleImages: ["./assets/guide/zebra-duiker-1.jpg"] credit: "Credit: Brent Huffman - Ultimate Ungulate Images." } ], behaviors: [ { header: 'aggression' description: 'Animal is displaying angry and/or threatening behaviour directed towards another animal or towards the camera.' }, { header: 'camera reaction' description: 'Animal is directly reacting to the presence of the video camera. The animal can be staring at the camera while being interested or wary, or poking at the camera. Sometimes you will see an animal look into the camera, walk by it, and then jostle the camera from behind, causing the video to shake.' }, { header: 'carrying object' description: 'Animal (usually a primate or an elephant) is carrying anything like fruit or a stick. Animal may also be carrying fruit, or, in some cases, may be carrying meat from a hunt—if you suspect a chimpanzee is carrying meat, please discuss it in Talk.' }, { header: 'carrying young/clinging' description: 'Animal is carrying a younger animal on its back or front, or a younger animal is clinging to an older animal in some way.' }, { header: 'climbing' description: 'Animal is moving in a mostly vertical direction, usually in a tree or liana' }, { header: 'cross-species interaction' description: 'Animal is doing something (interacting) with another animal of a different species. Interacting means when the actions of one individual is followed by an action in another individual whereby the second appears to be a response to the first one. This does not include two different species just walking by the camera or simply appearing at the same time in the video.' }, { header: 'drinking/feeding' description: 'Animal is drinking or eating food. If the animal or animals, especially chimpanzees, can be seen sharing food with others (often meat, nuts, or large fruits), please make a special note in Talk!' }, { header: 'drumming' description: 'Chimpanzees display a behaviour called "drumming" whereby they run up to a tree and repeatedly hit on it with their hands and/or feet to make a drumming sound. When you see any repeated hitting of a hard surface with hands and/or feet, consider it drumming. Pay very special attention to whether the chimpanzee drums with a stone; if yes, make sure to select the "Tool Use" button as well!' }, { header: 'grooming' description: 'Animal is cleaning itself or another animal. In chimpanzees, this is often seen as one animal scratching or inspecting the fur/hair of another animal and picking things out of the hair (and sometimes even eating these things).' }, { header: 'in a tree' description: 'Animal is perched on a tree, climbing a tree, or is travelling through the trees at any point during the video.' }, { header: 'nursing' description: 'Female animal is giving a teat to its young, which is then suckling to obtain milk.' }, { header: 'on the ground' description: 'Animal is on the ground, either standing or moving.' }, { header: 'playing' description: 'Animal is playing. Play behaviours are often normally expressed behaviours that are done out of context. For example, you may see a chimpanzee performing a threat, hitting, or chasing, but doing so without aggression. In chimpanzees, this is often (but not always) accompanied by a play-face, similar to a kind of smile.' }, { header: 'resting' description: 'Animal is sitting, lying down, sleeping, or otherwise appears relaxed.' }, { header: 'sex/mounting' description: 'Animals are having sexual intercourse or mounting each other. Many primate dominance interactions often include mounting that looks very sexual but is not in fact sex.' }, { header: 'social interaction' description: 'Animal is doing something (interacting) with another animal of the same species. Interacting means that the actions of one individual is followed by an action in another individual, whereby the second appears to be a response to the first one. This does not include two individuals just walking by the camera or simply appearing at the same time in the video.' }, { header: 'tool usage' description: 'Tool use if when an animal uses an external detached object to attain a goal. This is primarily for chimpanzees where you will see them using a tool to accomplish a task. This can be one or a series of stick tools for collecting insects, honey or algae, a wooden or stone hammer to crack nuts, or stone or wooden anvils on which they smash fruit. Seeing a chimpanzee throwing a stone at a tree is also tool use. Keep your eyes peeled for even more types of tool use that might not be on this list!' }, { header: 'traveling' description: 'Animal is walking, running, or otherwise moving and does not stop in front of the camera for long, if at all. Animal could be hunting or fleeing as well. If an animal appears to be hunting, please make a special note in Talk!' }, { header: 'vocalizing' description: 'Animal is making cries or other vocal noises.' } ] } module.exports = guideDetails
199023
guideDetails = { animals: [{ header: 'bird' subHeader: '<em>Aves</em> class' description: ''' <p>All birds can be classified using this option. Birds have wings, feathers, and beaks; most are capable of flight. A wide variety of birds can be found throughout Africa. Examples of birds seen on Chimp & See include guineafowl, ibis, hornbills, and rails. Usually seen during the day or at dawn/dusk.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':bat'] exampleImages: ["./assets/guide/bird-1.jpg", "./assets/guide/bird-2.jpg", "./assets/guide/bird-3.jpg"] }, { header: 'cattle' subHeader: '<em>Bos taurus</em>' description: ''' <p>Domestic cattle (cows, bulls, and steers) can sometimes be seen in these videos. Cattle are large ungulates typically raised as livestock. Often horned, they can vary in color, but are most often brown, black, tan, and/or white. Branding may be visible on side/flank. Usually seen during the day.</p> ''' confusions: ['forest buffalo'] exampleImages: ["./assets/guide/cattle-1.jpg"] }, { header: 'chimpanzee' subHeader: '<em>Pan</em> genus' description: ''' <p>This large primate, a close relative of humans, has no tail and is usually seen on the ground. The hair is most often black, though it can appear grey or yellow-grey, especially on the lower back. The face, ears, palms, and soles are hairless and skin color varies from peachy-pink to black. They most often travel by knuckle-walking on all fours, and are occasionally seen in trees. Males are slightly larger than females; infants have a white spot on rear. Almost always seen during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000002/discussions/DCP0000bwy" target="_blank">Youth or adult?</a></p> ''' confusions: ['gorilla', 'other (primate)', 'human'] exampleImages: ["./assets/guide/chimp-1.jpg", "./assets/guide/chimp-2.jpg", "./assets/guide/chimp-3.jpg"] }, { header: 'dark duiker' subHeader: '<em>Cephalophus</em> genus' description: ''' <p>Use this option to mark any duikers that are dark grey, black, or dark brown in color. Dark duikers include the yellow-backed duiker, a large duiker notable for a bright yellowish stripe on the back of a brown coat with a partially yellow muzzle, and the black duiker, which is medium-sized, solid black on the body, fading into red on the head, and with a white tail tip. Like other duikers, they have arched backs, stocky bodies and slender legs. Yellow-backed duikers are more often seen at night, while black duikers are seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate', 'small antelope'] exampleImages: ["./assets/guide/dark-duiker-1.jpg", "./assets/guide/dark-duiker-2.jpg", "./assets/guide/dark-duiker-3.jpg"] }, { header: 'elephant' subHeader: '<em>Loxodonta</em> genus' description: '<p>This massive, grey, thick-skinned animal is famous for its very large ears, long trunk, and ivory tusks. When not fully in frame, it can still be identified by its powerful, vertically positioned legs and its leathery, wrinkled skin. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/elephant-1.jpg", "./assets/guide/elephant-2.jpg", "./assets/guide/elephant-3.jpg"] }, { header: 'forest buffalo' subHeader: '<em>Syncerus caffer nanus</em>' description: ''' <p>Smaller (250-320 kg) subspecies of the African buffalo. Reddish-brown hide darkens to black around the face and lower legs, with a black dorsal stripe. Horns curl straight backwards in a C shape, with large, sometimes tufted ears. Solid, robust build with relatively short and thickset legs; typically carries head low. More often seen at night, but sometimes active during the day.</p> ''' confusions: ['cattle'] exampleImages: ["./assets/guide/forest-buffalo-1.jpg", "./assets/guide/forest-buffalo-2.jpg", "./assets/guide/forest-buffalo-3.jpg"] }, { header: 'giant forest hog' subHeader: '<em>Hylochoerus meinertzhageni</em>' description: ''' <p>The largest species of wild pig. Most identifiable by its size, coat of very long black hairs (thinner in older hogs), and upward-curved tusks that are proportionally smaller than a warthog’s. Skin color is dark brown. Males have large protruding swellings under each eye. Almost always seen during the day or at dawn/dusk.</p> ''' confusions: ['red river hog', 'warthog'] exampleImages: ["./assets/guide/giant-forest-hog-1.jpg", "./assets/guide/giant-forest-hog-2.jpg"] }, { header: 'gorilla' subHeader: '<em>Gorilla genus</em>' description: ''' <p>Like chimpanzees, gorillas are apes, but much bigger and more powerfully built. Gorillas also have black skin and faces throughout their lives, while chimpanzees are born with pink skin. Gorillas have black/brown coats, extremely muscular arms, and large heads. Males are larger, have silver-colored backs, and large domed crests on top of their heads. Almost always seen during the day. Gorillas are not found at any sites in Region A (West Africa).</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> ''' confusions: ['chimpanzee'] exampleImages: ["./assets/guide/gorilla-1.jpg", "./assets/guide/gorilla-2.jpg", "./assets/guide/gorilla-3.jpg"] }, { header: 'hippopotamus' subHeader: '<em>Hippopotamus amphibius</em>' description: ''' <p>Large and round with short legs and smooth, shiny skin that appears dark grey to pink. Small ears and a massive, wide mouth. Short, thick tail is trimmed with black bristles. Mostly seen at night.</p> ''' exampleImages: ["./assets/guide/hippos-1.jpg", "./assets/guide/hippos-2.jpg", "./assets/guide/hippos-3.jpg"] }, { header: 'human' subHeader: '<em>Homo sapiens</em>' description: '<p>Human beings may occasionally be seen in the videos: researchers, local residents, or even poachers. Mark any humans with this tag. When the camera is being methodically adjusted by the field team, but they are not in view, you can mark human too.</p>' exampleImages: ["./assets/guide/humans-1.jpg", "./assets/guide/humans-2.jpg", "./assets/guide/humans-3.jpg"] }, { header: 'hyena' subHeader: '<em>Hyaenidae</em> family' description: ''' <p>Looks dog-like. Broad head, with large pointed ears; body slopes dramatically from shoulder to hip. Two species in study range: spotted and striped. Spotted hyenas have speckled gray-red coats. Striped hyenas are slightly smaller, with dirty-gray, striped coats.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':viverrid'] exampleImages: ["./assets/guide/hyenas-1.jpg", "./assets/guide/hyenas-2.jpg", "./assets/guide/hyenas-3.jpg"] }, { header: 'Jentink\'s duiker' subHeader: '<em>Cephalophus jentinki</em>' description: ''' <p>Duiker with unique coloration: black head and shoulders, thin white band behind shoulders, and gray rest of body. Longer horns angling straight back from head. One of the largest species of duikers, with an extremely solid body. Almost always seen at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate'] exampleImages: ["./assets/guide/jentiks-duiker-1.jpg"] credit: "Credit: <NAME> - Ultimate Ungulate Images." }, { header: 'large ungulate' subHeader: '<em>Ungulata</em> superorder' description: ''' <p>Use this option to mark any large hooved mammal other than those with separate categories; for instance, sitatungas, bongos, okapi, roan antelope, etc. Water chevrotains are medium-sized, but get marked in this category. Some species are more likely to be seen during the day, and others at night.</p> ''' confusions: ['duiker', 'small antelope'] exampleImages: ["./assets/guide/large-ungulate-1.jpg", "./assets/guide/large-ungulate-2.jpg", "./assets/guide/large-ungulate-3.jpg"] }, { header: 'leopard' subHeader: '<em>Panthera pardus</em>' description: '<p>Muscular golden big cat with black rosettes. Spotted face, no black lines, with small, round ears. Long, spotted tail has bright white fur underneath the tip, which is easy to see when they curl their tails upward. Melanistic variant has mostly (or fully) black coat. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/leopard-1.jpg", "./assets/guide/leopard-2.jpg", "./assets/guide/leopard-3.jpg"] }, { header: 'lion' subHeader: '<em>Panthera leo</em>' description: '<p>Massive, muscular cats. They are tawny coloured with paler underparts; cubs show some spots, especially on their bellies and legs. They have a long tail with smooth fur and a dark tuft on its tip. Males have manes that get darker and thicker with age.</p>' exampleImages: ["./assets/guide/lion-1.jpg", "./assets/guide/lion-2.jpg", "./assets/guide/lion-3.jpg"] }, { header: 'other (non-primate)' subHeader: null description: ''' <p>Mark any animal that does not fall into the other categories as "other non-primate." This includes cat-like viverrids like the civet and genet (almost always seen at night), as well as honey badgers (night and day), hyrax (night and day), hares (night), and bats (night). Hyrax can be distinguished from rodents by their lack of a tail. Domestic animals other than cattle (e.g. dogs, goats, sheep) should be marked in this category as well. Please mark “Nothing here” for insects and fires, but feel free to tag them on the talk page!</p> ''' confusions: ['small cat', 'rodent', 'bird'] confusionsDetail: [' (for civets and genets)', ' (for hyrax and hares)', ' (for bats)'] exampleImages: ["./assets/guide/other-1.jpg", "./assets/guide/other-2.jpg", "./assets/guide/other-3.jpg", "./assets/guide/other-4.jpg"] }, { header: 'other (primate)' subHeader: '<em>Cercopithecidae</em> family and <em>Lorisoidea</em> superfamily' description: ''' <p>Non-ape primates are different from apes in several ways. They typically are smaller, with tails, less broad chests, and less upright posture. African monkeys have non-prehensile tails, hind legs longer than forearms, and downward-pointing nostrils. Coloration varies between species. Africa is also home to galagos (sometimes called bushbabies) and pottos, two kinds of small primitive primate. Monkeys are frequently seen in groups and during the day or at dawn/dusk. Galagos and pottos are usually seen alone and at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP00007sb" target="_blank">Monkey Guide</a></p> ''' confusions: ['chimpanzee', 'rodent'] confusionsDetail: [null, ' (for galagos/pottos)'] exampleImages: ["./assets/guide/small-primates-1.jpg", "./assets/guide/small-primates-2.jpg", "./assets/guide/small-primates-3.jpg"] }, { header: 'pangolin' subHeader: '<em>Manis</em> genus' description: '<p>Also called “scaly anteater,” this unique creature’s body is covered from snout to long tail in overlapping earth-toned plates. Multiple species of pangolin are native to Africa, ranging in size from around 2 kg to over 30 kg. Almost always seen at night.</p>' exampleImages: ["./assets/guide/pangolin-1.jpg", "./assets/guide/pangolin-2.jpg", "./assets/guide/pangolin-3.jpg"] }, { header: 'porcupine' subHeader: '<em>Hystricidae</em> family' description: ''' <p>Porcupines are short, rounded creatures covered from head to tail with long quills. Two species of porcupine are found in the study area: the crested porcupine with long quills on the back and sides that are raised into a crest, and the smaller brush-tailed porcupine, which has a small tuft of quills at the end of its thin tail. Both species are almost always seen at night.</p> ''' confusions: ['rodent'] confusionsDetail: [' (although porcupines are rodents, please mark them separately)'] exampleImages: ["./assets/guide/porcupine-1.jpg", "./assets/guide/porcupine-2.jpg", "./assets/guide/porcupine-3.jpg"] }, { header: 'red duiker' subHeader: '<em>Sylvicapra</em> and <em>Cephalophus</em> genuses' description: ''' <p>Use this option to mark small to medium duikers with chestnut-red fur; for example: the bush duiker which is small and reddish-brown, or the Bay duiker, notable for its red body colour and black stripe down its back. Like other duikers, they have arched backs, stocky bodies and slender legs. Some species are seen mainly at night, and others during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope', 'large ungulate'] exampleImages: ["./assets/guide/red-duiker-1.jpg", "./assets/guide/red-duiker-2.jpg", "./assets/guide/red-duiker-3.jpg"] }, { header: 'red river hog' subHeader: '<em>Potamochoerus porcus</em>' description: ''' <p>Pudgy pig-like animal notable for its bright red fur and its curled, pointed, elfin ears with white ear-tufts. The large muzzle is black with two small tusks and white markings around the eyes. Longer fur on flanks and underbelly. Has a line of spiky blonde hair down the spine. Seen both at night and during the day. Bushpigs, close relatives of red river hogs, should also be marked using this classifications. </p> ''' confusions: ['giant forest hog', 'warthog'] exampleImages: ["./assets/guide/red-river-hog-1.jpg", "./assets/guide/red-river-hog-2.jpg", "./assets/guide/red-river-hog-3.jpg"] }, { header: 'reptile' subHeader: '<em>Reptilia</em> class' description: '<p>Reptiles that may be found in Africa include lizards, snakes, turtles, and crocodiles. Reptiles typically have shells or scales, and are often colored in earthtones (though some snakes may have vibrant coloration). Mark all reptiles as "reptile."</p>' exampleImages: ["./assets/guide/reptiles-1.jpg", "./assets/guide/reptiles-2.jpg", "./assets/guide/reptiles-3.jpg"] }, { header: 'rodent' subHeader: '<em>Rodentia</em> order' description: ''' <p>Rodents of Africa include mice, squirrels, gerbils, and rats, but not hares, which should be marked other non-primate. These animals are typically small, with short limbs, thick bodies, and long tails. Rats and mice are almost always seen at night, while squirrels are almost always seen during the day or at dawn/dusk. (Note: please mark porcupines separately.)</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':hyrax or hare'] exampleImages: ["./assets/guide/rodent-1.jpg", "./assets/guide/rodent-2.jpg", "./assets/guide/rodent-3.jpg"] }, { header: 'small antelope' subHeader: '<em>Bovidae</em> family' description: ''' <p>Use this option to mark any small antelope other than a listed type of duiker; for instance: bushbuck, royal antelope, dik-dik, oribi, pygmy antelope, reedbuck, etc.</p> ''' confusions: ['duiker', 'large ungulate'] exampleImages: ["./assets/guide/sm-antelope-1.jpg", "./assets/guide/sm-antelope-2.jpg", "./assets/guide/sm-antelope-3.jpg"] }, { header: 'small grey duiker' subHeader: '<em>Cephalophus monticola</em> and <em>Cephalophus maxwelli</em>' description: ''' <p>Some of the smallest antelopes. Coat ranges from light brown to blue-grey with paler chest and underbelly. Small spiky horns in most males and some females. Stocky body, arched back, large hindquarters and thin legs. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope'] exampleImages: ["./assets/guide/sm-gray-duiker-1.jpg", "./assets/guide/sm-gray-duiker-2.jpg"] }, { header: 'small cat' subHeader: '<em>Felinae</em> subfamily' description: '<p>Several species of small felines can be found in Africa, including the caracal, the serval, the African golden cat, and the African wildcat. Any cat smaller than a leopard or a cheetah can be classified as a "small cat." Please note that viverrids, like civets and genets, are not cats, and should be marked as "other (non-primate)."</p>' exampleImages: ["./assets/guide/small-cat-1.jpg", "./assets/guide/small-cat-2.jpg", "./assets/guide/small-cat-3.jpg"] }, { header: 'warthog' subHeader: '<em>Phacochoerus africanus</em>' description: ''' <p>This pig-like animal has a grey body covered sparsely with darker hairs, and mane of long, wiry hairs along its neck and back. Its tail is thick with a black tassel. It has tusks that curve up around its snout. More often seen during the day, but sometimes seen at night.</p> ''' confusions: ['red river hog', 'giant forest hog'] exampleImages: ["./assets/guide/warthog-1.jpg", "./assets/guide/warthog-2.jpg", "./assets/guide/warthog-3.jpg"] }, { header: 'wild dog' subHeader: '<em>Lycaon pictus</em>' description: '<p>Social pack canine with tall, solid build and mottled coat of blacks, browns, reds, and whites. Muzzle is black and tail is typically white-tipped. Build is similar to domestic dogs and lacks hyenas\' sloped backs.</p>' exampleImages: ["./assets/guide/wild-dog-1.jpg", "./assets/guide/wild-dog-2.jpg", "./assets/guide/wild-dog-3.jpg"] }, { header: 'zebra duiker' subHeader: '<em>Cephalophus zebra</em>' description: ''' <p>Easily identifiable by the unique dark zebra-like stripes that cover its chestnut-colored back. Like other duikers, it has an arched back and stocky body with slender legs. The head has conical horns, the muzzle is black, and the lower jaw and undersides white. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' exampleImages: ["./assets/guide/zebra-duiker-1.jpg"] credit: "Credit: <NAME> - Ultimate Ungulate Images." } ], behaviors: [ { header: 'aggression' description: 'Animal is displaying angry and/or threatening behaviour directed towards another animal or towards the camera.' }, { header: 'camera reaction' description: 'Animal is directly reacting to the presence of the video camera. The animal can be staring at the camera while being interested or wary, or poking at the camera. Sometimes you will see an animal look into the camera, walk by it, and then jostle the camera from behind, causing the video to shake.' }, { header: 'carrying object' description: 'Animal (usually a primate or an elephant) is carrying anything like fruit or a stick. Animal may also be carrying fruit, or, in some cases, may be carrying meat from a hunt—if you suspect a chimpanzee is carrying meat, please discuss it in Talk.' }, { header: 'carrying young/clinging' description: 'Animal is carrying a younger animal on its back or front, or a younger animal is clinging to an older animal in some way.' }, { header: 'climbing' description: 'Animal is moving in a mostly vertical direction, usually in a tree or liana' }, { header: 'cross-species interaction' description: 'Animal is doing something (interacting) with another animal of a different species. Interacting means when the actions of one individual is followed by an action in another individual whereby the second appears to be a response to the first one. This does not include two different species just walking by the camera or simply appearing at the same time in the video.' }, { header: 'drinking/feeding' description: 'Animal is drinking or eating food. If the animal or animals, especially chimpanzees, can be seen sharing food with others (often meat, nuts, or large fruits), please make a special note in Talk!' }, { header: 'drumming' description: 'Chimpanzees display a behaviour called "drumming" whereby they run up to a tree and repeatedly hit on it with their hands and/or feet to make a drumming sound. When you see any repeated hitting of a hard surface with hands and/or feet, consider it drumming. Pay very special attention to whether the chimpanzee drums with a stone; if yes, make sure to select the "Tool Use" button as well!' }, { header: 'grooming' description: 'Animal is cleaning itself or another animal. In chimpanzees, this is often seen as one animal scratching or inspecting the fur/hair of another animal and picking things out of the hair (and sometimes even eating these things).' }, { header: 'in a tree' description: 'Animal is perched on a tree, climbing a tree, or is travelling through the trees at any point during the video.' }, { header: 'nursing' description: 'Female animal is giving a teat to its young, which is then suckling to obtain milk.' }, { header: 'on the ground' description: 'Animal is on the ground, either standing or moving.' }, { header: 'playing' description: 'Animal is playing. Play behaviours are often normally expressed behaviours that are done out of context. For example, you may see a chimpanzee performing a threat, hitting, or chasing, but doing so without aggression. In chimpanzees, this is often (but not always) accompanied by a play-face, similar to a kind of smile.' }, { header: 'resting' description: 'Animal is sitting, lying down, sleeping, or otherwise appears relaxed.' }, { header: 'sex/mounting' description: 'Animals are having sexual intercourse or mounting each other. Many primate dominance interactions often include mounting that looks very sexual but is not in fact sex.' }, { header: 'social interaction' description: 'Animal is doing something (interacting) with another animal of the same species. Interacting means that the actions of one individual is followed by an action in another individual, whereby the second appears to be a response to the first one. This does not include two individuals just walking by the camera or simply appearing at the same time in the video.' }, { header: 'tool usage' description: 'Tool use if when an animal uses an external detached object to attain a goal. This is primarily for chimpanzees where you will see them using a tool to accomplish a task. This can be one or a series of stick tools for collecting insects, honey or algae, a wooden or stone hammer to crack nuts, or stone or wooden anvils on which they smash fruit. Seeing a chimpanzee throwing a stone at a tree is also tool use. Keep your eyes peeled for even more types of tool use that might not be on this list!' }, { header: 'traveling' description: 'Animal is walking, running, or otherwise moving and does not stop in front of the camera for long, if at all. Animal could be hunting or fleeing as well. If an animal appears to be hunting, please make a special note in Talk!' }, { header: 'vocalizing' description: 'Animal is making cries or other vocal noises.' } ] } module.exports = guideDetails
true
guideDetails = { animals: [{ header: 'bird' subHeader: '<em>Aves</em> class' description: ''' <p>All birds can be classified using this option. Birds have wings, feathers, and beaks; most are capable of flight. A wide variety of birds can be found throughout Africa. Examples of birds seen on Chimp & See include guineafowl, ibis, hornbills, and rails. Usually seen during the day or at dawn/dusk.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':bat'] exampleImages: ["./assets/guide/bird-1.jpg", "./assets/guide/bird-2.jpg", "./assets/guide/bird-3.jpg"] }, { header: 'cattle' subHeader: '<em>Bos taurus</em>' description: ''' <p>Domestic cattle (cows, bulls, and steers) can sometimes be seen in these videos. Cattle are large ungulates typically raised as livestock. Often horned, they can vary in color, but are most often brown, black, tan, and/or white. Branding may be visible on side/flank. Usually seen during the day.</p> ''' confusions: ['forest buffalo'] exampleImages: ["./assets/guide/cattle-1.jpg"] }, { header: 'chimpanzee' subHeader: '<em>Pan</em> genus' description: ''' <p>This large primate, a close relative of humans, has no tail and is usually seen on the ground. The hair is most often black, though it can appear grey or yellow-grey, especially on the lower back. The face, ears, palms, and soles are hairless and skin color varies from peachy-pink to black. They most often travel by knuckle-walking on all fours, and are occasionally seen in trees. Males are slightly larger than females; infants have a white spot on rear. Almost always seen during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000002/discussions/DCP0000bwy" target="_blank">Youth or adult?</a></p> ''' confusions: ['gorilla', 'other (primate)', 'human'] exampleImages: ["./assets/guide/chimp-1.jpg", "./assets/guide/chimp-2.jpg", "./assets/guide/chimp-3.jpg"] }, { header: 'dark duiker' subHeader: '<em>Cephalophus</em> genus' description: ''' <p>Use this option to mark any duikers that are dark grey, black, or dark brown in color. Dark duikers include the yellow-backed duiker, a large duiker notable for a bright yellowish stripe on the back of a brown coat with a partially yellow muzzle, and the black duiker, which is medium-sized, solid black on the body, fading into red on the head, and with a white tail tip. Like other duikers, they have arched backs, stocky bodies and slender legs. Yellow-backed duikers are more often seen at night, while black duikers are seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate', 'small antelope'] exampleImages: ["./assets/guide/dark-duiker-1.jpg", "./assets/guide/dark-duiker-2.jpg", "./assets/guide/dark-duiker-3.jpg"] }, { header: 'elephant' subHeader: '<em>Loxodonta</em> genus' description: '<p>This massive, grey, thick-skinned animal is famous for its very large ears, long trunk, and ivory tusks. When not fully in frame, it can still be identified by its powerful, vertically positioned legs and its leathery, wrinkled skin. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/elephant-1.jpg", "./assets/guide/elephant-2.jpg", "./assets/guide/elephant-3.jpg"] }, { header: 'forest buffalo' subHeader: '<em>Syncerus caffer nanus</em>' description: ''' <p>Smaller (250-320 kg) subspecies of the African buffalo. Reddish-brown hide darkens to black around the face and lower legs, with a black dorsal stripe. Horns curl straight backwards in a C shape, with large, sometimes tufted ears. Solid, robust build with relatively short and thickset legs; typically carries head low. More often seen at night, but sometimes active during the day.</p> ''' confusions: ['cattle'] exampleImages: ["./assets/guide/forest-buffalo-1.jpg", "./assets/guide/forest-buffalo-2.jpg", "./assets/guide/forest-buffalo-3.jpg"] }, { header: 'giant forest hog' subHeader: '<em>Hylochoerus meinertzhageni</em>' description: ''' <p>The largest species of wild pig. Most identifiable by its size, coat of very long black hairs (thinner in older hogs), and upward-curved tusks that are proportionally smaller than a warthog’s. Skin color is dark brown. Males have large protruding swellings under each eye. Almost always seen during the day or at dawn/dusk.</p> ''' confusions: ['red river hog', 'warthog'] exampleImages: ["./assets/guide/giant-forest-hog-1.jpg", "./assets/guide/giant-forest-hog-2.jpg"] }, { header: 'gorilla' subHeader: '<em>Gorilla genus</em>' description: ''' <p>Like chimpanzees, gorillas are apes, but much bigger and more powerfully built. Gorillas also have black skin and faces throughout their lives, while chimpanzees are born with pink skin. Gorillas have black/brown coats, extremely muscular arms, and large heads. Males are larger, have silver-colored backs, and large domed crests on top of their heads. Almost always seen during the day. Gorillas are not found at any sites in Region A (West Africa).</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP0000001/discussions/DCP000015b" target="_blank">Chimp or gorilla?</a></p> ''' confusions: ['chimpanzee'] exampleImages: ["./assets/guide/gorilla-1.jpg", "./assets/guide/gorilla-2.jpg", "./assets/guide/gorilla-3.jpg"] }, { header: 'hippopotamus' subHeader: '<em>Hippopotamus amphibius</em>' description: ''' <p>Large and round with short legs and smooth, shiny skin that appears dark grey to pink. Small ears and a massive, wide mouth. Short, thick tail is trimmed with black bristles. Mostly seen at night.</p> ''' exampleImages: ["./assets/guide/hippos-1.jpg", "./assets/guide/hippos-2.jpg", "./assets/guide/hippos-3.jpg"] }, { header: 'human' subHeader: '<em>Homo sapiens</em>' description: '<p>Human beings may occasionally be seen in the videos: researchers, local residents, or even poachers. Mark any humans with this tag. When the camera is being methodically adjusted by the field team, but they are not in view, you can mark human too.</p>' exampleImages: ["./assets/guide/humans-1.jpg", "./assets/guide/humans-2.jpg", "./assets/guide/humans-3.jpg"] }, { header: 'hyena' subHeader: '<em>Hyaenidae</em> family' description: ''' <p>Looks dog-like. Broad head, with large pointed ears; body slopes dramatically from shoulder to hip. Two species in study range: spotted and striped. Spotted hyenas have speckled gray-red coats. Striped hyenas are slightly smaller, with dirty-gray, striped coats.</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':viverrid'] exampleImages: ["./assets/guide/hyenas-1.jpg", "./assets/guide/hyenas-2.jpg", "./assets/guide/hyenas-3.jpg"] }, { header: 'Jentink\'s duiker' subHeader: '<em>Cephalophus jentinki</em>' description: ''' <p>Duiker with unique coloration: black head and shoulders, thin white band behind shoulders, and gray rest of body. Longer horns angling straight back from head. One of the largest species of duikers, with an extremely solid body. Almost always seen at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['large ungulate'] exampleImages: ["./assets/guide/jentiks-duiker-1.jpg"] credit: "Credit: PI:NAME:<NAME>END_PI - Ultimate Ungulate Images." }, { header: 'large ungulate' subHeader: '<em>Ungulata</em> superorder' description: ''' <p>Use this option to mark any large hooved mammal other than those with separate categories; for instance, sitatungas, bongos, okapi, roan antelope, etc. Water chevrotains are medium-sized, but get marked in this category. Some species are more likely to be seen during the day, and others at night.</p> ''' confusions: ['duiker', 'small antelope'] exampleImages: ["./assets/guide/large-ungulate-1.jpg", "./assets/guide/large-ungulate-2.jpg", "./assets/guide/large-ungulate-3.jpg"] }, { header: 'leopard' subHeader: '<em>Panthera pardus</em>' description: '<p>Muscular golden big cat with black rosettes. Spotted face, no black lines, with small, round ears. Long, spotted tail has bright white fur underneath the tip, which is easy to see when they curl their tails upward. Melanistic variant has mostly (or fully) black coat. Seen both at night and during the day.</p>' exampleImages: ["./assets/guide/leopard-1.jpg", "./assets/guide/leopard-2.jpg", "./assets/guide/leopard-3.jpg"] }, { header: 'lion' subHeader: '<em>Panthera leo</em>' description: '<p>Massive, muscular cats. They are tawny coloured with paler underparts; cubs show some spots, especially on their bellies and legs. They have a long tail with smooth fur and a dark tuft on its tip. Males have manes that get darker and thicker with age.</p>' exampleImages: ["./assets/guide/lion-1.jpg", "./assets/guide/lion-2.jpg", "./assets/guide/lion-3.jpg"] }, { header: 'other (non-primate)' subHeader: null description: ''' <p>Mark any animal that does not fall into the other categories as "other non-primate." This includes cat-like viverrids like the civet and genet (almost always seen at night), as well as honey badgers (night and day), hyrax (night and day), hares (night), and bats (night). Hyrax can be distinguished from rodents by their lack of a tail. Domestic animals other than cattle (e.g. dogs, goats, sheep) should be marked in this category as well. Please mark “Nothing here” for insects and fires, but feel free to tag them on the talk page!</p> ''' confusions: ['small cat', 'rodent', 'bird'] confusionsDetail: [' (for civets and genets)', ' (for hyrax and hares)', ' (for bats)'] exampleImages: ["./assets/guide/other-1.jpg", "./assets/guide/other-2.jpg", "./assets/guide/other-3.jpg", "./assets/guide/other-4.jpg"] }, { header: 'other (primate)' subHeader: '<em>Cercopithecidae</em> family and <em>Lorisoidea</em> superfamily' description: ''' <p>Non-ape primates are different from apes in several ways. They typically are smaller, with tails, less broad chests, and less upright posture. African monkeys have non-prehensile tails, hind legs longer than forearms, and downward-pointing nostrils. Coloration varies between species. Africa is also home to galagos (sometimes called bushbabies) and pottos, two kinds of small primitive primate. Monkeys are frequently seen in groups and during the day or at dawn/dusk. Galagos and pottos are usually seen alone and at night.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP00007sb" target="_blank">Monkey Guide</a></p> ''' confusions: ['chimpanzee', 'rodent'] confusionsDetail: [null, ' (for galagos/pottos)'] exampleImages: ["./assets/guide/small-primates-1.jpg", "./assets/guide/small-primates-2.jpg", "./assets/guide/small-primates-3.jpg"] }, { header: 'pangolin' subHeader: '<em>Manis</em> genus' description: '<p>Also called “scaly anteater,” this unique creature’s body is covered from snout to long tail in overlapping earth-toned plates. Multiple species of pangolin are native to Africa, ranging in size from around 2 kg to over 30 kg. Almost always seen at night.</p>' exampleImages: ["./assets/guide/pangolin-1.jpg", "./assets/guide/pangolin-2.jpg", "./assets/guide/pangolin-3.jpg"] }, { header: 'porcupine' subHeader: '<em>Hystricidae</em> family' description: ''' <p>Porcupines are short, rounded creatures covered from head to tail with long quills. Two species of porcupine are found in the study area: the crested porcupine with long quills on the back and sides that are raised into a crest, and the smaller brush-tailed porcupine, which has a small tuft of quills at the end of its thin tail. Both species are almost always seen at night.</p> ''' confusions: ['rodent'] confusionsDetail: [' (although porcupines are rodents, please mark them separately)'] exampleImages: ["./assets/guide/porcupine-1.jpg", "./assets/guide/porcupine-2.jpg", "./assets/guide/porcupine-3.jpg"] }, { header: 'red duiker' subHeader: '<em>Sylvicapra</em> and <em>Cephalophus</em> genuses' description: ''' <p>Use this option to mark small to medium duikers with chestnut-red fur; for example: the bush duiker which is small and reddish-brown, or the Bay duiker, notable for its red body colour and black stripe down its back. Like other duikers, they have arched backs, stocky bodies and slender legs. Some species are seen mainly at night, and others during the day.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope', 'large ungulate'] exampleImages: ["./assets/guide/red-duiker-1.jpg", "./assets/guide/red-duiker-2.jpg", "./assets/guide/red-duiker-3.jpg"] }, { header: 'red river hog' subHeader: '<em>Potamochoerus porcus</em>' description: ''' <p>Pudgy pig-like animal notable for its bright red fur and its curled, pointed, elfin ears with white ear-tufts. The large muzzle is black with two small tusks and white markings around the eyes. Longer fur on flanks and underbelly. Has a line of spiky blonde hair down the spine. Seen both at night and during the day. Bushpigs, close relatives of red river hogs, should also be marked using this classifications. </p> ''' confusions: ['giant forest hog', 'warthog'] exampleImages: ["./assets/guide/red-river-hog-1.jpg", "./assets/guide/red-river-hog-2.jpg", "./assets/guide/red-river-hog-3.jpg"] }, { header: 'reptile' subHeader: '<em>Reptilia</em> class' description: '<p>Reptiles that may be found in Africa include lizards, snakes, turtles, and crocodiles. Reptiles typically have shells or scales, and are often colored in earthtones (though some snakes may have vibrant coloration). Mark all reptiles as "reptile."</p>' exampleImages: ["./assets/guide/reptiles-1.jpg", "./assets/guide/reptiles-2.jpg", "./assets/guide/reptiles-3.jpg"] }, { header: 'rodent' subHeader: '<em>Rodentia</em> order' description: ''' <p>Rodents of Africa include mice, squirrels, gerbils, and rats, but not hares, which should be marked other non-primate. These animals are typically small, with short limbs, thick bodies, and long tails. Rats and mice are almost always seen at night, while squirrels are almost always seen during the day or at dawn/dusk. (Note: please mark porcupines separately.)</p> ''' confusions: ['other (non-primate)'] confusionsDetail: [':hyrax or hare'] exampleImages: ["./assets/guide/rodent-1.jpg", "./assets/guide/rodent-2.jpg", "./assets/guide/rodent-3.jpg"] }, { header: 'small antelope' subHeader: '<em>Bovidae</em> family' description: ''' <p>Use this option to mark any small antelope other than a listed type of duiker; for instance: bushbuck, royal antelope, dik-dik, oribi, pygmy antelope, reedbuck, etc.</p> ''' confusions: ['duiker', 'large ungulate'] exampleImages: ["./assets/guide/sm-antelope-1.jpg", "./assets/guide/sm-antelope-2.jpg", "./assets/guide/sm-antelope-3.jpg"] }, { header: 'small grey duiker' subHeader: '<em>Cephalophus monticola</em> and <em>Cephalophus maxwelli</em>' description: ''' <p>Some of the smallest antelopes. Coat ranges from light brown to blue-grey with paler chest and underbelly. Small spiky horns in most males and some females. Stocky body, arched back, large hindquarters and thin legs. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' confusions: ['small antelope'] exampleImages: ["./assets/guide/sm-gray-duiker-1.jpg", "./assets/guide/sm-gray-duiker-2.jpg"] }, { header: 'small cat' subHeader: '<em>Felinae</em> subfamily' description: '<p>Several species of small felines can be found in Africa, including the caracal, the serval, the African golden cat, and the African wildcat. Any cat smaller than a leopard or a cheetah can be classified as a "small cat." Please note that viverrids, like civets and genets, are not cats, and should be marked as "other (non-primate)."</p>' exampleImages: ["./assets/guide/small-cat-1.jpg", "./assets/guide/small-cat-2.jpg", "./assets/guide/small-cat-3.jpg"] }, { header: 'warthog' subHeader: '<em>Phacochoerus africanus</em>' description: ''' <p>This pig-like animal has a grey body covered sparsely with darker hairs, and mane of long, wiry hairs along its neck and back. Its tail is thick with a black tassel. It has tusks that curve up around its snout. More often seen during the day, but sometimes seen at night.</p> ''' confusions: ['red river hog', 'giant forest hog'] exampleImages: ["./assets/guide/warthog-1.jpg", "./assets/guide/warthog-2.jpg", "./assets/guide/warthog-3.jpg"] }, { header: 'wild dog' subHeader: '<em>Lycaon pictus</em>' description: '<p>Social pack canine with tall, solid build and mottled coat of blacks, browns, reds, and whites. Muzzle is black and tail is typically white-tipped. Build is similar to domestic dogs and lacks hyenas\' sloped backs.</p>' exampleImages: ["./assets/guide/wild-dog-1.jpg", "./assets/guide/wild-dog-2.jpg", "./assets/guide/wild-dog-3.jpg"] }, { header: 'zebra duiker' subHeader: '<em>Cephalophus zebra</em>' description: ''' <p>Easily identifiable by the unique dark zebra-like stripes that cover its chestnut-colored back. Like other duikers, it has an arched back and stocky body with slender legs. The head has conical horns, the muzzle is black, and the lower jaw and undersides white. Usually seen during the day or at dawn/dusk.</p> <p class="talk-link"><a href="http://talk.chimpandsee.org/#/boards/BCP000000e/discussions/DCP0000asr" target="_blank">Duiker Guide</a></p> ''' exampleImages: ["./assets/guide/zebra-duiker-1.jpg"] credit: "Credit: PI:NAME:<NAME>END_PI - Ultimate Ungulate Images." } ], behaviors: [ { header: 'aggression' description: 'Animal is displaying angry and/or threatening behaviour directed towards another animal or towards the camera.' }, { header: 'camera reaction' description: 'Animal is directly reacting to the presence of the video camera. The animal can be staring at the camera while being interested or wary, or poking at the camera. Sometimes you will see an animal look into the camera, walk by it, and then jostle the camera from behind, causing the video to shake.' }, { header: 'carrying object' description: 'Animal (usually a primate or an elephant) is carrying anything like fruit or a stick. Animal may also be carrying fruit, or, in some cases, may be carrying meat from a hunt—if you suspect a chimpanzee is carrying meat, please discuss it in Talk.' }, { header: 'carrying young/clinging' description: 'Animal is carrying a younger animal on its back or front, or a younger animal is clinging to an older animal in some way.' }, { header: 'climbing' description: 'Animal is moving in a mostly vertical direction, usually in a tree or liana' }, { header: 'cross-species interaction' description: 'Animal is doing something (interacting) with another animal of a different species. Interacting means when the actions of one individual is followed by an action in another individual whereby the second appears to be a response to the first one. This does not include two different species just walking by the camera or simply appearing at the same time in the video.' }, { header: 'drinking/feeding' description: 'Animal is drinking or eating food. If the animal or animals, especially chimpanzees, can be seen sharing food with others (often meat, nuts, or large fruits), please make a special note in Talk!' }, { header: 'drumming' description: 'Chimpanzees display a behaviour called "drumming" whereby they run up to a tree and repeatedly hit on it with their hands and/or feet to make a drumming sound. When you see any repeated hitting of a hard surface with hands and/or feet, consider it drumming. Pay very special attention to whether the chimpanzee drums with a stone; if yes, make sure to select the "Tool Use" button as well!' }, { header: 'grooming' description: 'Animal is cleaning itself or another animal. In chimpanzees, this is often seen as one animal scratching or inspecting the fur/hair of another animal and picking things out of the hair (and sometimes even eating these things).' }, { header: 'in a tree' description: 'Animal is perched on a tree, climbing a tree, or is travelling through the trees at any point during the video.' }, { header: 'nursing' description: 'Female animal is giving a teat to its young, which is then suckling to obtain milk.' }, { header: 'on the ground' description: 'Animal is on the ground, either standing or moving.' }, { header: 'playing' description: 'Animal is playing. Play behaviours are often normally expressed behaviours that are done out of context. For example, you may see a chimpanzee performing a threat, hitting, or chasing, but doing so without aggression. In chimpanzees, this is often (but not always) accompanied by a play-face, similar to a kind of smile.' }, { header: 'resting' description: 'Animal is sitting, lying down, sleeping, or otherwise appears relaxed.' }, { header: 'sex/mounting' description: 'Animals are having sexual intercourse or mounting each other. Many primate dominance interactions often include mounting that looks very sexual but is not in fact sex.' }, { header: 'social interaction' description: 'Animal is doing something (interacting) with another animal of the same species. Interacting means that the actions of one individual is followed by an action in another individual, whereby the second appears to be a response to the first one. This does not include two individuals just walking by the camera or simply appearing at the same time in the video.' }, { header: 'tool usage' description: 'Tool use if when an animal uses an external detached object to attain a goal. This is primarily for chimpanzees where you will see them using a tool to accomplish a task. This can be one or a series of stick tools for collecting insects, honey or algae, a wooden or stone hammer to crack nuts, or stone or wooden anvils on which they smash fruit. Seeing a chimpanzee throwing a stone at a tree is also tool use. Keep your eyes peeled for even more types of tool use that might not be on this list!' }, { header: 'traveling' description: 'Animal is walking, running, or otherwise moving and does not stop in front of the camera for long, if at all. Animal could be hunting or fleeing as well. If an animal appears to be hunting, please make a special note in Talk!' }, { header: 'vocalizing' description: 'Animal is making cries or other vocal noises.' } ] } module.exports = guideDetails
[ { "context": "\tif typeof key == \"number\"\r\n\t\t\ti = key\r\n\t\t\tkey = @keys[i]\r\n\t\t\telement = @elements[i]\r\n\t\t\t@elements.splice(", "end": 438, "score": 0.5701131224632263, "start": 432, "tag": "KEY", "value": "keys[i" } ]
src/core/keyed-array.coffee
homeant/cola-ui
90
class cola.util.KeyedArray size: 0 constructor: ()-> @elements = [] @keys = [] @keyMap = {} add: (key, element)-> if @keyMap.hasOwnProperty(key) i = @elements.indexOf(element) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @keyMap[key] = element @size = @elements.push(element) @keys.push(key) return @ remove: (key)-> if typeof key == "number" i = key key = @keys[i] element = @elements[i] @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length delete @keyMap[key] else element = @keyMap[key] delete @keyMap[key] if element i = @keys.indexOf(key) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length return element get: (key)-> if typeof key == "number" return @elements[key] else return @keyMap[key] getIndex: (key)-> if @keyMap.hasOwnProperty(key) return @keys.indexOf(key) return -1 clear: ()-> @elements = [] @keys = [] @keyMap = {} @size = 0 return elements: ()-> return @elements each: (fn)-> keys = @keys for element, i in @elements if fn.call(this, element, keys[i]) == false break return
177395
class cola.util.KeyedArray size: 0 constructor: ()-> @elements = [] @keys = [] @keyMap = {} add: (key, element)-> if @keyMap.hasOwnProperty(key) i = @elements.indexOf(element) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @keyMap[key] = element @size = @elements.push(element) @keys.push(key) return @ remove: (key)-> if typeof key == "number" i = key key = @<KEY>] element = @elements[i] @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length delete @keyMap[key] else element = @keyMap[key] delete @keyMap[key] if element i = @keys.indexOf(key) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length return element get: (key)-> if typeof key == "number" return @elements[key] else return @keyMap[key] getIndex: (key)-> if @keyMap.hasOwnProperty(key) return @keys.indexOf(key) return -1 clear: ()-> @elements = [] @keys = [] @keyMap = {} @size = 0 return elements: ()-> return @elements each: (fn)-> keys = @keys for element, i in @elements if fn.call(this, element, keys[i]) == false break return
true
class cola.util.KeyedArray size: 0 constructor: ()-> @elements = [] @keys = [] @keyMap = {} add: (key, element)-> if @keyMap.hasOwnProperty(key) i = @elements.indexOf(element) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @keyMap[key] = element @size = @elements.push(element) @keys.push(key) return @ remove: (key)-> if typeof key == "number" i = key key = @PI:KEY:<KEY>END_PI] element = @elements[i] @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length delete @keyMap[key] else element = @keyMap[key] delete @keyMap[key] if element i = @keys.indexOf(key) if i > -1 @elements.splice(i, 1) @keys.splice(i, 1) @size = @elements.length return element get: (key)-> if typeof key == "number" return @elements[key] else return @keyMap[key] getIndex: (key)-> if @keyMap.hasOwnProperty(key) return @keys.indexOf(key) return -1 clear: ()-> @elements = [] @keys = [] @keyMap = {} @size = 0 return elements: ()-> return @elements each: (fn)-> keys = @keys for element, i in @elements if fn.call(this, element, keys[i]) == false break return
[ { "context": "/PEM--/grunt-phonegapsplash\n#\n# Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under", "end": 120, "score": 0.9998788833618164, "start": 98, "tag": "NAME", "value": "Pierre-Eric Marchandet" }, { "context": "Copyright (c) 2013 Pi...
lib/profiles.coffee
oarsheo/grunt-phonegapsplash
0
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>) # Licensed under the MIT licence. ### 'use strict' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' ### # All profiles for every splashscreens covered by PhoneGap are stored hereafter # with the following structure: # # * platform: A dictionary key representing the OS (the platform) # * dir: The subfolder where are stored the splashscreens # * layout: A dictionary key representing the available layouts # * splashs: An array of the required splashscreens # * name: The name of the splashscreen # * width: The width of the splashscreen # * height: The height of the splascreen ### module.exports = (config) -> # Android 'android': dir: path.join 'android', 'app', 'src', 'main', 'res' layout: landscape: splashs: [ { name: (path.join 'drawable-land-ldpi', 'screen.png') width: 320, height: 200 } { name: (path.join 'drawable-land-mdpi', 'screen.png') width: 480, height: 320 } { name: (path.join 'drawable-land-hdpi', 'screen.png') width: 800, height: 480 } { name: (path.join 'drawable-land-xhdpi', 'screen.png') width: 1280, height: 720 } ] portrait: splashs: [ { name: (path.join 'drawable-port-ldpi', 'screen.png') width: 200, height: 320 } { name: (path.join 'drawable-port-mdpi', 'screen.png') width: 320, height: 480 } { name: (path.join 'drawable-port-hdpi', 'screen.png') width: 480, height: 800 } { name: (path.join 'drawable-port-xhdpi', 'screen.png') width: 720, height: 1280 } { name: (path.join 'drawable-port-xxhdpi', 'screen.png') width: 960, height: 1600 } { name: (path.join 'drawable-port-xxxhdpi', 'screen.png') width: 1280, height: 1920 } ] # iOS (Retina and legacy resolutions) 'ios': dir: path.join 'ios', config.prjName, 'Images.xcassets', 'LaunchImage.launchimage' layout: landscape: splashs: [ { name: 'Default-Landscape~ipad.png', width: 1024, height: 768 } { name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 } { name: 'Default-Landscape-736h.png', width: 2208, height: 1242 } ] portrait: splashs: [ { name: 'Default~iphone.png', width: 320, height: 480 } { name: 'Default@2x~iphone.png', width: 640, height: 960 } { name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 } { name: 'Default-Portrait~ipad.png', width: 768, height: 1024 } { name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 } { name: 'Default-667h.png', width: 750, height: 1334 } { name: 'Default-736h.png', width: 1242, height: 2208 } { name: 'Default-2436h.png', width: 1125, height: 2436 } { name: 'Default@3x~iphone~comany.png', width: 1242, height: 2436 } { name: 'Default@2x~iphone~anyany.png', width: 1334, height: 1334 } { name: 'Default@2x~iphone~comany.png', width: 750, height: 1334 } { name: 'Default@2x~iphone~comcom.png', width: 750, height: 750 } { name: 'Default@3x~iphone~anyany.png', width: 2436, height: 2436 } { name: 'Default@3x~iphone~anycom.png', width: 2436, height: 1242 } { name: 'Default@2x~ipad~anyany.png', width: 2732, height: 2732 } { name: 'Default@2x~ipad~comany.png', width: 1278, height: 2732 } { name: 'Default@1x~iphone~comany.png', width: 1125, height: 2436 } ]
47189
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 <NAME> (PEM-- <<EMAIL>>) # Licensed under the MIT licence. ### 'use strict' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' ### # All profiles for every splashscreens covered by PhoneGap are stored hereafter # with the following structure: # # * platform: A dictionary key representing the OS (the platform) # * dir: The subfolder where are stored the splashscreens # * layout: A dictionary key representing the available layouts # * splashs: An array of the required splashscreens # * name: The name of the splashscreen # * width: The width of the splashscreen # * height: The height of the splascreen ### module.exports = (config) -> # Android 'android': dir: path.join 'android', 'app', 'src', 'main', 'res' layout: landscape: splashs: [ { name: (path.join 'drawable-land-ldpi', 'screen.png') width: 320, height: 200 } { name: (path.join 'drawable-land-mdpi', 'screen.png') width: 480, height: 320 } { name: (path.join 'drawable-land-hdpi', 'screen.png') width: 800, height: 480 } { name: (path.join 'drawable-land-xhdpi', 'screen.png') width: 1280, height: 720 } ] portrait: splashs: [ { name: (path.join 'drawable-port-ldpi', 'screen.png') width: 200, height: 320 } { name: (path.join 'drawable-port-mdpi', 'screen.png') width: 320, height: 480 } { name: (path.join 'drawable-port-hdpi', 'screen.png') width: 480, height: 800 } { name: (path.join 'drawable-port-xhdpi', 'screen.png') width: 720, height: 1280 } { name: (path.join 'drawable-port-xxhdpi', 'screen.png') width: 960, height: 1600 } { name: (path.join 'drawable-port-xxxhdpi', 'screen.png') width: 1280, height: 1920 } ] # iOS (Retina and legacy resolutions) 'ios': dir: path.join 'ios', config.prjName, 'Images.xcassets', 'LaunchImage.launchimage' layout: landscape: splashs: [ { name: 'Default-Landscape~ipad.png', width: 1024, height: 768 } { name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 } { name: 'Default-Landscape-736h.png', width: 2208, height: 1242 } ] portrait: splashs: [ { name: 'Default~iphone.png', width: 320, height: 480 } { name: 'Default@2x~iphone.png', width: 640, height: 960 } { name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 } { name: 'Default-Portrait~ipad.png', width: 768, height: 1024 } { name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 } { name: 'Default-667h.png', width: 750, height: 1334 } { name: 'Default-736h.png', width: 1242, height: 2208 } { name: 'Default-2436h.png', width: 1125, height: 2436 } { name: 'Default@3x~iphone~comany.png', width: 1242, height: 2436 } { name: 'Default@2x~iphone~anyany.png', width: 1334, height: 1334 } { name: 'Default@2x~iphone~comany.png', width: 750, height: 1334 } { name: 'Default@2x~iphone~comcom.png', width: 750, height: 750 } { name: 'Default@3x~iphone~anyany.png', width: 2436, height: 2436 } { name: 'Default@3x~iphone~anycom.png', width: 2436, height: 1242 } { name: 'Default@2x~ipad~anyany.png', width: 2732, height: 2732 } { name: 'Default@2x~ipad~comany.png', width: 1278, height: 2732 } { name: 'Default@1x~iphone~comany.png', width: 1125, height: 2436 } ]
true
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 PI:NAME:<NAME>END_PI (PEM-- <PI:EMAIL:<EMAIL>END_PI>) # Licensed under the MIT licence. ### 'use strict' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' ### # All profiles for every splashscreens covered by PhoneGap are stored hereafter # with the following structure: # # * platform: A dictionary key representing the OS (the platform) # * dir: The subfolder where are stored the splashscreens # * layout: A dictionary key representing the available layouts # * splashs: An array of the required splashscreens # * name: The name of the splashscreen # * width: The width of the splashscreen # * height: The height of the splascreen ### module.exports = (config) -> # Android 'android': dir: path.join 'android', 'app', 'src', 'main', 'res' layout: landscape: splashs: [ { name: (path.join 'drawable-land-ldpi', 'screen.png') width: 320, height: 200 } { name: (path.join 'drawable-land-mdpi', 'screen.png') width: 480, height: 320 } { name: (path.join 'drawable-land-hdpi', 'screen.png') width: 800, height: 480 } { name: (path.join 'drawable-land-xhdpi', 'screen.png') width: 1280, height: 720 } ] portrait: splashs: [ { name: (path.join 'drawable-port-ldpi', 'screen.png') width: 200, height: 320 } { name: (path.join 'drawable-port-mdpi', 'screen.png') width: 320, height: 480 } { name: (path.join 'drawable-port-hdpi', 'screen.png') width: 480, height: 800 } { name: (path.join 'drawable-port-xhdpi', 'screen.png') width: 720, height: 1280 } { name: (path.join 'drawable-port-xxhdpi', 'screen.png') width: 960, height: 1600 } { name: (path.join 'drawable-port-xxxhdpi', 'screen.png') width: 1280, height: 1920 } ] # iOS (Retina and legacy resolutions) 'ios': dir: path.join 'ios', config.prjName, 'Images.xcassets', 'LaunchImage.launchimage' layout: landscape: splashs: [ { name: 'Default-Landscape~ipad.png', width: 1024, height: 768 } { name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 } { name: 'Default-Landscape-736h.png', width: 2208, height: 1242 } ] portrait: splashs: [ { name: 'Default~iphone.png', width: 320, height: 480 } { name: 'Default@2x~iphone.png', width: 640, height: 960 } { name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 } { name: 'Default-Portrait~ipad.png', width: 768, height: 1024 } { name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 } { name: 'Default-667h.png', width: 750, height: 1334 } { name: 'Default-736h.png', width: 1242, height: 2208 } { name: 'Default-2436h.png', width: 1125, height: 2436 } { name: 'Default@3x~iphone~comany.png', width: 1242, height: 2436 } { name: 'Default@2x~iphone~anyany.png', width: 1334, height: 1334 } { name: 'Default@2x~iphone~comany.png', width: 750, height: 1334 } { name: 'Default@2x~iphone~comcom.png', width: 750, height: 750 } { name: 'Default@3x~iphone~anyany.png', width: 2436, height: 2436 } { name: 'Default@3x~iphone~anycom.png', width: 2436, height: 1242 } { name: 'Default@2x~ipad~anyany.png', width: 2732, height: 2732 } { name: 'Default@2x~ipad~comany.png', width: 1278, height: 2732 } { name: 'Default@1x~iphone~comany.png', width: 1125, height: 2436 } ]
[ { "context": "n\"\ncs += \" addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}\\n\"\ncs += \" router.log \\", "end": 1202, "score": 0.9996731877326965, "start": 1195, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "s) {\n return res.end(\"Hello, W...
images/Postman.app/Contents/Resources/app/node_modules/node-simple-router/src/mk-server.coffee
longjo/longjo.github.io
7
#!/usr/bin/env coffee cs = "#!/usr/bin/env coffee" cs += "\n\n" cs += "try\n" cs += " Router = require 'node-simple-router'\n" cs += "catch e\n" cs += " Router = require '../lib/router'\n\n" cs += "http = require 'http'\n" cs += "router = Router(list_dir: true)\n" cs += "#\n" cs += "#Example routes\n" cs += "#\n" cs += "router.get \"/\", (request, response) ->\n" cs += " response.end 'Home'\n\n" cs += "router.get \"/hello\", (req, res) ->\n" cs += " res.end 'Hello, World!, Hola, Mundo!'\n\n" cs += "router.get \"/users\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end '<h1 style=\"color: navy; text-align: center;\">Active members registry</h1>'\n\n" cs += "router.get \"/users/:id\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end \"<h1>User No: <span style='color: red;'>\" + req.params.id + \"</span></h1>\"\n\n" cs += "#\n" cs += "#End of example routes\n" cs += "#\n\n\n" cs += "#Ok, just start the server!\n\n" cs += "argv = process.argv.slice 2\n\n" cs += "server = http.createServer router\n\n" cs += "server.on 'listening', ->\n" cs += " addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}\n" cs += " router.log \"Serving web content at \" + addr.address + \":\" + addr.port \n\n" cs += "process.on \"SIGINT\", ->\n" cs += " server.close()\n" cs += " router.log ' '\n" cs += " router.log \"Server shutting up...\"\n" cs += " router.log ' '\n" cs += " process.exit 0\n\n" cs += "server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000\n" js = """ #!/usr/bin/env node // Generated by CoffeeScript 1.4.0 (function() { var Router, argv, http, router, server; try { Router = require('node-simple-router'); } catch (e) { Router = require('../lib/router'); } http = require('http'); router = Router({ list_dir: true }); /* Example routes */ router.get("/", function(req, res) { return res.end("Home"); }); router.get("/hello", function(req, res) { return res.end("Hello, World!, Hola, Mundo!"); }); router.get("/users", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1 style='color: navy; text-align: center;'>Active members registry</h1>"); }); router.get("/users/:id", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1>User No: <span style='color: red;'>" + req.params.id + "</span></h1>"); }); /* End of example routes */ argv = process.argv.slice(2); server = http.createServer(router); server.on('listening', function() { var addr; addr = server.address() || { address: '0.0.0.0', port: argv[0] || 8000 }; return router.log("Serving web content at " + addr.address + ":" + addr.port); }); process.on("SIGINT", function() { server.close(); router.log(" "); router.log("Server shutting up..."); router.log(" "); return process.exit(0); }); server.listen((argv[0] != null) && !isNaN(parseInt(argv[0])) ? parseInt(argv[0]) : 8000); }).call(this); """ fs = require 'fs' filename = if process.argv[2]?.toLowerCase() is 'js' then 'server.js' else 'server.coffee' full_filename = "#{process.cwd()}/#{filename}" text = if process.argv[2]?.toLowerCase() is 'js' then js else cs fs.writeFileSync full_filename, text fs.chmodSync full_filename, 0o755
80581
#!/usr/bin/env coffee cs = "#!/usr/bin/env coffee" cs += "\n\n" cs += "try\n" cs += " Router = require 'node-simple-router'\n" cs += "catch e\n" cs += " Router = require '../lib/router'\n\n" cs += "http = require 'http'\n" cs += "router = Router(list_dir: true)\n" cs += "#\n" cs += "#Example routes\n" cs += "#\n" cs += "router.get \"/\", (request, response) ->\n" cs += " response.end 'Home'\n\n" cs += "router.get \"/hello\", (req, res) ->\n" cs += " res.end 'Hello, World!, Hola, Mundo!'\n\n" cs += "router.get \"/users\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end '<h1 style=\"color: navy; text-align: center;\">Active members registry</h1>'\n\n" cs += "router.get \"/users/:id\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end \"<h1>User No: <span style='color: red;'>\" + req.params.id + \"</span></h1>\"\n\n" cs += "#\n" cs += "#End of example routes\n" cs += "#\n\n\n" cs += "#Ok, just start the server!\n\n" cs += "argv = process.argv.slice 2\n\n" cs += "server = http.createServer router\n\n" cs += "server.on 'listening', ->\n" cs += " addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}\n" cs += " router.log \"Serving web content at \" + addr.address + \":\" + addr.port \n\n" cs += "process.on \"SIGINT\", ->\n" cs += " server.close()\n" cs += " router.log ' '\n" cs += " router.log \"Server shutting up...\"\n" cs += " router.log ' '\n" cs += " process.exit 0\n\n" cs += "server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000\n" js = """ #!/usr/bin/env node // Generated by CoffeeScript 1.4.0 (function() { var Router, argv, http, router, server; try { Router = require('node-simple-router'); } catch (e) { Router = require('../lib/router'); } http = require('http'); router = Router({ list_dir: true }); /* Example routes */ router.get("/", function(req, res) { return res.end("Home"); }); router.get("/hello", function(req, res) { return res.end("Hello, World!, Hola, M<NAME>!"); }); router.get("/users", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1 style='color: navy; text-align: center;'>Active members registry</h1>"); }); router.get("/users/:id", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1>User No: <span style='color: red;'>" + req.params.id + "</span></h1>"); }); /* End of example routes */ argv = process.argv.slice(2); server = http.createServer(router); server.on('listening', function() { var addr; addr = server.address() || { address: '0.0.0.0', port: argv[0] || 8000 }; return router.log("Serving web content at " + addr.address + ":" + addr.port); }); process.on("SIGINT", function() { server.close(); router.log(" "); router.log("Server shutting up..."); router.log(" "); return process.exit(0); }); server.listen((argv[0] != null) && !isNaN(parseInt(argv[0])) ? parseInt(argv[0]) : 8000); }).call(this); """ fs = require 'fs' filename = if process.argv[2]?.toLowerCase() is 'js' then 'server.js' else 'server.coffee' full_filename = "#{process.cwd()}/#{filename}" text = if process.argv[2]?.toLowerCase() is 'js' then js else cs fs.writeFileSync full_filename, text fs.chmodSync full_filename, 0o755
true
#!/usr/bin/env coffee cs = "#!/usr/bin/env coffee" cs += "\n\n" cs += "try\n" cs += " Router = require 'node-simple-router'\n" cs += "catch e\n" cs += " Router = require '../lib/router'\n\n" cs += "http = require 'http'\n" cs += "router = Router(list_dir: true)\n" cs += "#\n" cs += "#Example routes\n" cs += "#\n" cs += "router.get \"/\", (request, response) ->\n" cs += " response.end 'Home'\n\n" cs += "router.get \"/hello\", (req, res) ->\n" cs += " res.end 'Hello, World!, Hola, Mundo!'\n\n" cs += "router.get \"/users\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end '<h1 style=\"color: navy; text-align: center;\">Active members registry</h1>'\n\n" cs += "router.get \"/users/:id\", (req, res) ->\n" cs += " res.writeHead(200, {'Content-type': 'text/html'})\n" cs += " res.end \"<h1>User No: <span style='color: red;'>\" + req.params.id + \"</span></h1>\"\n\n" cs += "#\n" cs += "#End of example routes\n" cs += "#\n\n\n" cs += "#Ok, just start the server!\n\n" cs += "argv = process.argv.slice 2\n\n" cs += "server = http.createServer router\n\n" cs += "server.on 'listening', ->\n" cs += " addr = server.address() or {address: '0.0.0.0', port: argv[0] or 8000}\n" cs += " router.log \"Serving web content at \" + addr.address + \":\" + addr.port \n\n" cs += "process.on \"SIGINT\", ->\n" cs += " server.close()\n" cs += " router.log ' '\n" cs += " router.log \"Server shutting up...\"\n" cs += " router.log ' '\n" cs += " process.exit 0\n\n" cs += "server.listen if argv[0]? and not isNaN(parseInt(argv[0])) then parseInt(argv[0]) else 8000\n" js = """ #!/usr/bin/env node // Generated by CoffeeScript 1.4.0 (function() { var Router, argv, http, router, server; try { Router = require('node-simple-router'); } catch (e) { Router = require('../lib/router'); } http = require('http'); router = Router({ list_dir: true }); /* Example routes */ router.get("/", function(req, res) { return res.end("Home"); }); router.get("/hello", function(req, res) { return res.end("Hello, World!, Hola, MPI:NAME:<NAME>END_PI!"); }); router.get("/users", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1 style='color: navy; text-align: center;'>Active members registry</h1>"); }); router.get("/users/:id", function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); return res.end("<h1>User No: <span style='color: red;'>" + req.params.id + "</span></h1>"); }); /* End of example routes */ argv = process.argv.slice(2); server = http.createServer(router); server.on('listening', function() { var addr; addr = server.address() || { address: '0.0.0.0', port: argv[0] || 8000 }; return router.log("Serving web content at " + addr.address + ":" + addr.port); }); process.on("SIGINT", function() { server.close(); router.log(" "); router.log("Server shutting up..."); router.log(" "); return process.exit(0); }); server.listen((argv[0] != null) && !isNaN(parseInt(argv[0])) ? parseInt(argv[0]) : 8000); }).call(this); """ fs = require 'fs' filename = if process.argv[2]?.toLowerCase() is 'js' then 'server.js' else 'server.coffee' full_filename = "#{process.cwd()}/#{filename}" text = if process.argv[2]?.toLowerCase() is 'js' then js else cs fs.writeFileSync full_filename, text fs.chmodSync full_filename, 0o755
[ { "context": " def = {\n id: id,\n name: name,\n type: type,\n domain: doma", "end": 12061, "score": 0.999542236328125, "start": 12057, "tag": "NAME", "value": "name" } ]
csat/visualization/assets/coffeescripts/graph.coffee
GaretJax/csat
0
parseIds = (id, onlyLast=false) -> tokens = id.split('::') if onlyLast parseInt(tokens[tokens.length-1].replace(/^n|g|d|e/, '')) else tokens.map((el) -> parseInt(el.replace(/^n|g|d|e/, '')) ) class NeighborsIterator constructor: (@node) -> @directed = true @index = 0 next: => if @directed if @index < @node._outEdges.length return @node._outEdges[@index++].dst else @directed = false @index = 0 if @index < @node._edges.length edge = @node._edges[@index++] if edge.dst == @node return edge.src else return edge.dst throw StopIteration class Node constructor: (@model, @domain, id, @attributes, @_globalId) -> @fqid = parseIds(id) @id = @fqid.last() @_offset = new THREE.Vector3(0, 0, 0) @_position = new THREE.Vector3(0, 0, 0) @_absPosition = new THREE.Vector3(0, 0, 0) @_degree = 0 @_inDegree = 0 @_outDegree = 0 @_selfloops = 0 @_size = 10 @_color = new THREE.Color(0xffffff) @_opacity = 1.0 @_visible = true @_label = @fqid.join(',') @_inEdges = [] @_outEdges = [] @_edges = [] @neighbors = new IteratorFactory(NeighborsIterator, [this]) getAbsoluteID: -> @fqid.join('::') setOffset: (o) -> ### Sets the offset to be applied to the node after its domain-relative position has been defined. ### @_offset = o @updatePosition() setPosition: (p) -> ### Sets the position of the node relative to the absolute coordinates of the domain node. ### @_position.x = p.x @_position.y = p.y @_position.z = p.z @updatePosition() getPosition: -> ### Gets the position of the node relative to the domain. ### return @_position getAbsolutePosition: -> ### Gets the position of the node relative to the origin of the coordinate system, by including any offset due to the domain position. ### return @_absPosition updatePosition: -> ### Updates the absolute position of the object by applying the offset to the position. ### # Use a matrix transformation here to be able to do generic affine # transformations in the future (mainly to include plane rotations # for domains). transformation = new THREE.Matrix4( 1, 0, 0, @_offset.x, 0, 1, 0, @_offset.y, 0, 0, 1, @_offset.z, 0, 0, 0, 1, ) transformed = @_position.clone().applyMatrix4(transformation) @_absPosition.copy(transformed) getSize: -> @_size setSize: (@_size) -> @domain.nodeSizes[@id] = @_size return @ getColor: -> @_color setColor: (color) -> @domain.nodeColors[@id] = @_color = new THREE.Color(color) return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.nodeOpacity[@id] = @_opacity return @ getDegree: -> @_degree getLabel: -> @_label setLabel: (label) -> @_label = "#{label}" return @ getAttr: (key) -> switch key when 'domain' if @domain return @domain.getAttr('domain') else return @attributes['domain'] when 'totdegree' return @_degree + @_inDegree + @_outDegree + 2 * @_selfloops when 'degree' return @_degree when 'selfloops' return @_selfloops when 'indegree' return @_inDegree when 'outdegree' return @_outDegree else return @attributes[key] isVisible: -> @_visible hide: -> @_visible = false @domain.nodeVisibility[@id] = 0.0 return @ show: -> @_visible = true @domain.nodeVisibility[@id] = 1.0 return @ class Edge constructor: (@model, @domain, @id, @src, @dst, @attributes, real=true) -> if attributes._directed? direction = attributes._directed else if domain? direction = domain.edgedefault else direction = model.edgedefault switch direction when 'true', 'directed' @directed = true when 'false', 'undirected' @directed = false else throw "Invalid direction #{direction}" if real if @directed @src._outEdges.push(@) @dst._inEdges.push(@) else @src._edges.push(@) @dst._edges.push(@) @_weight = 1 @_color = new THREE.Color(0x000000) @_opacity = 0.5 @_visible = true if not @domain? @domain = @model if @src == @dst @src._selfloops += 1 else if @directed @src._outDegree += 1 @dst._inDegree += 1 else @src._degree += 1 @dst._degree += 1 other: (node) -> if node == @src return @dst if node == @dst return @src throw 'Node not linked by this edge' getWeight: -> @_weight setWeight: (@_weight) -> @domain.edgeWeights[@_index * 2] = @_weight @domain.edgeWeights[@_index * 2 + 1] = @_weight return @ getColor: -> @_color setColor: (color) -> @domain.edgeColors[@_index * 2] = @_color = new THREE.Color(color) @domain.edgeColors[@_index * 2 + 1] = @_color return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.edgeOpacity[@_index * 2] = @_opacity @domain.edgeOpacity[@_index * 2 + 1] = @_opacity return @ isVisible: -> @_visible hide: -> @_visible = false @domain.edgeVisibility[@_index * 2] = 0.0 @domain.edgeVisibility[@_index * 2 + 1] = 0.0 return @ show: -> @_visible = true @domain.edgeVisibility[@_index * 2] = 1.0 @domain.edgeVisibility[@_index * 2 + 1] = 1.0 return @ class Domain extends Node constructor: (@model, id, @attributes) -> super(@model, undefined, id, @attributes) @texture = THREE.ImageUtils.loadTexture('/static/images/node-textures/ball2.png') #uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping @nodes = [] @edges = [] @nodeSizes = [] @nodeOpacity = [] @nodeColors = [] @nodeVisibility = [] @nodePositions = [] @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] rebuildAttributeMappings: => @nodeSizes.length = 0 @nodeColors.length = 0 @nodePositions.length = 0 @nodes.iter((n, i) => @nodeSizes[i] = n.getSize() @nodeOpacity[i] = n.getOpacity() @nodeColors[i] = n.getColor() @nodeVisibility[i] = n.isVisible() @nodePositions[i] = n.getAbsolutePosition() ) @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @edges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) setTexture: (url) -> @texture = THREE.ImageUtils.loadTexture(url) addNode: (el) -> attrs = this.model._getAttributes(el) node = new Node(@model, @, el.attr('id'), attrs) @nodes[node.id] = node node.setOffset(@getAbsolutePosition()) return node addEdge: (el) -> attrs = this.model._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) if src[0] != dst[0] or src[0] != @id throw "Invalid edge definition" src = this.nodes[src[1]] dst = this.nodes[dst[1]] edge = new Edge(this.model, this, el.attr('id'), src, dst, attrs) edge._index = this.edges.length this.edges.push(edge) return edge class GraphModel extends EventDispatcher @fromGraphML: (data) -> xml = $(data) graph = new GraphModel() graph.edgedefault = $('graphml > graph', xml).attr('edgedefault') $('graphml > key', xml).each((i) -> graph.addAttribute($(this)) ) graph._attributes = graph._getAttributes($('graphml > graph', xml)) $('graphml > graph > node', xml).each((i) -> domain = graph.addDomain($(this)) domain.edgedefault = $('> graph', this).attr('edgedefault') $('> graph > node', this).each(-> domain.addNode($(this)) ) $('> graph > edge', this).each(-> domain.addEdge($(this)) ) domain.rebuildAttributeMappings() ) $('graphml > graph > edge', xml).each(-> graph.addEdge($(this)) ) graph.rebuildAttributeMappings() return graph constructor: -> super this.nextNodeId = 0 this.nextEdgeId = 0 this.domains = [] this.superedges = [] this.attributes = { node: {}, graph: {}, edge: {}, all: {}, _by_id: {}, } @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] @nodes = new IteratorFactory(ArrayPropertyIterator, [this.domains, 'nodes']) @edges = new IteratorFactory(FlattenIterator, [[ @superedges, new IteratorFactory(ArrayPropertyIterator, [this.domains, 'edges']) ]]) rebuildAttributeMappings: => @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @superedges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) getNodeAttributes: -> $.extend({}, @attributes.node, @attributes.all) _getAttributes: (el) -> data = {} attrs = this.attributes._by_id $('> data', el).each(-> el = $(this) data[attrs[el.attr('key')].name] = el.text() ) return data addAttribute: (el) -> id = el.attr('id') name = el.attr('attr.name') type = el.attr('attr.type') domain = el.attr('for') def = { id: id, name: name, type: type, domain: domain, } this.attributes._by_id[id] = def this.attributes[domain][name] = def addDomain: (el) -> domain = new Domain(this, el.attr('id'), this._getAttributes(el)) this.domains[domain.id] = domain addEdge: (el) -> attrs = this._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) src = this.domains[src[0]].nodes[src[1]] dst = this.domains[dst[0]].nodes[dst[1]] src._degree += 1 dst._degree += 1 edge = new Edge(this, undefined, el.attr('id'), src, dst, attrs) edge._index = @superedges.length this.superedges.push(edge) return edge numNodes: -> total = 0 for d in this.domains total += d.nodes.length return total getAttr: (name) -> @_attributes[name]
117364
parseIds = (id, onlyLast=false) -> tokens = id.split('::') if onlyLast parseInt(tokens[tokens.length-1].replace(/^n|g|d|e/, '')) else tokens.map((el) -> parseInt(el.replace(/^n|g|d|e/, '')) ) class NeighborsIterator constructor: (@node) -> @directed = true @index = 0 next: => if @directed if @index < @node._outEdges.length return @node._outEdges[@index++].dst else @directed = false @index = 0 if @index < @node._edges.length edge = @node._edges[@index++] if edge.dst == @node return edge.src else return edge.dst throw StopIteration class Node constructor: (@model, @domain, id, @attributes, @_globalId) -> @fqid = parseIds(id) @id = @fqid.last() @_offset = new THREE.Vector3(0, 0, 0) @_position = new THREE.Vector3(0, 0, 0) @_absPosition = new THREE.Vector3(0, 0, 0) @_degree = 0 @_inDegree = 0 @_outDegree = 0 @_selfloops = 0 @_size = 10 @_color = new THREE.Color(0xffffff) @_opacity = 1.0 @_visible = true @_label = @fqid.join(',') @_inEdges = [] @_outEdges = [] @_edges = [] @neighbors = new IteratorFactory(NeighborsIterator, [this]) getAbsoluteID: -> @fqid.join('::') setOffset: (o) -> ### Sets the offset to be applied to the node after its domain-relative position has been defined. ### @_offset = o @updatePosition() setPosition: (p) -> ### Sets the position of the node relative to the absolute coordinates of the domain node. ### @_position.x = p.x @_position.y = p.y @_position.z = p.z @updatePosition() getPosition: -> ### Gets the position of the node relative to the domain. ### return @_position getAbsolutePosition: -> ### Gets the position of the node relative to the origin of the coordinate system, by including any offset due to the domain position. ### return @_absPosition updatePosition: -> ### Updates the absolute position of the object by applying the offset to the position. ### # Use a matrix transformation here to be able to do generic affine # transformations in the future (mainly to include plane rotations # for domains). transformation = new THREE.Matrix4( 1, 0, 0, @_offset.x, 0, 1, 0, @_offset.y, 0, 0, 1, @_offset.z, 0, 0, 0, 1, ) transformed = @_position.clone().applyMatrix4(transformation) @_absPosition.copy(transformed) getSize: -> @_size setSize: (@_size) -> @domain.nodeSizes[@id] = @_size return @ getColor: -> @_color setColor: (color) -> @domain.nodeColors[@id] = @_color = new THREE.Color(color) return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.nodeOpacity[@id] = @_opacity return @ getDegree: -> @_degree getLabel: -> @_label setLabel: (label) -> @_label = "#{label}" return @ getAttr: (key) -> switch key when 'domain' if @domain return @domain.getAttr('domain') else return @attributes['domain'] when 'totdegree' return @_degree + @_inDegree + @_outDegree + 2 * @_selfloops when 'degree' return @_degree when 'selfloops' return @_selfloops when 'indegree' return @_inDegree when 'outdegree' return @_outDegree else return @attributes[key] isVisible: -> @_visible hide: -> @_visible = false @domain.nodeVisibility[@id] = 0.0 return @ show: -> @_visible = true @domain.nodeVisibility[@id] = 1.0 return @ class Edge constructor: (@model, @domain, @id, @src, @dst, @attributes, real=true) -> if attributes._directed? direction = attributes._directed else if domain? direction = domain.edgedefault else direction = model.edgedefault switch direction when 'true', 'directed' @directed = true when 'false', 'undirected' @directed = false else throw "Invalid direction #{direction}" if real if @directed @src._outEdges.push(@) @dst._inEdges.push(@) else @src._edges.push(@) @dst._edges.push(@) @_weight = 1 @_color = new THREE.Color(0x000000) @_opacity = 0.5 @_visible = true if not @domain? @domain = @model if @src == @dst @src._selfloops += 1 else if @directed @src._outDegree += 1 @dst._inDegree += 1 else @src._degree += 1 @dst._degree += 1 other: (node) -> if node == @src return @dst if node == @dst return @src throw 'Node not linked by this edge' getWeight: -> @_weight setWeight: (@_weight) -> @domain.edgeWeights[@_index * 2] = @_weight @domain.edgeWeights[@_index * 2 + 1] = @_weight return @ getColor: -> @_color setColor: (color) -> @domain.edgeColors[@_index * 2] = @_color = new THREE.Color(color) @domain.edgeColors[@_index * 2 + 1] = @_color return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.edgeOpacity[@_index * 2] = @_opacity @domain.edgeOpacity[@_index * 2 + 1] = @_opacity return @ isVisible: -> @_visible hide: -> @_visible = false @domain.edgeVisibility[@_index * 2] = 0.0 @domain.edgeVisibility[@_index * 2 + 1] = 0.0 return @ show: -> @_visible = true @domain.edgeVisibility[@_index * 2] = 1.0 @domain.edgeVisibility[@_index * 2 + 1] = 1.0 return @ class Domain extends Node constructor: (@model, id, @attributes) -> super(@model, undefined, id, @attributes) @texture = THREE.ImageUtils.loadTexture('/static/images/node-textures/ball2.png') #uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping @nodes = [] @edges = [] @nodeSizes = [] @nodeOpacity = [] @nodeColors = [] @nodeVisibility = [] @nodePositions = [] @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] rebuildAttributeMappings: => @nodeSizes.length = 0 @nodeColors.length = 0 @nodePositions.length = 0 @nodes.iter((n, i) => @nodeSizes[i] = n.getSize() @nodeOpacity[i] = n.getOpacity() @nodeColors[i] = n.getColor() @nodeVisibility[i] = n.isVisible() @nodePositions[i] = n.getAbsolutePosition() ) @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @edges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) setTexture: (url) -> @texture = THREE.ImageUtils.loadTexture(url) addNode: (el) -> attrs = this.model._getAttributes(el) node = new Node(@model, @, el.attr('id'), attrs) @nodes[node.id] = node node.setOffset(@getAbsolutePosition()) return node addEdge: (el) -> attrs = this.model._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) if src[0] != dst[0] or src[0] != @id throw "Invalid edge definition" src = this.nodes[src[1]] dst = this.nodes[dst[1]] edge = new Edge(this.model, this, el.attr('id'), src, dst, attrs) edge._index = this.edges.length this.edges.push(edge) return edge class GraphModel extends EventDispatcher @fromGraphML: (data) -> xml = $(data) graph = new GraphModel() graph.edgedefault = $('graphml > graph', xml).attr('edgedefault') $('graphml > key', xml).each((i) -> graph.addAttribute($(this)) ) graph._attributes = graph._getAttributes($('graphml > graph', xml)) $('graphml > graph > node', xml).each((i) -> domain = graph.addDomain($(this)) domain.edgedefault = $('> graph', this).attr('edgedefault') $('> graph > node', this).each(-> domain.addNode($(this)) ) $('> graph > edge', this).each(-> domain.addEdge($(this)) ) domain.rebuildAttributeMappings() ) $('graphml > graph > edge', xml).each(-> graph.addEdge($(this)) ) graph.rebuildAttributeMappings() return graph constructor: -> super this.nextNodeId = 0 this.nextEdgeId = 0 this.domains = [] this.superedges = [] this.attributes = { node: {}, graph: {}, edge: {}, all: {}, _by_id: {}, } @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] @nodes = new IteratorFactory(ArrayPropertyIterator, [this.domains, 'nodes']) @edges = new IteratorFactory(FlattenIterator, [[ @superedges, new IteratorFactory(ArrayPropertyIterator, [this.domains, 'edges']) ]]) rebuildAttributeMappings: => @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @superedges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) getNodeAttributes: -> $.extend({}, @attributes.node, @attributes.all) _getAttributes: (el) -> data = {} attrs = this.attributes._by_id $('> data', el).each(-> el = $(this) data[attrs[el.attr('key')].name] = el.text() ) return data addAttribute: (el) -> id = el.attr('id') name = el.attr('attr.name') type = el.attr('attr.type') domain = el.attr('for') def = { id: id, name: <NAME>, type: type, domain: domain, } this.attributes._by_id[id] = def this.attributes[domain][name] = def addDomain: (el) -> domain = new Domain(this, el.attr('id'), this._getAttributes(el)) this.domains[domain.id] = domain addEdge: (el) -> attrs = this._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) src = this.domains[src[0]].nodes[src[1]] dst = this.domains[dst[0]].nodes[dst[1]] src._degree += 1 dst._degree += 1 edge = new Edge(this, undefined, el.attr('id'), src, dst, attrs) edge._index = @superedges.length this.superedges.push(edge) return edge numNodes: -> total = 0 for d in this.domains total += d.nodes.length return total getAttr: (name) -> @_attributes[name]
true
parseIds = (id, onlyLast=false) -> tokens = id.split('::') if onlyLast parseInt(tokens[tokens.length-1].replace(/^n|g|d|e/, '')) else tokens.map((el) -> parseInt(el.replace(/^n|g|d|e/, '')) ) class NeighborsIterator constructor: (@node) -> @directed = true @index = 0 next: => if @directed if @index < @node._outEdges.length return @node._outEdges[@index++].dst else @directed = false @index = 0 if @index < @node._edges.length edge = @node._edges[@index++] if edge.dst == @node return edge.src else return edge.dst throw StopIteration class Node constructor: (@model, @domain, id, @attributes, @_globalId) -> @fqid = parseIds(id) @id = @fqid.last() @_offset = new THREE.Vector3(0, 0, 0) @_position = new THREE.Vector3(0, 0, 0) @_absPosition = new THREE.Vector3(0, 0, 0) @_degree = 0 @_inDegree = 0 @_outDegree = 0 @_selfloops = 0 @_size = 10 @_color = new THREE.Color(0xffffff) @_opacity = 1.0 @_visible = true @_label = @fqid.join(',') @_inEdges = [] @_outEdges = [] @_edges = [] @neighbors = new IteratorFactory(NeighborsIterator, [this]) getAbsoluteID: -> @fqid.join('::') setOffset: (o) -> ### Sets the offset to be applied to the node after its domain-relative position has been defined. ### @_offset = o @updatePosition() setPosition: (p) -> ### Sets the position of the node relative to the absolute coordinates of the domain node. ### @_position.x = p.x @_position.y = p.y @_position.z = p.z @updatePosition() getPosition: -> ### Gets the position of the node relative to the domain. ### return @_position getAbsolutePosition: -> ### Gets the position of the node relative to the origin of the coordinate system, by including any offset due to the domain position. ### return @_absPosition updatePosition: -> ### Updates the absolute position of the object by applying the offset to the position. ### # Use a matrix transformation here to be able to do generic affine # transformations in the future (mainly to include plane rotations # for domains). transformation = new THREE.Matrix4( 1, 0, 0, @_offset.x, 0, 1, 0, @_offset.y, 0, 0, 1, @_offset.z, 0, 0, 0, 1, ) transformed = @_position.clone().applyMatrix4(transformation) @_absPosition.copy(transformed) getSize: -> @_size setSize: (@_size) -> @domain.nodeSizes[@id] = @_size return @ getColor: -> @_color setColor: (color) -> @domain.nodeColors[@id] = @_color = new THREE.Color(color) return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.nodeOpacity[@id] = @_opacity return @ getDegree: -> @_degree getLabel: -> @_label setLabel: (label) -> @_label = "#{label}" return @ getAttr: (key) -> switch key when 'domain' if @domain return @domain.getAttr('domain') else return @attributes['domain'] when 'totdegree' return @_degree + @_inDegree + @_outDegree + 2 * @_selfloops when 'degree' return @_degree when 'selfloops' return @_selfloops when 'indegree' return @_inDegree when 'outdegree' return @_outDegree else return @attributes[key] isVisible: -> @_visible hide: -> @_visible = false @domain.nodeVisibility[@id] = 0.0 return @ show: -> @_visible = true @domain.nodeVisibility[@id] = 1.0 return @ class Edge constructor: (@model, @domain, @id, @src, @dst, @attributes, real=true) -> if attributes._directed? direction = attributes._directed else if domain? direction = domain.edgedefault else direction = model.edgedefault switch direction when 'true', 'directed' @directed = true when 'false', 'undirected' @directed = false else throw "Invalid direction #{direction}" if real if @directed @src._outEdges.push(@) @dst._inEdges.push(@) else @src._edges.push(@) @dst._edges.push(@) @_weight = 1 @_color = new THREE.Color(0x000000) @_opacity = 0.5 @_visible = true if not @domain? @domain = @model if @src == @dst @src._selfloops += 1 else if @directed @src._outDegree += 1 @dst._inDegree += 1 else @src._degree += 1 @dst._degree += 1 other: (node) -> if node == @src return @dst if node == @dst return @src throw 'Node not linked by this edge' getWeight: -> @_weight setWeight: (@_weight) -> @domain.edgeWeights[@_index * 2] = @_weight @domain.edgeWeights[@_index * 2 + 1] = @_weight return @ getColor: -> @_color setColor: (color) -> @domain.edgeColors[@_index * 2] = @_color = new THREE.Color(color) @domain.edgeColors[@_index * 2 + 1] = @_color return @ getOpacity: -> @_opacity setOpacity: (@_opacity) -> @domain.edgeOpacity[@_index * 2] = @_opacity @domain.edgeOpacity[@_index * 2 + 1] = @_opacity return @ isVisible: -> @_visible hide: -> @_visible = false @domain.edgeVisibility[@_index * 2] = 0.0 @domain.edgeVisibility[@_index * 2 + 1] = 0.0 return @ show: -> @_visible = true @domain.edgeVisibility[@_index * 2] = 1.0 @domain.edgeVisibility[@_index * 2 + 1] = 1.0 return @ class Domain extends Node constructor: (@model, id, @attributes) -> super(@model, undefined, id, @attributes) @texture = THREE.ImageUtils.loadTexture('/static/images/node-textures/ball2.png') #uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping @nodes = [] @edges = [] @nodeSizes = [] @nodeOpacity = [] @nodeColors = [] @nodeVisibility = [] @nodePositions = [] @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] rebuildAttributeMappings: => @nodeSizes.length = 0 @nodeColors.length = 0 @nodePositions.length = 0 @nodes.iter((n, i) => @nodeSizes[i] = n.getSize() @nodeOpacity[i] = n.getOpacity() @nodeColors[i] = n.getColor() @nodeVisibility[i] = n.isVisible() @nodePositions[i] = n.getAbsolutePosition() ) @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @edges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) setTexture: (url) -> @texture = THREE.ImageUtils.loadTexture(url) addNode: (el) -> attrs = this.model._getAttributes(el) node = new Node(@model, @, el.attr('id'), attrs) @nodes[node.id] = node node.setOffset(@getAbsolutePosition()) return node addEdge: (el) -> attrs = this.model._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) if src[0] != dst[0] or src[0] != @id throw "Invalid edge definition" src = this.nodes[src[1]] dst = this.nodes[dst[1]] edge = new Edge(this.model, this, el.attr('id'), src, dst, attrs) edge._index = this.edges.length this.edges.push(edge) return edge class GraphModel extends EventDispatcher @fromGraphML: (data) -> xml = $(data) graph = new GraphModel() graph.edgedefault = $('graphml > graph', xml).attr('edgedefault') $('graphml > key', xml).each((i) -> graph.addAttribute($(this)) ) graph._attributes = graph._getAttributes($('graphml > graph', xml)) $('graphml > graph > node', xml).each((i) -> domain = graph.addDomain($(this)) domain.edgedefault = $('> graph', this).attr('edgedefault') $('> graph > node', this).each(-> domain.addNode($(this)) ) $('> graph > edge', this).each(-> domain.addEdge($(this)) ) domain.rebuildAttributeMappings() ) $('graphml > graph > edge', xml).each(-> graph.addEdge($(this)) ) graph.rebuildAttributeMappings() return graph constructor: -> super this.nextNodeId = 0 this.nextEdgeId = 0 this.domains = [] this.superedges = [] this.attributes = { node: {}, graph: {}, edge: {}, all: {}, _by_id: {}, } @edgeWeights = [] @edgeColors = [] @edgeOpacity = [] @edgeVisibility = [] @edgeVertices = [] @nodes = new IteratorFactory(ArrayPropertyIterator, [this.domains, 'nodes']) @edges = new IteratorFactory(FlattenIterator, [[ @superedges, new IteratorFactory(ArrayPropertyIterator, [this.domains, 'edges']) ]]) rebuildAttributeMappings: => @edgeVertices.length = 0 @edgeWeights.length = 0 @edgeColors.length = 0 @edgeOpacity.length = 0 @edgeVisibility.length = 0 @superedges.iter((e, i) => @edgeVertices[i * 2] = e.src.getAbsolutePosition() @edgeVertices[i * 2 + 1] = e.dst.getAbsolutePosition() @edgeWeights[i * 2] = e.getWeight() @edgeWeights[i * 2 + 1] = e.getWeight() @edgeColors[i * 2] = e.getColor() @edgeColors[i * 2 + 1] = e.getColor() @edgeOpacity[i * 2] = e.getOpacity() @edgeOpacity[i * 2 + 1] = e.getOpacity() @edgeVisibility[i * 2] = e.isVisible() @edgeVisibility[i * 2 + 1] = e.isVisible() ) getNodeAttributes: -> $.extend({}, @attributes.node, @attributes.all) _getAttributes: (el) -> data = {} attrs = this.attributes._by_id $('> data', el).each(-> el = $(this) data[attrs[el.attr('key')].name] = el.text() ) return data addAttribute: (el) -> id = el.attr('id') name = el.attr('attr.name') type = el.attr('attr.type') domain = el.attr('for') def = { id: id, name: PI:NAME:<NAME>END_PI, type: type, domain: domain, } this.attributes._by_id[id] = def this.attributes[domain][name] = def addDomain: (el) -> domain = new Domain(this, el.attr('id'), this._getAttributes(el)) this.domains[domain.id] = domain addEdge: (el) -> attrs = this._getAttributes(el) attrs._directed = el.attr('directed') src = parseIds(el.attr('source')) dst = parseIds(el.attr('target')) src = this.domains[src[0]].nodes[src[1]] dst = this.domains[dst[0]].nodes[dst[1]] src._degree += 1 dst._degree += 1 edge = new Edge(this, undefined, el.attr('id'), src, dst, attrs) edge._index = @superedges.length this.superedges.push(edge) return edge numNodes: -> total = 0 for d in this.domains total += d.nodes.length return total getAttr: (name) -> @_attributes[name]
[ { "context": "atal\n# Bootstrap ClojureScript React Native apps\n# Dan Motzenbecker\n# http://oxism.com\n# MIT License\n\nfs = requi", "end": 73, "score": 0.9998711347579956, "start": 57, "tag": "NAME", "value": "Dan Motzenbecker" }, { "context": "->\n allowedTypes = {'real': '...
re-natal.coffee
pvinis/re-natal
0
# Re-Natal # Bootstrap ClojureScript React Native apps # Dan Motzenbecker # http://oxism.com # MIT License fs = require 'fs-extra' fpath = require 'path' net = require 'net' http = require 'http' os = require 'os' child = require 'child_process' cli = require 'commander' chalk = require 'chalk' semver = require 'semver' ckDeps = require 'check-dependencies' pkgJson = require __dirname + '/package.json' nodeVersion = pkgJson.engines.node resources = __dirname + '/resources' validNameRx = /^[A-Z][0-9A-Z]*$/i camelRx = /([a-z])([A-Z])/g projNameRx = /\$PROJECT_NAME\$/g projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g projNameUsRx = /\$PROJECT_NAME_UNDERSCORED\$/g interfaceDepsRx = /\$INTERFACE_DEPS\$/g platformRx = /\$PLATFORM\$/g devHostRx = /\$DEV_HOST\$/g ipAddressRx = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/i figwheelUrlRx = /ws:\/\/[0-9a-zA-Z\.]*:/g appDelegateRx = /http:\/\/[^:]+/g debugHostRx = /host\s+=\s+@".*";/g rnVersion = '0.39.0' rnPackagerPort = 8081 process.title = 're-natal' interfaceConf = 'reagent': cljsDir: "cljs-reagent" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["handlers.cljs", "subs.cljs", "db.cljs"] other: [] deps: ['[reagent "0.5.1" :exclusions [cljsjs/react]]' '[re-frame "0.6.0"]'] shims: ["cljsjs.react"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'reagent6': cljsDir: "cljs-reagent6" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["events.cljs", "subs.cljs", "db.cljs"] other: [["reagent_dom.cljs","reagent/dom.cljs"], ["reagent_dom_server.cljs","reagent/dom/server.cljs"]] deps: ['[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]' '[re-frame "0.8.0"]'] shims: ["cljsjs.react", "cljsjs.react.dom", "cljsjs.react.dom.server"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'om-next': cljsDir: "cljs-om-next" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["state.cljs"] other: [["support.cljs","re_natal/support.cljs"]] deps: ['[org.omcljs/om "1.0.0-alpha41" :exclusions [cljsjs/react cljsjs/react-dom]]'] shims: ["cljsjs.react", "cljsjs.react.dom"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.state)' sampleCommand: '(swap! app-state assoc :app/msg "Hello Native World!")' 'rum': cljsDir: "cljs-rum" sources: ios: ["core.cljs"] android: ["core.cljs"] common: [] other: [["sablono_compiler.clj","sablono/compiler.clj"],["support.cljs","re_natal/support.cljs"]] deps: ['[rum "0.9.1" :exclusions [cljsjs/react cljsjs/react-dom sablono]]'] shims: ["cljsjs.react", "cljsjs.react.dom", "sablono.core"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(swap! app-state assoc :greeting "Hello Clojure in iOS and Android with Rum!")' interfaceNames = Object.keys interfaceConf defaultInterface = 'reagent6' defaultEnvRoots = dev: 'env/dev' prod: 'env/prod' platforms = ['ios', 'android'] log = (s, color = 'green') -> console.log chalk[color] s logErr = (err, color = 'red') -> console.error chalk[color] err process.exit 1 exec = (cmd, keepOutput) -> if keepOutput child.execSync cmd else child.execSync cmd, stdio: 'ignore' ensureExecutableAvailable = (executable) -> if os.platform() == 'win32' try exec "where #{executable}" catch e throw new Error("type: #{executable}: not found") else exec "type #{executable}" ensureOSX = (cb) -> if os.platform() == 'darwin' cb() else logErr 'This command is only available on OSX' readFile = (path) -> fs.readFileSync path, encoding: 'ascii' edit = (path, pairs) -> fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) -> contents.replace rx, replacement , readFile path toUnderscored = (s) -> s.replace(camelRx, '$1_$2').toLowerCase() checkPort = (port, cb) -> sock = net.connect {port}, -> sock.end() http.get "http://localhost:#{port}/status", (res) -> data = '' res.on 'data', (chunk) -> data += chunk res.on 'end', -> cb data.toString() isnt 'packager-status:running' .on 'error', -> cb true .setTimeout 3000 sock.on 'error', -> sock.end() cb false ensureFreePort = (cb) -> checkPort rnPackagerPort, (inUse) -> if inUse logErr " Port #{rnPackagerPort} is currently in use by another process and is needed by the React Native packager. " cb() ensureXcode = (cb) -> try ensureExecutableAvailable 'xcodebuild' cb(); catch {message} if message.match /type.+xcodebuild/i logErr 'Xcode Command Line Tools are required' generateConfig = (interfaceName, projName) -> log 'Creating Re-Natal config' config = name: projName interface: interfaceName androidHost: "localhost" iosHost: "localhost" envRoots: defaultEnvRoots modules: [] imageDirs: ["images"] writeConfig config config writeConfig = (config) -> try fs.writeFileSync '.re-natal', JSON.stringify config, null, 2 catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating .re-natal config file' else message verifyConfig = (config) -> if !config.androidHost? || !config.modules? || !config.imageDirs? || !config.interface? || !config.iosHost? || !config.envRoots? throw new Error 're-natal project needs to be upgraded, please run: re-natal upgrade' config readConfig = (verify = true)-> try config = JSON.parse readFile '.re-natal' if (verify) verifyConfig(config) else config catch {message} logErr \ if message.match /ENOENT/i 'No Re-Natal config was found in this directory (.re-natal)' else if message.match /EACCES/i 'No read permissions for .re-natal' else if message.match /Unexpected/i '.re-natal contains malformed JSON' else message scanImageDir = (dir) -> fnames = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isFile() .filter (path) -> removeExcludeFiles(path) .map (path) -> path.replace /@2x|@3x/i, '' .map (path) -> path.replace new RegExp(".(android|ios)" + fpath.extname(path) + "$", "i"), fpath.extname(path) .filter (v, idx, slf) -> slf.indexOf(v) == idx dirs = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isDirectory() fnames.concat scanImages(dirs) removeExcludeFiles = (file) -> excludedFileNames = [".DS_Store"] res = excludedFileNames.map (ex) -> (file.indexOf ex) == -1 true in res scanImages = (dirs) -> imgs = [] for dir in dirs imgs = imgs.concat(scanImageDir(dir)); imgs resolveAndroidDevHost = (deviceType) -> allowedTypes = {'real': 'localhost', 'avd': '10.0.2.2', 'genymotion': '10.0.3.2'} devHost = allowedTypes[deviceType] if (devHost?) log "Using '#{devHost}' for device type #{deviceType}" devHost else deviceTypeIsIpAddress(deviceType, Object.keys(allowedTypes)) configureDevHostForAndroidDevice = (deviceType) -> try devHost = resolveAndroidDevHost(deviceType) config = readConfig() config.androidHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message resolveIosDevHost = (deviceType) -> if deviceType == 'simulator' log "Using 'localhost' for iOS simulator" 'localhost' else if deviceType == 'real' en0Ip = exec('ipconfig getifaddr en0', true).toString().trim() log "Using IP of interface en0:'#{en0Ip}' for real iOS device" en0Ip else deviceTypeIsIpAddress(deviceType, ['simulator', 'real']) configureDevHostForIosDevice = (deviceType) -> try devHost = resolveIosDevHost(deviceType) config = readConfig() config.iosHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message deviceTypeIsIpAddress = (deviceType, allowedTypes) -> if deviceType.match(ipAddressRx) log "Using development host IP: '#{deviceType}'" deviceType else log("Value '#{deviceType}' is not a valid IP address, still configured it as development host. Did you mean one of: [#{allowedTypes}] ?", 'yellow') deviceType copyDevEnvironmentFiles = (interfaceName, projNameHyph, projName, devEnvRoot, devHost) -> fs.mkdirpSync "#{devEnvRoot}/env/ios" fs.mkdirpSync "#{devEnvRoot}/env/android" userNsPath = "#{devEnvRoot}/user.clj" fs.copySync("#{resources}/user.clj", userNsPath) mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainIosDevPath) edit mainIosDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"], [devHostRx, devHost] ] fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainAndroidDevPath) edit mainAndroidDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"], [devHostRx, devHost]] copyProdEnvironmentFiles = (interfaceName, projNameHyph, projName, prodEnvRoot) -> fs.mkdirpSync "#{prodEnvRoot}/env/ios" fs.mkdirpSync "#{prodEnvRoot}/env/android" mainIosProdPath = "#{prodEnvRoot}/env/ios/main.cljs" mainAndroidProdPath = "#{prodEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainIosProdPath) edit mainIosProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"]] fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainAndroidProdPath) edit mainAndroidProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"]] copyFigwheelBridge = (projNameUs) -> fs.copySync("#{resources}/figwheel-bridge.js", "./figwheel-bridge.js") edit "figwheel-bridge.js", [[projNameUsRx, projNameUs]] updateGitIgnore = () -> fs.appendFileSync(".gitignore", "\n# Generated by re-natal\n#\nindex.android.js\nindex.ios.js\ntarget/\n") fs.appendFileSync(".gitignore", "\n# Figwheel\n#\nfigwheel_server.log") patchReactNativePackager = () -> ckDeps.sync {install: true, verbose: false} log "Patching react-native packager to serve *.map files" edit "node_modules/react-native/packager/react-packager/src/Server/index.js", [[/match.*\.map\$\/\)/m, "match(/index\\..*\\.map$/)"]] shimCljsNamespace = (ns) -> filePath = "src/" + ns.replace(/\./g, "/") + ".cljs" fs.mkdirpSync fpath.dirname(filePath) fs.writeFileSync(filePath, "(ns #{ns})") copySrcFiles = (interfaceName, projName, projNameUs, projNameHyph) -> cljsDir = interfaceConf[interfaceName].cljsDir fileNames = interfaceConf[interfaceName].sources.common; for fileName in fileNames path = "src/#{projNameUs}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName]] for platform in platforms fs.mkdirSync "src/#{projNameUs}/#{platform}" fileNames = interfaceConf[interfaceName].sources[platform] for fileName in fileNames path = "src/#{projNameUs}/#{platform}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, platform]] otherFiles = interfaceConf[interfaceName].sources.other; for cpFile in otherFiles from = "#{resources}/#{cljsDir}/#{cpFile[0]}" to = "src/#{cpFile[1]}" fs.copySync(from, to) shims = fileNames = interfaceConf[interfaceName].shims; for namespace in shims shimCljsNamespace(namespace) copyProjectClj = (interfaceName, projNameHyph) -> fs.copySync("#{resources}/project.clj", "project.clj") deps = interfaceConf[interfaceName].deps.join("\n") edit 'project.clj', [[projNameHyphRx, projNameHyph], [interfaceDepsRx, deps]] init = (interfaceName, projName) -> if projName.toLowerCase() is 'react' or !projName.match validNameRx logErr 'Invalid project name. Use an alphanumeric CamelCase name.' projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName try log "Creating #{projName}", 'bgMagenta' log '\u2615 Grab a coffee! Downloading deps might take a while...', 'yellow' if fs.existsSync projNameHyph throw new Error "Directory #{projNameHyph} already exists" ensureExecutableAvailable 'lein' log 'Creating Leiningen project' exec "lein new #{projNameHyph}" log 'Updating Leiningen project' process.chdir projNameHyph fs.removeSync "resources" corePath = "src/#{projNameUs}/core.clj" fs.unlinkSync corePath copyProjectClj(interfaceName, projNameHyph) copySrcFiles(interfaceName, projName, projNameUs, projNameHyph) copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.prod) fs.copySync("#{resources}/images", "./images") log 'Creating React Native skeleton.' fs.writeFileSync 'package.json', JSON.stringify name: projName version: '0.0.1' private: true scripts: start: 'node_modules/react-native/packager/packager.sh --nonPersistent' dependencies: 'react-native': rnVersion # Fixes issue with packager 'TimeoutError: transforming ... took longer than 301 seconds.' 'babel-plugin-transform-es2015-block-scoping': '6.15.0' , null, 2 exec 'npm i' fs.unlinkSync '.gitignore' exec "node -e \"require('react-native/local-cli/cli').init('.', '#{projName}')\" " updateGitIgnore() generateConfig(interfaceName, projName) copyFigwheelBridge(projNameUs) log 'Compiling ClojureScript' exec 'lein prod-build' log '' log 'To get started with your new app, first cd into its directory:', 'yellow' log "cd #{projNameHyph}", 'inverse' log '' log 'Run iOS app:' , 'yellow' log 'react-native run-ios > /dev/null', 'inverse' log '' log 'To use figwheel type:' , 'yellow' log 're-natal use-figwheel', 'inverse' log 'lein figwheel ios', 'inverse' log '' log 'Reload the app in simulator (\u2318 + R)' log '' log 'At the REPL prompt type this:', 'yellow' log interfaceConf[interfaceName].sampleCommandNs.replace(projNameHyphRx, projNameHyph), 'inverse' log '' log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow' log '' log 'Try this command as an example:', 'yellow' log interfaceConf[interfaceName].sampleCommand, 'inverse' log '' log '✔ Done', 'bgMagenta' log '' catch {message} logErr \ if message.match /type.+lein/i 'Leiningen is required (http://leiningen.org)' else if message.match /npm/i "npm install failed. This may be a network issue. Check #{projNameHyph}/npm-debug.log for details." else message openXcode = (name) -> try exec "open ios/#{name}.xcodeproj" catch {message} logErr \ if message.match /ENOENT/i """ Cannot find #{name}.xcodeproj in ios. Run this command from your project's root directory. """ else if message.match /EACCES/i "Invalid permissions for opening #{name}.xcodeproj in ios" else message generateRequireModulesCode = (modules) -> jsCode = "var modules={'react-native': require('react-native'), 'react': require('react')};" for m in modules jsCode += "modules['#{m}']=require('#{m}');"; jsCode += '\n' updateFigwheelUrls = (devEnvRoot, androidHost, iosHost) -> mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" edit mainAndroidDevPath, [[figwheelUrlRx, "ws://#{androidHost}:"]] mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" edit mainIosDevPath, [[figwheelUrlRx, "ws://#{iosHost}:"]] # Current RN version (0.29.2) has no host in AppDelegate.m maybe docs are outdated? updateIosAppDelegate = (projName, iosHost) -> appDelegatePath = "ios/#{projName}/AppDelegate.m" edit appDelegatePath, [[appDelegateRx, "http://#{iosHost}"]] updateIosRCTWebSocketExecutor = (iosHost) -> RCTWebSocketExecutorPath = "node_modules/react-native/Libraries/WebSocket/RCTWebSocketExecutor.m" edit RCTWebSocketExecutorPath, [[debugHostRx, "host = @\"#{iosHost}\";"]] platformModulesAndImages = (config, platform) -> images = scanImages(config.imageDirs).map (fname) -> './' + fname; modulesAndImages = config.modules.concat images; if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {}; if typeof config.modulesPlatform is 'undefined' or typeof config.modulesPlatform[platform] is 'undefined' modulesAndImages else modulesAndImages.concat(config.modulesPlatform[platform]) generateDevScripts = () -> try config = readConfig() projName = config.name devEnvRoot = config.envRoots.dev depState = ckDeps.sync {install: false, verbose: false} if (!depState.depsWereOk) throw new Error "Missing dependencies, please run: re-natal deps" log 'Cleaning...' exec 'lein clean' androidDevHost = config.androidHost iosDevHost = config.iosHost devHost = {'android' : androidDevHost, 'ios' : iosDevHost} for platform in platforms moduleMap = generateRequireModulesCode(platformModulesAndImages(config, platform)) fs.writeFileSync "index.#{platform}.js", "#{moduleMap}require('figwheel-bridge').withModules(modules).start('#{projName}','#{platform}','#{devHost[platform]}');" log "index.#{platform}.js was regenerated" #updateIosAppDelegate(projName, iosDevHost) updateIosRCTWebSocketExecutor(iosDevHost) log "Host in RCTWebSocketExecutor.m was updated" updateFigwheelUrls(devEnvRoot, androidDevHost, iosDevHost) log 'Dev server host for iOS: ' + iosDevHost log 'Dev server host for Android: ' + androidDevHost catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating development scripts' else message doUpgrade = (config) -> projName = config.name projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName unless config.interface config.interface = defaultInterface unless config.modules config.modules = [] unless config.imageDirs config.imageDirs = ["images"] unless config.androidHost config.androidHost = "localhost" unless config.iosHost config.iosHost = "localhost" unless config.envRoots config.envRoots = defaultEnvRoots writeConfig(config) log 'upgraded .re-natal' interfaceName = config.interface envRoots = config.envRoots copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.prod) log "upgraded files in #{envRoots.dev} and #{envRoots.prod} " copyFigwheelBridge(projNameUs) log 'upgraded figwheel-bridge.js' log('To upgrade React Native version please follow the official guide in https://facebook.github.io/react-native/docs/upgrading.html', 'yellow') useComponent = (name, platform) -> try config = readConfig() if typeof platform isnt 'string' config.modules.push name log "Component '#{name}' is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else if platforms.indexOf(platform) > -1 if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {} if typeof config.modulesPlatform[platform] is 'undefined' config.modulesPlatform[platform] = [] config.modulesPlatform[platform].push name log "Component '#{name}' (#{platform}-only) is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else throw new Error("unsupported platform: #{platform}") writeConfig(config) catch {message} logErr message cli._name = 're-natal' cli.version pkgJson.version cli.command 'init <name>' .description 'create a new ClojureScript React Native project' .option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface', defaultInterface .action (name, cmd) -> if typeof name isnt 'string' logErr ''' re-natal init requires a project name as the first argument. e.g. re-natal init HelloWorld ''' unless interfaceConf[cmd.interface] logErr "Unsupported React interface: #{cmd.interface}, one of [#{interfaceNames}] was expected." ensureFreePort -> init(cmd.interface, name) cli.command 'upgrade' .description 'upgrades project files to current installed version of re-natal (the upgrade of re-natal itself is done via npm)' .action -> doUpgrade readConfig(false) cli.command 'xcode' .description 'open Xcode project' .action -> ensureOSX -> ensureXcode -> openXcode readConfig().name cli.command 'deps' .description 'install all dependencies for the project' .action -> ckDeps.sync {install: true, verbose: true} cli.command 'use-figwheel' .description 'generate index.ios.js and index.android.js for development with figwheel' .action () -> generateDevScripts() cli.command 'use-android-device <type>' .description 'sets up the host for android device type: \'real\' - localhost, \'avd\' - 10.0.2.2, \'genymotion\' - 10.0.3.2, IP' .action (type) -> configureDevHostForAndroidDevice type cli.command 'use-ios-device <type>' .description 'sets up the host for ios device type: \'simulator\' - localhost, \'real\' - auto detect IP on eth0, IP' .action (type) -> configureDevHostForIosDevice type cli.command 'use-component <name> [<platform>]' .description 'configures a custom component to work with figwheel. name is the value you pass to (js/require) function.' .action (name, platform) -> useComponent(name, platform) cli.command 'enable-source-maps' .description 'patches RN packager to server *.map files from filesystem, so that chrome can download them.' .action () -> patchReactNativePackager() cli.command 'copy-figwheel-bridge' .description 'copy figwheel-bridge.js into project' .action () -> copyFigwheelBridge(readConfig(false).name) log "Copied figwheel-bridge.js" cli.on '*', (command) -> logErr "unknown command #{command[0]}. See re-natal --help for valid commands" unless semver.satisfies process.version[1...], nodeVersion logErr """ Re-Natal requires Node.js version #{nodeVersion} You have #{process.version[1...]} """ if process.argv.length <= 2 cli.outputHelp() else cli.parse process.argv
122383
# Re-Natal # Bootstrap ClojureScript React Native apps # <NAME> # http://oxism.com # MIT License fs = require 'fs-extra' fpath = require 'path' net = require 'net' http = require 'http' os = require 'os' child = require 'child_process' cli = require 'commander' chalk = require 'chalk' semver = require 'semver' ckDeps = require 'check-dependencies' pkgJson = require __dirname + '/package.json' nodeVersion = pkgJson.engines.node resources = __dirname + '/resources' validNameRx = /^[A-Z][0-9A-Z]*$/i camelRx = /([a-z])([A-Z])/g projNameRx = /\$PROJECT_NAME\$/g projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g projNameUsRx = /\$PROJECT_NAME_UNDERSCORED\$/g interfaceDepsRx = /\$INTERFACE_DEPS\$/g platformRx = /\$PLATFORM\$/g devHostRx = /\$DEV_HOST\$/g ipAddressRx = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/i figwheelUrlRx = /ws:\/\/[0-9a-zA-Z\.]*:/g appDelegateRx = /http:\/\/[^:]+/g debugHostRx = /host\s+=\s+@".*";/g rnVersion = '0.39.0' rnPackagerPort = 8081 process.title = 're-natal' interfaceConf = 'reagent': cljsDir: "cljs-reagent" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["handlers.cljs", "subs.cljs", "db.cljs"] other: [] deps: ['[reagent "0.5.1" :exclusions [cljsjs/react]]' '[re-frame "0.6.0"]'] shims: ["cljsjs.react"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'reagent6': cljsDir: "cljs-reagent6" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["events.cljs", "subs.cljs", "db.cljs"] other: [["reagent_dom.cljs","reagent/dom.cljs"], ["reagent_dom_server.cljs","reagent/dom/server.cljs"]] deps: ['[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]' '[re-frame "0.8.0"]'] shims: ["cljsjs.react", "cljsjs.react.dom", "cljsjs.react.dom.server"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'om-next': cljsDir: "cljs-om-next" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["state.cljs"] other: [["support.cljs","re_natal/support.cljs"]] deps: ['[org.omcljs/om "1.0.0-alpha41" :exclusions [cljsjs/react cljsjs/react-dom]]'] shims: ["cljsjs.react", "cljsjs.react.dom"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.state)' sampleCommand: '(swap! app-state assoc :app/msg "Hello Native World!")' 'rum': cljsDir: "cljs-rum" sources: ios: ["core.cljs"] android: ["core.cljs"] common: [] other: [["sablono_compiler.clj","sablono/compiler.clj"],["support.cljs","re_natal/support.cljs"]] deps: ['[rum "0.9.1" :exclusions [cljsjs/react cljsjs/react-dom sablono]]'] shims: ["cljsjs.react", "cljsjs.react.dom", "sablono.core"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(swap! app-state assoc :greeting "Hello Clojure in iOS and Android with Rum!")' interfaceNames = Object.keys interfaceConf defaultInterface = 'reagent6' defaultEnvRoots = dev: 'env/dev' prod: 'env/prod' platforms = ['ios', 'android'] log = (s, color = 'green') -> console.log chalk[color] s logErr = (err, color = 'red') -> console.error chalk[color] err process.exit 1 exec = (cmd, keepOutput) -> if keepOutput child.execSync cmd else child.execSync cmd, stdio: 'ignore' ensureExecutableAvailable = (executable) -> if os.platform() == 'win32' try exec "where #{executable}" catch e throw new Error("type: #{executable}: not found") else exec "type #{executable}" ensureOSX = (cb) -> if os.platform() == 'darwin' cb() else logErr 'This command is only available on OSX' readFile = (path) -> fs.readFileSync path, encoding: 'ascii' edit = (path, pairs) -> fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) -> contents.replace rx, replacement , readFile path toUnderscored = (s) -> s.replace(camelRx, '$1_$2').toLowerCase() checkPort = (port, cb) -> sock = net.connect {port}, -> sock.end() http.get "http://localhost:#{port}/status", (res) -> data = '' res.on 'data', (chunk) -> data += chunk res.on 'end', -> cb data.toString() isnt 'packager-status:running' .on 'error', -> cb true .setTimeout 3000 sock.on 'error', -> sock.end() cb false ensureFreePort = (cb) -> checkPort rnPackagerPort, (inUse) -> if inUse logErr " Port #{rnPackagerPort} is currently in use by another process and is needed by the React Native packager. " cb() ensureXcode = (cb) -> try ensureExecutableAvailable 'xcodebuild' cb(); catch {message} if message.match /type.+xcodebuild/i logErr 'Xcode Command Line Tools are required' generateConfig = (interfaceName, projName) -> log 'Creating Re-Natal config' config = name: projName interface: interfaceName androidHost: "localhost" iosHost: "localhost" envRoots: defaultEnvRoots modules: [] imageDirs: ["images"] writeConfig config config writeConfig = (config) -> try fs.writeFileSync '.re-natal', JSON.stringify config, null, 2 catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating .re-natal config file' else message verifyConfig = (config) -> if !config.androidHost? || !config.modules? || !config.imageDirs? || !config.interface? || !config.iosHost? || !config.envRoots? throw new Error 're-natal project needs to be upgraded, please run: re-natal upgrade' config readConfig = (verify = true)-> try config = JSON.parse readFile '.re-natal' if (verify) verifyConfig(config) else config catch {message} logErr \ if message.match /ENOENT/i 'No Re-Natal config was found in this directory (.re-natal)' else if message.match /EACCES/i 'No read permissions for .re-natal' else if message.match /Unexpected/i '.re-natal contains malformed JSON' else message scanImageDir = (dir) -> fnames = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isFile() .filter (path) -> removeExcludeFiles(path) .map (path) -> path.replace /@2x|@3x/i, '' .map (path) -> path.replace new RegExp(".(android|ios)" + fpath.extname(path) + "$", "i"), fpath.extname(path) .filter (v, idx, slf) -> slf.indexOf(v) == idx dirs = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isDirectory() fnames.concat scanImages(dirs) removeExcludeFiles = (file) -> excludedFileNames = [".DS_Store"] res = excludedFileNames.map (ex) -> (file.indexOf ex) == -1 true in res scanImages = (dirs) -> imgs = [] for dir in dirs imgs = imgs.concat(scanImageDir(dir)); imgs resolveAndroidDevHost = (deviceType) -> allowedTypes = {'real': 'localhost', 'avd': '10.0.2.2', 'genymotion': '10.0.3.2'} devHost = allowedTypes[deviceType] if (devHost?) log "Using '#{devHost}' for device type #{deviceType}" devHost else deviceTypeIsIpAddress(deviceType, Object.keys(allowedTypes)) configureDevHostForAndroidDevice = (deviceType) -> try devHost = resolveAndroidDevHost(deviceType) config = readConfig() config.androidHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message resolveIosDevHost = (deviceType) -> if deviceType == 'simulator' log "Using 'localhost' for iOS simulator" 'localhost' else if deviceType == 'real' en0Ip = exec('ipconfig getifaddr en0', true).toString().trim() log "Using IP of interface en0:'#{en0Ip}' for real iOS device" en0Ip else deviceTypeIsIpAddress(deviceType, ['simulator', 'real']) configureDevHostForIosDevice = (deviceType) -> try devHost = resolveIosDevHost(deviceType) config = readConfig() config.iosHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message deviceTypeIsIpAddress = (deviceType, allowedTypes) -> if deviceType.match(ipAddressRx) log "Using development host IP: '#{deviceType}'" deviceType else log("Value '#{deviceType}' is not a valid IP address, still configured it as development host. Did you mean one of: [#{allowedTypes}] ?", 'yellow') deviceType copyDevEnvironmentFiles = (interfaceName, projNameHyph, projName, devEnvRoot, devHost) -> fs.mkdirpSync "#{devEnvRoot}/env/ios" fs.mkdirpSync "#{devEnvRoot}/env/android" userNsPath = "#{devEnvRoot}/user.clj" fs.copySync("#{resources}/user.clj", userNsPath) mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainIosDevPath) edit mainIosDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"], [devHostRx, devHost] ] fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainAndroidDevPath) edit mainAndroidDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"], [devHostRx, devHost]] copyProdEnvironmentFiles = (interfaceName, projNameHyph, projName, prodEnvRoot) -> fs.mkdirpSync "#{prodEnvRoot}/env/ios" fs.mkdirpSync "#{prodEnvRoot}/env/android" mainIosProdPath = "#{prodEnvRoot}/env/ios/main.cljs" mainAndroidProdPath = "#{prodEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainIosProdPath) edit mainIosProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"]] fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainAndroidProdPath) edit mainAndroidProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"]] copyFigwheelBridge = (projNameUs) -> fs.copySync("#{resources}/figwheel-bridge.js", "./figwheel-bridge.js") edit "figwheel-bridge.js", [[projNameUsRx, projNameUs]] updateGitIgnore = () -> fs.appendFileSync(".gitignore", "\n# Generated by re-natal\n#\nindex.android.js\nindex.ios.js\ntarget/\n") fs.appendFileSync(".gitignore", "\n# Figwheel\n#\nfigwheel_server.log") patchReactNativePackager = () -> ckDeps.sync {install: true, verbose: false} log "Patching react-native packager to serve *.map files" edit "node_modules/react-native/packager/react-packager/src/Server/index.js", [[/match.*\.map\$\/\)/m, "match(/index\\..*\\.map$/)"]] shimCljsNamespace = (ns) -> filePath = "src/" + ns.replace(/\./g, "/") + ".cljs" fs.mkdirpSync fpath.dirname(filePath) fs.writeFileSync(filePath, "(ns #{ns})") copySrcFiles = (interfaceName, projName, projNameUs, projNameHyph) -> cljsDir = interfaceConf[interfaceName].cljsDir fileNames = interfaceConf[interfaceName].sources.common; for fileName in fileNames path = "src/#{projNameUs}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName]] for platform in platforms fs.mkdirSync "src/#{projNameUs}/#{platform}" fileNames = interfaceConf[interfaceName].sources[platform] for fileName in fileNames path = "src/#{projNameUs}/#{platform}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, platform]] otherFiles = interfaceConf[interfaceName].sources.other; for cpFile in otherFiles from = "#{resources}/#{cljsDir}/#{cpFile[0]}" to = "src/#{cpFile[1]}" fs.copySync(from, to) shims = fileNames = interfaceConf[interfaceName].shims; for namespace in shims shimCljsNamespace(namespace) copyProjectClj = (interfaceName, projNameHyph) -> fs.copySync("#{resources}/project.clj", "project.clj") deps = interfaceConf[interfaceName].deps.join("\n") edit 'project.clj', [[projNameHyphRx, projNameHyph], [interfaceDepsRx, deps]] init = (interfaceName, projName) -> if projName.toLowerCase() is 'react' or !projName.match validNameRx logErr 'Invalid project name. Use an alphanumeric CamelCase name.' projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName try log "Creating #{projName}", 'bgMagenta' log '\u2615 Grab a coffee! Downloading deps might take a while...', 'yellow' if fs.existsSync projNameHyph throw new Error "Directory #{projNameHyph} already exists" ensureExecutableAvailable 'lein' log 'Creating Leiningen project' exec "lein new #{projNameHyph}" log 'Updating Leiningen project' process.chdir projNameHyph fs.removeSync "resources" corePath = "src/#{projNameUs}/core.clj" fs.unlinkSync corePath copyProjectClj(interfaceName, projNameHyph) copySrcFiles(interfaceName, projName, projNameUs, projNameHyph) copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.prod) fs.copySync("#{resources}/images", "./images") log 'Creating React Native skeleton.' fs.writeFileSync 'package.json', JSON.stringify name: projName version: '0.0.1' private: true scripts: start: 'node_modules/react-native/packager/packager.sh --nonPersistent' dependencies: 'react-native': rnVersion # Fixes issue with packager 'TimeoutError: transforming ... took longer than 301 seconds.' 'babel-plugin-transform-es2015-block-scoping': '6.15.0' , null, 2 exec 'npm i' fs.unlinkSync '.gitignore' exec "node -e \"require('react-native/local-cli/cli').init('.', '#{projName}')\" " updateGitIgnore() generateConfig(interfaceName, projName) copyFigwheelBridge(projNameUs) log 'Compiling ClojureScript' exec 'lein prod-build' log '' log 'To get started with your new app, first cd into its directory:', 'yellow' log "cd #{projNameHyph}", 'inverse' log '' log 'Run iOS app:' , 'yellow' log 'react-native run-ios > /dev/null', 'inverse' log '' log 'To use figwheel type:' , 'yellow' log 're-natal use-figwheel', 'inverse' log 'lein figwheel ios', 'inverse' log '' log 'Reload the app in simulator (\u2318 + R)' log '' log 'At the REPL prompt type this:', 'yellow' log interfaceConf[interfaceName].sampleCommandNs.replace(projNameHyphRx, projNameHyph), 'inverse' log '' log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow' log '' log 'Try this command as an example:', 'yellow' log interfaceConf[interfaceName].sampleCommand, 'inverse' log '' log '✔ Done', 'bgMagenta' log '' catch {message} logErr \ if message.match /type.+lein/i 'Leiningen is required (http://leiningen.org)' else if message.match /npm/i "npm install failed. This may be a network issue. Check #{projNameHyph}/npm-debug.log for details." else message openXcode = (name) -> try exec "open ios/#{name}.xcodeproj" catch {message} logErr \ if message.match /ENOENT/i """ Cannot find #{name}.xcodeproj in ios. Run this command from your project's root directory. """ else if message.match /EACCES/i "Invalid permissions for opening #{name}.xcodeproj in ios" else message generateRequireModulesCode = (modules) -> jsCode = "var modules={'react-native': require('react-native'), 'react': require('react')};" for m in modules jsCode += "modules['#{m}']=require('#{m}');"; jsCode += '\n' updateFigwheelUrls = (devEnvRoot, androidHost, iosHost) -> mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" edit mainAndroidDevPath, [[figwheelUrlRx, "ws://#{androidHost}:"]] mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" edit mainIosDevPath, [[figwheelUrlRx, "ws://#{iosHost}:"]] # Current RN version (0.29.2) has no host in AppDelegate.m maybe docs are outdated? updateIosAppDelegate = (projName, iosHost) -> appDelegatePath = "ios/#{projName}/AppDelegate.m" edit appDelegatePath, [[appDelegateRx, "http://#{iosHost}"]] updateIosRCTWebSocketExecutor = (iosHost) -> RCTWebSocketExecutorPath = "node_modules/react-native/Libraries/WebSocket/RCTWebSocketExecutor.m" edit RCTWebSocketExecutorPath, [[debugHostRx, "host = @\"#{iosHost}\";"]] platformModulesAndImages = (config, platform) -> images = scanImages(config.imageDirs).map (fname) -> './' + fname; modulesAndImages = config.modules.concat images; if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {}; if typeof config.modulesPlatform is 'undefined' or typeof config.modulesPlatform[platform] is 'undefined' modulesAndImages else modulesAndImages.concat(config.modulesPlatform[platform]) generateDevScripts = () -> try config = readConfig() projName = config.name devEnvRoot = config.envRoots.dev depState = ckDeps.sync {install: false, verbose: false} if (!depState.depsWereOk) throw new Error "Missing dependencies, please run: re-natal deps" log 'Cleaning...' exec 'lein clean' androidDevHost = config.androidHost iosDevHost = config.iosHost devHost = {'android' : androidDevHost, 'ios' : iosDevHost} for platform in platforms moduleMap = generateRequireModulesCode(platformModulesAndImages(config, platform)) fs.writeFileSync "index.#{platform}.js", "#{moduleMap}require('figwheel-bridge').withModules(modules).start('#{projName}','#{platform}','#{devHost[platform]}');" log "index.#{platform}.js was regenerated" #updateIosAppDelegate(projName, iosDevHost) updateIosRCTWebSocketExecutor(iosDevHost) log "Host in RCTWebSocketExecutor.m was updated" updateFigwheelUrls(devEnvRoot, androidDevHost, iosDevHost) log 'Dev server host for iOS: ' + iosDevHost log 'Dev server host for Android: ' + androidDevHost catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating development scripts' else message doUpgrade = (config) -> projName = config.name projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName unless config.interface config.interface = defaultInterface unless config.modules config.modules = [] unless config.imageDirs config.imageDirs = ["images"] unless config.androidHost config.androidHost = "localhost" unless config.iosHost config.iosHost = "localhost" unless config.envRoots config.envRoots = defaultEnvRoots writeConfig(config) log 'upgraded .re-natal' interfaceName = config.interface envRoots = config.envRoots copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.prod) log "upgraded files in #{envRoots.dev} and #{envRoots.prod} " copyFigwheelBridge(projNameUs) log 'upgraded figwheel-bridge.js' log('To upgrade React Native version please follow the official guide in https://facebook.github.io/react-native/docs/upgrading.html', 'yellow') useComponent = (name, platform) -> try config = readConfig() if typeof platform isnt 'string' config.modules.push name log "Component '#{name}' is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else if platforms.indexOf(platform) > -1 if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {} if typeof config.modulesPlatform[platform] is 'undefined' config.modulesPlatform[platform] = [] config.modulesPlatform[platform].push name log "Component '#{name}' (#{platform}-only) is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else throw new Error("unsupported platform: #{platform}") writeConfig(config) catch {message} logErr message cli._name = 're-natal' cli.version pkgJson.version cli.command 'init <name>' .description 'create a new ClojureScript React Native project' .option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface', defaultInterface .action (name, cmd) -> if typeof name isnt 'string' logErr ''' re-natal init requires a project name as the first argument. e.g. re-natal init HelloWorld ''' unless interfaceConf[cmd.interface] logErr "Unsupported React interface: #{cmd.interface}, one of [#{interfaceNames}] was expected." ensureFreePort -> init(cmd.interface, name) cli.command 'upgrade' .description 'upgrades project files to current installed version of re-natal (the upgrade of re-natal itself is done via npm)' .action -> doUpgrade readConfig(false) cli.command 'xcode' .description 'open Xcode project' .action -> ensureOSX -> ensureXcode -> openXcode readConfig().name cli.command 'deps' .description 'install all dependencies for the project' .action -> ckDeps.sync {install: true, verbose: true} cli.command 'use-figwheel' .description 'generate index.ios.js and index.android.js for development with figwheel' .action () -> generateDevScripts() cli.command 'use-android-device <type>' .description 'sets up the host for android device type: \'real\' - localhost, \'avd\' - 10.0.2.2, \'genymotion\' - 10.0.3.2, IP' .action (type) -> configureDevHostForAndroidDevice type cli.command 'use-ios-device <type>' .description 'sets up the host for ios device type: \'simulator\' - localhost, \'real\' - auto detect IP on eth0, IP' .action (type) -> configureDevHostForIosDevice type cli.command 'use-component <name> [<platform>]' .description 'configures a custom component to work with figwheel. name is the value you pass to (js/require) function.' .action (name, platform) -> useComponent(name, platform) cli.command 'enable-source-maps' .description 'patches RN packager to server *.map files from filesystem, so that chrome can download them.' .action () -> patchReactNativePackager() cli.command 'copy-figwheel-bridge' .description 'copy figwheel-bridge.js into project' .action () -> copyFigwheelBridge(readConfig(false).name) log "Copied figwheel-bridge.js" cli.on '*', (command) -> logErr "unknown command #{command[0]}. See re-natal --help for valid commands" unless semver.satisfies process.version[1...], nodeVersion logErr """ Re-Natal requires Node.js version #{nodeVersion} You have #{process.version[1...]} """ if process.argv.length <= 2 cli.outputHelp() else cli.parse process.argv
true
# Re-Natal # Bootstrap ClojureScript React Native apps # PI:NAME:<NAME>END_PI # http://oxism.com # MIT License fs = require 'fs-extra' fpath = require 'path' net = require 'net' http = require 'http' os = require 'os' child = require 'child_process' cli = require 'commander' chalk = require 'chalk' semver = require 'semver' ckDeps = require 'check-dependencies' pkgJson = require __dirname + '/package.json' nodeVersion = pkgJson.engines.node resources = __dirname + '/resources' validNameRx = /^[A-Z][0-9A-Z]*$/i camelRx = /([a-z])([A-Z])/g projNameRx = /\$PROJECT_NAME\$/g projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g projNameUsRx = /\$PROJECT_NAME_UNDERSCORED\$/g interfaceDepsRx = /\$INTERFACE_DEPS\$/g platformRx = /\$PLATFORM\$/g devHostRx = /\$DEV_HOST\$/g ipAddressRx = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/i figwheelUrlRx = /ws:\/\/[0-9a-zA-Z\.]*:/g appDelegateRx = /http:\/\/[^:]+/g debugHostRx = /host\s+=\s+@".*";/g rnVersion = '0.39.0' rnPackagerPort = 8081 process.title = 're-natal' interfaceConf = 'reagent': cljsDir: "cljs-reagent" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["handlers.cljs", "subs.cljs", "db.cljs"] other: [] deps: ['[reagent "0.5.1" :exclusions [cljsjs/react]]' '[re-frame "0.6.0"]'] shims: ["cljsjs.react"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'reagent6': cljsDir: "cljs-reagent6" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["events.cljs", "subs.cljs", "db.cljs"] other: [["reagent_dom.cljs","reagent/dom.cljs"], ["reagent_dom_server.cljs","reagent/dom/server.cljs"]] deps: ['[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]' '[re-frame "0.8.0"]'] shims: ["cljsjs.react", "cljsjs.react.dom", "cljsjs.react.dom.server"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(dispatch [:set-greeting "Hello Native World!"])' 'om-next': cljsDir: "cljs-om-next" sources: ios: ["core.cljs"] android: ["core.cljs"] common: ["state.cljs"] other: [["support.cljs","re_natal/support.cljs"]] deps: ['[org.omcljs/om "1.0.0-alpha41" :exclusions [cljsjs/react cljsjs/react-dom]]'] shims: ["cljsjs.react", "cljsjs.react.dom"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.state)' sampleCommand: '(swap! app-state assoc :app/msg "Hello Native World!")' 'rum': cljsDir: "cljs-rum" sources: ios: ["core.cljs"] android: ["core.cljs"] common: [] other: [["sablono_compiler.clj","sablono/compiler.clj"],["support.cljs","re_natal/support.cljs"]] deps: ['[rum "0.9.1" :exclusions [cljsjs/react cljsjs/react-dom sablono]]'] shims: ["cljsjs.react", "cljsjs.react.dom", "sablono.core"] sampleCommandNs: '(in-ns \'$PROJECT_NAME_HYPHENATED$.ios.core)' sampleCommand: '(swap! app-state assoc :greeting "Hello Clojure in iOS and Android with Rum!")' interfaceNames = Object.keys interfaceConf defaultInterface = 'reagent6' defaultEnvRoots = dev: 'env/dev' prod: 'env/prod' platforms = ['ios', 'android'] log = (s, color = 'green') -> console.log chalk[color] s logErr = (err, color = 'red') -> console.error chalk[color] err process.exit 1 exec = (cmd, keepOutput) -> if keepOutput child.execSync cmd else child.execSync cmd, stdio: 'ignore' ensureExecutableAvailable = (executable) -> if os.platform() == 'win32' try exec "where #{executable}" catch e throw new Error("type: #{executable}: not found") else exec "type #{executable}" ensureOSX = (cb) -> if os.platform() == 'darwin' cb() else logErr 'This command is only available on OSX' readFile = (path) -> fs.readFileSync path, encoding: 'ascii' edit = (path, pairs) -> fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) -> contents.replace rx, replacement , readFile path toUnderscored = (s) -> s.replace(camelRx, '$1_$2').toLowerCase() checkPort = (port, cb) -> sock = net.connect {port}, -> sock.end() http.get "http://localhost:#{port}/status", (res) -> data = '' res.on 'data', (chunk) -> data += chunk res.on 'end', -> cb data.toString() isnt 'packager-status:running' .on 'error', -> cb true .setTimeout 3000 sock.on 'error', -> sock.end() cb false ensureFreePort = (cb) -> checkPort rnPackagerPort, (inUse) -> if inUse logErr " Port #{rnPackagerPort} is currently in use by another process and is needed by the React Native packager. " cb() ensureXcode = (cb) -> try ensureExecutableAvailable 'xcodebuild' cb(); catch {message} if message.match /type.+xcodebuild/i logErr 'Xcode Command Line Tools are required' generateConfig = (interfaceName, projName) -> log 'Creating Re-Natal config' config = name: projName interface: interfaceName androidHost: "localhost" iosHost: "localhost" envRoots: defaultEnvRoots modules: [] imageDirs: ["images"] writeConfig config config writeConfig = (config) -> try fs.writeFileSync '.re-natal', JSON.stringify config, null, 2 catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating .re-natal config file' else message verifyConfig = (config) -> if !config.androidHost? || !config.modules? || !config.imageDirs? || !config.interface? || !config.iosHost? || !config.envRoots? throw new Error 're-natal project needs to be upgraded, please run: re-natal upgrade' config readConfig = (verify = true)-> try config = JSON.parse readFile '.re-natal' if (verify) verifyConfig(config) else config catch {message} logErr \ if message.match /ENOENT/i 'No Re-Natal config was found in this directory (.re-natal)' else if message.match /EACCES/i 'No read permissions for .re-natal' else if message.match /Unexpected/i '.re-natal contains malformed JSON' else message scanImageDir = (dir) -> fnames = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isFile() .filter (path) -> removeExcludeFiles(path) .map (path) -> path.replace /@2x|@3x/i, '' .map (path) -> path.replace new RegExp(".(android|ios)" + fpath.extname(path) + "$", "i"), fpath.extname(path) .filter (v, idx, slf) -> slf.indexOf(v) == idx dirs = fs.readdirSync(dir) .map (fname) -> "#{dir}/#{fname}" .filter (path) -> fs.statSync(path).isDirectory() fnames.concat scanImages(dirs) removeExcludeFiles = (file) -> excludedFileNames = [".DS_Store"] res = excludedFileNames.map (ex) -> (file.indexOf ex) == -1 true in res scanImages = (dirs) -> imgs = [] for dir in dirs imgs = imgs.concat(scanImageDir(dir)); imgs resolveAndroidDevHost = (deviceType) -> allowedTypes = {'real': 'localhost', 'avd': '10.0.2.2', 'genymotion': '10.0.3.2'} devHost = allowedTypes[deviceType] if (devHost?) log "Using '#{devHost}' for device type #{deviceType}" devHost else deviceTypeIsIpAddress(deviceType, Object.keys(allowedTypes)) configureDevHostForAndroidDevice = (deviceType) -> try devHost = resolveAndroidDevHost(deviceType) config = readConfig() config.androidHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message resolveIosDevHost = (deviceType) -> if deviceType == 'simulator' log "Using 'localhost' for iOS simulator" 'localhost' else if deviceType == 'real' en0Ip = exec('ipconfig getifaddr en0', true).toString().trim() log "Using IP of interface en0:'#{en0Ip}' for real iOS device" en0Ip else deviceTypeIsIpAddress(deviceType, ['simulator', 'real']) configureDevHostForIosDevice = (deviceType) -> try devHost = resolveIosDevHost(deviceType) config = readConfig() config.iosHost = devHost writeConfig(config) log "Please run: re-natal use-figwheel to take effect." catch {message} logErr message deviceTypeIsIpAddress = (deviceType, allowedTypes) -> if deviceType.match(ipAddressRx) log "Using development host IP: '#{deviceType}'" deviceType else log("Value '#{deviceType}' is not a valid IP address, still configured it as development host. Did you mean one of: [#{allowedTypes}] ?", 'yellow') deviceType copyDevEnvironmentFiles = (interfaceName, projNameHyph, projName, devEnvRoot, devHost) -> fs.mkdirpSync "#{devEnvRoot}/env/ios" fs.mkdirpSync "#{devEnvRoot}/env/android" userNsPath = "#{devEnvRoot}/user.clj" fs.copySync("#{resources}/user.clj", userNsPath) mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainIosDevPath) edit mainIosDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"], [devHostRx, devHost] ] fs.copySync("#{resources}/#{cljsDir}/main_dev.cljs", mainAndroidDevPath) edit mainAndroidDevPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"], [devHostRx, devHost]] copyProdEnvironmentFiles = (interfaceName, projNameHyph, projName, prodEnvRoot) -> fs.mkdirpSync "#{prodEnvRoot}/env/ios" fs.mkdirpSync "#{prodEnvRoot}/env/android" mainIosProdPath = "#{prodEnvRoot}/env/ios/main.cljs" mainAndroidProdPath = "#{prodEnvRoot}/env/android/main.cljs" cljsDir = interfaceConf[interfaceName].cljsDir fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainIosProdPath) edit mainIosProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "ios"]] fs.copySync("#{resources}/#{cljsDir}/main_prod.cljs", mainAndroidProdPath) edit mainAndroidProdPath, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, "android"]] copyFigwheelBridge = (projNameUs) -> fs.copySync("#{resources}/figwheel-bridge.js", "./figwheel-bridge.js") edit "figwheel-bridge.js", [[projNameUsRx, projNameUs]] updateGitIgnore = () -> fs.appendFileSync(".gitignore", "\n# Generated by re-natal\n#\nindex.android.js\nindex.ios.js\ntarget/\n") fs.appendFileSync(".gitignore", "\n# Figwheel\n#\nfigwheel_server.log") patchReactNativePackager = () -> ckDeps.sync {install: true, verbose: false} log "Patching react-native packager to serve *.map files" edit "node_modules/react-native/packager/react-packager/src/Server/index.js", [[/match.*\.map\$\/\)/m, "match(/index\\..*\\.map$/)"]] shimCljsNamespace = (ns) -> filePath = "src/" + ns.replace(/\./g, "/") + ".cljs" fs.mkdirpSync fpath.dirname(filePath) fs.writeFileSync(filePath, "(ns #{ns})") copySrcFiles = (interfaceName, projName, projNameUs, projNameHyph) -> cljsDir = interfaceConf[interfaceName].cljsDir fileNames = interfaceConf[interfaceName].sources.common; for fileName in fileNames path = "src/#{projNameUs}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName]] for platform in platforms fs.mkdirSync "src/#{projNameUs}/#{platform}" fileNames = interfaceConf[interfaceName].sources[platform] for fileName in fileNames path = "src/#{projNameUs}/#{platform}/#{fileName}" fs.copySync("#{resources}/#{cljsDir}/#{fileName}", path) edit path, [[projNameHyphRx, projNameHyph], [projNameRx, projName], [platformRx, platform]] otherFiles = interfaceConf[interfaceName].sources.other; for cpFile in otherFiles from = "#{resources}/#{cljsDir}/#{cpFile[0]}" to = "src/#{cpFile[1]}" fs.copySync(from, to) shims = fileNames = interfaceConf[interfaceName].shims; for namespace in shims shimCljsNamespace(namespace) copyProjectClj = (interfaceName, projNameHyph) -> fs.copySync("#{resources}/project.clj", "project.clj") deps = interfaceConf[interfaceName].deps.join("\n") edit 'project.clj', [[projNameHyphRx, projNameHyph], [interfaceDepsRx, deps]] init = (interfaceName, projName) -> if projName.toLowerCase() is 'react' or !projName.match validNameRx logErr 'Invalid project name. Use an alphanumeric CamelCase name.' projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName try log "Creating #{projName}", 'bgMagenta' log '\u2615 Grab a coffee! Downloading deps might take a while...', 'yellow' if fs.existsSync projNameHyph throw new Error "Directory #{projNameHyph} already exists" ensureExecutableAvailable 'lein' log 'Creating Leiningen project' exec "lein new #{projNameHyph}" log 'Updating Leiningen project' process.chdir projNameHyph fs.removeSync "resources" corePath = "src/#{projNameUs}/core.clj" fs.unlinkSync corePath copyProjectClj(interfaceName, projNameHyph) copySrcFiles(interfaceName, projName, projNameUs, projNameHyph) copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, defaultEnvRoots.prod) fs.copySync("#{resources}/images", "./images") log 'Creating React Native skeleton.' fs.writeFileSync 'package.json', JSON.stringify name: projName version: '0.0.1' private: true scripts: start: 'node_modules/react-native/packager/packager.sh --nonPersistent' dependencies: 'react-native': rnVersion # Fixes issue with packager 'TimeoutError: transforming ... took longer than 301 seconds.' 'babel-plugin-transform-es2015-block-scoping': '6.15.0' , null, 2 exec 'npm i' fs.unlinkSync '.gitignore' exec "node -e \"require('react-native/local-cli/cli').init('.', '#{projName}')\" " updateGitIgnore() generateConfig(interfaceName, projName) copyFigwheelBridge(projNameUs) log 'Compiling ClojureScript' exec 'lein prod-build' log '' log 'To get started with your new app, first cd into its directory:', 'yellow' log "cd #{projNameHyph}", 'inverse' log '' log 'Run iOS app:' , 'yellow' log 'react-native run-ios > /dev/null', 'inverse' log '' log 'To use figwheel type:' , 'yellow' log 're-natal use-figwheel', 'inverse' log 'lein figwheel ios', 'inverse' log '' log 'Reload the app in simulator (\u2318 + R)' log '' log 'At the REPL prompt type this:', 'yellow' log interfaceConf[interfaceName].sampleCommandNs.replace(projNameHyphRx, projNameHyph), 'inverse' log '' log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow' log '' log 'Try this command as an example:', 'yellow' log interfaceConf[interfaceName].sampleCommand, 'inverse' log '' log '✔ Done', 'bgMagenta' log '' catch {message} logErr \ if message.match /type.+lein/i 'Leiningen is required (http://leiningen.org)' else if message.match /npm/i "npm install failed. This may be a network issue. Check #{projNameHyph}/npm-debug.log for details." else message openXcode = (name) -> try exec "open ios/#{name}.xcodeproj" catch {message} logErr \ if message.match /ENOENT/i """ Cannot find #{name}.xcodeproj in ios. Run this command from your project's root directory. """ else if message.match /EACCES/i "Invalid permissions for opening #{name}.xcodeproj in ios" else message generateRequireModulesCode = (modules) -> jsCode = "var modules={'react-native': require('react-native'), 'react': require('react')};" for m in modules jsCode += "modules['#{m}']=require('#{m}');"; jsCode += '\n' updateFigwheelUrls = (devEnvRoot, androidHost, iosHost) -> mainAndroidDevPath = "#{devEnvRoot}/env/android/main.cljs" edit mainAndroidDevPath, [[figwheelUrlRx, "ws://#{androidHost}:"]] mainIosDevPath = "#{devEnvRoot}/env/ios/main.cljs" edit mainIosDevPath, [[figwheelUrlRx, "ws://#{iosHost}:"]] # Current RN version (0.29.2) has no host in AppDelegate.m maybe docs are outdated? updateIosAppDelegate = (projName, iosHost) -> appDelegatePath = "ios/#{projName}/AppDelegate.m" edit appDelegatePath, [[appDelegateRx, "http://#{iosHost}"]] updateIosRCTWebSocketExecutor = (iosHost) -> RCTWebSocketExecutorPath = "node_modules/react-native/Libraries/WebSocket/RCTWebSocketExecutor.m" edit RCTWebSocketExecutorPath, [[debugHostRx, "host = @\"#{iosHost}\";"]] platformModulesAndImages = (config, platform) -> images = scanImages(config.imageDirs).map (fname) -> './' + fname; modulesAndImages = config.modules.concat images; if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {}; if typeof config.modulesPlatform is 'undefined' or typeof config.modulesPlatform[platform] is 'undefined' modulesAndImages else modulesAndImages.concat(config.modulesPlatform[platform]) generateDevScripts = () -> try config = readConfig() projName = config.name devEnvRoot = config.envRoots.dev depState = ckDeps.sync {install: false, verbose: false} if (!depState.depsWereOk) throw new Error "Missing dependencies, please run: re-natal deps" log 'Cleaning...' exec 'lein clean' androidDevHost = config.androidHost iosDevHost = config.iosHost devHost = {'android' : androidDevHost, 'ios' : iosDevHost} for platform in platforms moduleMap = generateRequireModulesCode(platformModulesAndImages(config, platform)) fs.writeFileSync "index.#{platform}.js", "#{moduleMap}require('figwheel-bridge').withModules(modules).start('#{projName}','#{platform}','#{devHost[platform]}');" log "index.#{platform}.js was regenerated" #updateIosAppDelegate(projName, iosDevHost) updateIosRCTWebSocketExecutor(iosDevHost) log "Host in RCTWebSocketExecutor.m was updated" updateFigwheelUrls(devEnvRoot, androidDevHost, iosDevHost) log 'Dev server host for iOS: ' + iosDevHost log 'Dev server host for Android: ' + androidDevHost catch {message} logErr \ if message.match /EACCES/i 'Invalid write permissions for creating development scripts' else message doUpgrade = (config) -> projName = config.name projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase() projNameUs = toUnderscored projName unless config.interface config.interface = defaultInterface unless config.modules config.modules = [] unless config.imageDirs config.imageDirs = ["images"] unless config.androidHost config.androidHost = "localhost" unless config.iosHost config.iosHost = "localhost" unless config.envRoots config.envRoots = defaultEnvRoots writeConfig(config) log 'upgraded .re-natal' interfaceName = config.interface envRoots = config.envRoots copyDevEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.dev, "localhost") copyProdEnvironmentFiles(interfaceName, projNameHyph, projName, envRoots.prod) log "upgraded files in #{envRoots.dev} and #{envRoots.prod} " copyFigwheelBridge(projNameUs) log 'upgraded figwheel-bridge.js' log('To upgrade React Native version please follow the official guide in https://facebook.github.io/react-native/docs/upgrading.html', 'yellow') useComponent = (name, platform) -> try config = readConfig() if typeof platform isnt 'string' config.modules.push name log "Component '#{name}' is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else if platforms.indexOf(platform) > -1 if typeof config.modulesPlatform is 'undefined' config.modulesPlatform = {} if typeof config.modulesPlatform[platform] is 'undefined' config.modulesPlatform[platform] = [] config.modulesPlatform[platform].push name log "Component '#{name}' (#{platform}-only) is now configured for figwheel, please re-run 'use-figwheel' command to take effect" else throw new Error("unsupported platform: #{platform}") writeConfig(config) catch {message} logErr message cli._name = 're-natal' cli.version pkgJson.version cli.command 'init <name>' .description 'create a new ClojureScript React Native project' .option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface', defaultInterface .action (name, cmd) -> if typeof name isnt 'string' logErr ''' re-natal init requires a project name as the first argument. e.g. re-natal init HelloWorld ''' unless interfaceConf[cmd.interface] logErr "Unsupported React interface: #{cmd.interface}, one of [#{interfaceNames}] was expected." ensureFreePort -> init(cmd.interface, name) cli.command 'upgrade' .description 'upgrades project files to current installed version of re-natal (the upgrade of re-natal itself is done via npm)' .action -> doUpgrade readConfig(false) cli.command 'xcode' .description 'open Xcode project' .action -> ensureOSX -> ensureXcode -> openXcode readConfig().name cli.command 'deps' .description 'install all dependencies for the project' .action -> ckDeps.sync {install: true, verbose: true} cli.command 'use-figwheel' .description 'generate index.ios.js and index.android.js for development with figwheel' .action () -> generateDevScripts() cli.command 'use-android-device <type>' .description 'sets up the host for android device type: \'real\' - localhost, \'avd\' - 10.0.2.2, \'genymotion\' - 10.0.3.2, IP' .action (type) -> configureDevHostForAndroidDevice type cli.command 'use-ios-device <type>' .description 'sets up the host for ios device type: \'simulator\' - localhost, \'real\' - auto detect IP on eth0, IP' .action (type) -> configureDevHostForIosDevice type cli.command 'use-component <name> [<platform>]' .description 'configures a custom component to work with figwheel. name is the value you pass to (js/require) function.' .action (name, platform) -> useComponent(name, platform) cli.command 'enable-source-maps' .description 'patches RN packager to server *.map files from filesystem, so that chrome can download them.' .action () -> patchReactNativePackager() cli.command 'copy-figwheel-bridge' .description 'copy figwheel-bridge.js into project' .action () -> copyFigwheelBridge(readConfig(false).name) log "Copied figwheel-bridge.js" cli.on '*', (command) -> logErr "unknown command #{command[0]}. See re-natal --help for valid commands" unless semver.satisfies process.version[1...], nodeVersion logErr """ Re-Natal requires Node.js version #{nodeVersion} You have #{process.version[1...]} """ if process.argv.length <= 2 cli.outputHelp() else cli.parse process.argv
[ { "context": " will fall back to reddit/r/golang\n#\n# Author:\n# Nevio Vesic (0x19) <nevio.vesic@gmail.com>\n\nparser = require ", "end": 320, "score": 0.9998486638069153, "start": 309, "tag": "NAME", "value": "Nevio Vesic" }, { "context": "ddit/r/golang\n#\n# Author:\n# Nevio V...
src/gonews.coffee
0x19/hubot-gonews
2
# Description # Hubot golang news pulled from reddit # # Configuration: # GONEWS_RSS_FEED_URL # # Commands: # gonews latest [\d+] - returns list of latest golang news. Default 5 items per response... # # Notes: # GONEWS_RSS_FEED_URL is not needed. It will fall back to reddit/r/golang # # Author: # Nevio Vesic (0x19) <nevio.vesic@gmail.com> parser = require 'parse-rss' reddit_url = process.env.GONEWS_RSS_FEED_URL || "https://www.reddit.com/r/golang/.rss" module.exports = (robot) -> robot.respond /gonews help/i, (msg) -> cmds = robot.helpCommands() cmds = (cmd for cmd in cmds when cmd.match(/(gonews)/)) msg.send cmds.join("\n") robot.respond /gonews latest ?(\d+)?/i, (msg) -> random = Math.floor(Math.random() * (2000000 - 1000000) + 1000000) count = msg.match[1] || 5 robot.logger.info "Fetching latest #{count} rss feed messages" robot.logger.info "#{reddit_url}?time=#{random}" parser "#{reddit_url}?time=#{random}", (err,rss)-> if err msg.send "Error happen while fetching golang news: #{err}" return for feed in rss[0..count] robot.emit 'slack.attachment', message: msg.message content: title: feed.title, title_link: feed.link text: feed.description
186881
# Description # Hubot golang news pulled from reddit # # Configuration: # GONEWS_RSS_FEED_URL # # Commands: # gonews latest [\d+] - returns list of latest golang news. Default 5 items per response... # # Notes: # GONEWS_RSS_FEED_URL is not needed. It will fall back to reddit/r/golang # # Author: # <NAME> (0x19) <<EMAIL>> parser = require 'parse-rss' reddit_url = process.env.GONEWS_RSS_FEED_URL || "https://www.reddit.com/r/golang/.rss" module.exports = (robot) -> robot.respond /gonews help/i, (msg) -> cmds = robot.helpCommands() cmds = (cmd for cmd in cmds when cmd.match(/(gonews)/)) msg.send cmds.join("\n") robot.respond /gonews latest ?(\d+)?/i, (msg) -> random = Math.floor(Math.random() * (2000000 - 1000000) + 1000000) count = msg.match[1] || 5 robot.logger.info "Fetching latest #{count} rss feed messages" robot.logger.info "#{reddit_url}?time=#{random}" parser "#{reddit_url}?time=#{random}", (err,rss)-> if err msg.send "Error happen while fetching golang news: #{err}" return for feed in rss[0..count] robot.emit 'slack.attachment', message: msg.message content: title: feed.title, title_link: feed.link text: feed.description
true
# Description # Hubot golang news pulled from reddit # # Configuration: # GONEWS_RSS_FEED_URL # # Commands: # gonews latest [\d+] - returns list of latest golang news. Default 5 items per response... # # Notes: # GONEWS_RSS_FEED_URL is not needed. It will fall back to reddit/r/golang # # Author: # PI:NAME:<NAME>END_PI (0x19) <PI:EMAIL:<EMAIL>END_PI> parser = require 'parse-rss' reddit_url = process.env.GONEWS_RSS_FEED_URL || "https://www.reddit.com/r/golang/.rss" module.exports = (robot) -> robot.respond /gonews help/i, (msg) -> cmds = robot.helpCommands() cmds = (cmd for cmd in cmds when cmd.match(/(gonews)/)) msg.send cmds.join("\n") robot.respond /gonews latest ?(\d+)?/i, (msg) -> random = Math.floor(Math.random() * (2000000 - 1000000) + 1000000) count = msg.match[1] || 5 robot.logger.info "Fetching latest #{count} rss feed messages" robot.logger.info "#{reddit_url}?time=#{random}" parser "#{reddit_url}?time=#{random}", (err,rss)-> if err msg.send "Error happen while fetching golang news: #{err}" return for feed in rss[0..count] robot.emit 'slack.attachment', message: msg.message content: title: feed.title, title_link: feed.link text: feed.description
[ { "context": ": Tier 3 - Total Cost of Ownership Tool\n# Author: matt@wintr.us @ WINTR\n#########################################", "end": 129, "score": 0.9999143481254578, "start": 116, "tag": "EMAIL", "value": "matt@wintr.us" } ]
source/js/main.coffee
CenturyLinkCloud/EstimatorTCO
4
######################################################### # Title: Tier 3 - Total Cost of Ownership Tool # Author: matt@wintr.us @ WINTR ######################################################### #-------------------------------------------------------- # Imports #-------------------------------------------------------- Config = require './app/Config.coffee' Utils = require './app/Utils.coffee' PubSub = require './app/PubSub.coffee' Router = require './app/Router.coffee' InputPanelView = require './app/views/InputPanelView.coffee' PlatformProductsView = require './app/views/PlatformProductsView.coffee' VariancesView = require './app/views/VariancesView.coffee' CenturyLinkProductsView = require './app/views/CenturyLinkProductsView.coffee' SettingsModel = require './app/models/SettingsModel.coffee' PlatformsCollection = require './app/collections/PlatformsCollection.coffee' ProductsCollection = require './app/collections/ProductsCollection.coffee' DEFAULT_PRICING = require './app/data/default-pricing-object.coffee' DEFAULT_BENCHMARKING = require './app/data/benchmarking.coffee' #-------------------------------------------------------- # Init #-------------------------------------------------------- window.App = readyToInitCount: 0 clcBenchmarking: DEFAULT_BENCHMARKING currency: symbol: "$" rate: 1.0 id: "USD" init: -> dataFromURL = @getDataFromURL() $.getJSON Config.BENCHMARKING_URL, (data) => if data? @clcBenchmarking = data $.getJSON Config.DEFAULT_PRICING_URL, (data) => if data? DEFAULT_PRICING = data @settingsModel = new SettingsModel() @settingsModel.set(dataFromURL) if dataFromURL @platformsCollection = new PlatformsCollection() @productsCollection = new ProductsCollection() @loadCLCData() @initEvents() @router = new Router() Backbone.history.start() #-------------------------------------------------------- # Event initialization #-------------------------------------------------------- initEvents: -> PubSub.on("platform:change", @onPlatformChange, @) PubSub.on("inputPanel:change", @onInputPanelChange, @) PubSub.on("url:change", @onURLChange, @) @platformsCollection.on "sync", => @onPlatformCollectionSync() @productsCollection.on 'reset', => @onProductsUpdated() #-------------------------------------------------------- # Event Listeners #-------------------------------------------------------- onPlatformChange: (e) -> @platform = @platformsCollection.findWhere("key": e.platformKey) products = @platform.get("products") @productsCollection.reset products onPlatformCollectionSync: -> @readyToInitCount += 1 @buildUI() onProductsUpdated: -> @platformProductsView.setCollection @productsCollection @platformProductsView.updateProducts() @centuryLinkProductsView.setCollection @productsCollection @centuryLinkProductsView.updateProducts() @variancesView.setCollection @productsCollection @variancesView.updateProducts() onInputPanelChange: (data) -> # @router.navigate("input/#{JSON.stringify(data)}") onURLChange: (data) -> # @settingsModel.set data #-------------------------------------------------------- # Load CLC Pricing #-------------------------------------------------------- loadCLCData: -> $.ajax type: "GET" url: Config.PRICING_URL success: (data) => @clcPricing = @parsePricingData(data) return @onPricingSync() error: (error) => console.error error @clcPricing = DEFAULT_PRICING return @onPricingSync() return @ onPricingSync: -> @readyToInitCount += 1 @buildUI() return @ parsePricingData: (categories) -> pricing = _.clone DEFAULT_PRICING _.each categories,((category) -> if category.products? _.each category.products, (product) -> if _.has(product,'key') ids = product.key.split(":") switch ids[0] when 'server' switch ids[1] when 'storage' pricing.standardStorage = product.hourly if ids[2] is 'standard' pricing.premiumStorage = product.hourly if ids[2] is 'premium' when 'os' pricing.windows = product.hourly if ids[2] is 'windows' pricing.redhat = product.hourly if ids[2] is 'redhat' else pricing.cpu = product.hourly if ids[1] is 'cpu' pricing.ram = product.hourly if ids[1] is 'memory' when 'networking' pricing.bandwidth = product.monthly if ids[1] is 'bandwidth' ) return pricing #-------------------------------------------------------- # Build UI #-------------------------------------------------------- buildUI: -> return unless @readyToInitCount is 2 @platformProductsView = new PlatformProductsView app: @ @centuryLinkProductsView = new CenturyLinkProductsView app: @ @variancesView = new VariancesView app: @ @inputPanelView = new InputPanelView model: @settingsModel platforms: @platformsCollection app: @ #-------------------------------------------------------- # Get data from URL #-------------------------------------------------------- getDataFromURL: -> if location.hash.length > 10 dataString = location.hash.substring(1) data = JSON.parse dataString location.hash = "" history.pushState("", document.title, window.location.pathname) return data else return null getCurrencyDataThenInit: -> unless @currencyData? $.ajax url: Config.CURRENCY_URL type: "GET" success: (data) => @currencyData = data $currencySelect = $("#currency-select") $currencySelect.html('') _.each data[Config.DEFAULT_CURRENCY_ID], (currency) => extra = if currency.id is Config.DEFAULT_CURRENCY_ID then "" else " (#{currency.rate} x #{Config.DEFAULT_CURRENCY_ID})" $option = $("<option value='#{currency.id}'>#{currency.id}#{extra}</option>") $currencySelect.append $option return setTimeout(@init(),500) error: (error) => $currencySelect = $("#currency-select") $option = $("<option value='#{Config.DEFAULT_CURRENCY_ID}'>#{Config.DEFAULT_CURRENCY_ID}</option>") $currencySelect.append $option return setTimeout(@init(),500) #-------------------------------------------------------- # DOM Ready #-------------------------------------------------------- $ -> Config.init(App)
188380
######################################################### # Title: Tier 3 - Total Cost of Ownership Tool # Author: <EMAIL> @ WINTR ######################################################### #-------------------------------------------------------- # Imports #-------------------------------------------------------- Config = require './app/Config.coffee' Utils = require './app/Utils.coffee' PubSub = require './app/PubSub.coffee' Router = require './app/Router.coffee' InputPanelView = require './app/views/InputPanelView.coffee' PlatformProductsView = require './app/views/PlatformProductsView.coffee' VariancesView = require './app/views/VariancesView.coffee' CenturyLinkProductsView = require './app/views/CenturyLinkProductsView.coffee' SettingsModel = require './app/models/SettingsModel.coffee' PlatformsCollection = require './app/collections/PlatformsCollection.coffee' ProductsCollection = require './app/collections/ProductsCollection.coffee' DEFAULT_PRICING = require './app/data/default-pricing-object.coffee' DEFAULT_BENCHMARKING = require './app/data/benchmarking.coffee' #-------------------------------------------------------- # Init #-------------------------------------------------------- window.App = readyToInitCount: 0 clcBenchmarking: DEFAULT_BENCHMARKING currency: symbol: "$" rate: 1.0 id: "USD" init: -> dataFromURL = @getDataFromURL() $.getJSON Config.BENCHMARKING_URL, (data) => if data? @clcBenchmarking = data $.getJSON Config.DEFAULT_PRICING_URL, (data) => if data? DEFAULT_PRICING = data @settingsModel = new SettingsModel() @settingsModel.set(dataFromURL) if dataFromURL @platformsCollection = new PlatformsCollection() @productsCollection = new ProductsCollection() @loadCLCData() @initEvents() @router = new Router() Backbone.history.start() #-------------------------------------------------------- # Event initialization #-------------------------------------------------------- initEvents: -> PubSub.on("platform:change", @onPlatformChange, @) PubSub.on("inputPanel:change", @onInputPanelChange, @) PubSub.on("url:change", @onURLChange, @) @platformsCollection.on "sync", => @onPlatformCollectionSync() @productsCollection.on 'reset', => @onProductsUpdated() #-------------------------------------------------------- # Event Listeners #-------------------------------------------------------- onPlatformChange: (e) -> @platform = @platformsCollection.findWhere("key": e.platformKey) products = @platform.get("products") @productsCollection.reset products onPlatformCollectionSync: -> @readyToInitCount += 1 @buildUI() onProductsUpdated: -> @platformProductsView.setCollection @productsCollection @platformProductsView.updateProducts() @centuryLinkProductsView.setCollection @productsCollection @centuryLinkProductsView.updateProducts() @variancesView.setCollection @productsCollection @variancesView.updateProducts() onInputPanelChange: (data) -> # @router.navigate("input/#{JSON.stringify(data)}") onURLChange: (data) -> # @settingsModel.set data #-------------------------------------------------------- # Load CLC Pricing #-------------------------------------------------------- loadCLCData: -> $.ajax type: "GET" url: Config.PRICING_URL success: (data) => @clcPricing = @parsePricingData(data) return @onPricingSync() error: (error) => console.error error @clcPricing = DEFAULT_PRICING return @onPricingSync() return @ onPricingSync: -> @readyToInitCount += 1 @buildUI() return @ parsePricingData: (categories) -> pricing = _.clone DEFAULT_PRICING _.each categories,((category) -> if category.products? _.each category.products, (product) -> if _.has(product,'key') ids = product.key.split(":") switch ids[0] when 'server' switch ids[1] when 'storage' pricing.standardStorage = product.hourly if ids[2] is 'standard' pricing.premiumStorage = product.hourly if ids[2] is 'premium' when 'os' pricing.windows = product.hourly if ids[2] is 'windows' pricing.redhat = product.hourly if ids[2] is 'redhat' else pricing.cpu = product.hourly if ids[1] is 'cpu' pricing.ram = product.hourly if ids[1] is 'memory' when 'networking' pricing.bandwidth = product.monthly if ids[1] is 'bandwidth' ) return pricing #-------------------------------------------------------- # Build UI #-------------------------------------------------------- buildUI: -> return unless @readyToInitCount is 2 @platformProductsView = new PlatformProductsView app: @ @centuryLinkProductsView = new CenturyLinkProductsView app: @ @variancesView = new VariancesView app: @ @inputPanelView = new InputPanelView model: @settingsModel platforms: @platformsCollection app: @ #-------------------------------------------------------- # Get data from URL #-------------------------------------------------------- getDataFromURL: -> if location.hash.length > 10 dataString = location.hash.substring(1) data = JSON.parse dataString location.hash = "" history.pushState("", document.title, window.location.pathname) return data else return null getCurrencyDataThenInit: -> unless @currencyData? $.ajax url: Config.CURRENCY_URL type: "GET" success: (data) => @currencyData = data $currencySelect = $("#currency-select") $currencySelect.html('') _.each data[Config.DEFAULT_CURRENCY_ID], (currency) => extra = if currency.id is Config.DEFAULT_CURRENCY_ID then "" else " (#{currency.rate} x #{Config.DEFAULT_CURRENCY_ID})" $option = $("<option value='#{currency.id}'>#{currency.id}#{extra}</option>") $currencySelect.append $option return setTimeout(@init(),500) error: (error) => $currencySelect = $("#currency-select") $option = $("<option value='#{Config.DEFAULT_CURRENCY_ID}'>#{Config.DEFAULT_CURRENCY_ID}</option>") $currencySelect.append $option return setTimeout(@init(),500) #-------------------------------------------------------- # DOM Ready #-------------------------------------------------------- $ -> Config.init(App)
true
######################################################### # Title: Tier 3 - Total Cost of Ownership Tool # Author: PI:EMAIL:<EMAIL>END_PI @ WINTR ######################################################### #-------------------------------------------------------- # Imports #-------------------------------------------------------- Config = require './app/Config.coffee' Utils = require './app/Utils.coffee' PubSub = require './app/PubSub.coffee' Router = require './app/Router.coffee' InputPanelView = require './app/views/InputPanelView.coffee' PlatformProductsView = require './app/views/PlatformProductsView.coffee' VariancesView = require './app/views/VariancesView.coffee' CenturyLinkProductsView = require './app/views/CenturyLinkProductsView.coffee' SettingsModel = require './app/models/SettingsModel.coffee' PlatformsCollection = require './app/collections/PlatformsCollection.coffee' ProductsCollection = require './app/collections/ProductsCollection.coffee' DEFAULT_PRICING = require './app/data/default-pricing-object.coffee' DEFAULT_BENCHMARKING = require './app/data/benchmarking.coffee' #-------------------------------------------------------- # Init #-------------------------------------------------------- window.App = readyToInitCount: 0 clcBenchmarking: DEFAULT_BENCHMARKING currency: symbol: "$" rate: 1.0 id: "USD" init: -> dataFromURL = @getDataFromURL() $.getJSON Config.BENCHMARKING_URL, (data) => if data? @clcBenchmarking = data $.getJSON Config.DEFAULT_PRICING_URL, (data) => if data? DEFAULT_PRICING = data @settingsModel = new SettingsModel() @settingsModel.set(dataFromURL) if dataFromURL @platformsCollection = new PlatformsCollection() @productsCollection = new ProductsCollection() @loadCLCData() @initEvents() @router = new Router() Backbone.history.start() #-------------------------------------------------------- # Event initialization #-------------------------------------------------------- initEvents: -> PubSub.on("platform:change", @onPlatformChange, @) PubSub.on("inputPanel:change", @onInputPanelChange, @) PubSub.on("url:change", @onURLChange, @) @platformsCollection.on "sync", => @onPlatformCollectionSync() @productsCollection.on 'reset', => @onProductsUpdated() #-------------------------------------------------------- # Event Listeners #-------------------------------------------------------- onPlatformChange: (e) -> @platform = @platformsCollection.findWhere("key": e.platformKey) products = @platform.get("products") @productsCollection.reset products onPlatformCollectionSync: -> @readyToInitCount += 1 @buildUI() onProductsUpdated: -> @platformProductsView.setCollection @productsCollection @platformProductsView.updateProducts() @centuryLinkProductsView.setCollection @productsCollection @centuryLinkProductsView.updateProducts() @variancesView.setCollection @productsCollection @variancesView.updateProducts() onInputPanelChange: (data) -> # @router.navigate("input/#{JSON.stringify(data)}") onURLChange: (data) -> # @settingsModel.set data #-------------------------------------------------------- # Load CLC Pricing #-------------------------------------------------------- loadCLCData: -> $.ajax type: "GET" url: Config.PRICING_URL success: (data) => @clcPricing = @parsePricingData(data) return @onPricingSync() error: (error) => console.error error @clcPricing = DEFAULT_PRICING return @onPricingSync() return @ onPricingSync: -> @readyToInitCount += 1 @buildUI() return @ parsePricingData: (categories) -> pricing = _.clone DEFAULT_PRICING _.each categories,((category) -> if category.products? _.each category.products, (product) -> if _.has(product,'key') ids = product.key.split(":") switch ids[0] when 'server' switch ids[1] when 'storage' pricing.standardStorage = product.hourly if ids[2] is 'standard' pricing.premiumStorage = product.hourly if ids[2] is 'premium' when 'os' pricing.windows = product.hourly if ids[2] is 'windows' pricing.redhat = product.hourly if ids[2] is 'redhat' else pricing.cpu = product.hourly if ids[1] is 'cpu' pricing.ram = product.hourly if ids[1] is 'memory' when 'networking' pricing.bandwidth = product.monthly if ids[1] is 'bandwidth' ) return pricing #-------------------------------------------------------- # Build UI #-------------------------------------------------------- buildUI: -> return unless @readyToInitCount is 2 @platformProductsView = new PlatformProductsView app: @ @centuryLinkProductsView = new CenturyLinkProductsView app: @ @variancesView = new VariancesView app: @ @inputPanelView = new InputPanelView model: @settingsModel platforms: @platformsCollection app: @ #-------------------------------------------------------- # Get data from URL #-------------------------------------------------------- getDataFromURL: -> if location.hash.length > 10 dataString = location.hash.substring(1) data = JSON.parse dataString location.hash = "" history.pushState("", document.title, window.location.pathname) return data else return null getCurrencyDataThenInit: -> unless @currencyData? $.ajax url: Config.CURRENCY_URL type: "GET" success: (data) => @currencyData = data $currencySelect = $("#currency-select") $currencySelect.html('') _.each data[Config.DEFAULT_CURRENCY_ID], (currency) => extra = if currency.id is Config.DEFAULT_CURRENCY_ID then "" else " (#{currency.rate} x #{Config.DEFAULT_CURRENCY_ID})" $option = $("<option value='#{currency.id}'>#{currency.id}#{extra}</option>") $currencySelect.append $option return setTimeout(@init(),500) error: (error) => $currencySelect = $("#currency-select") $option = $("<option value='#{Config.DEFAULT_CURRENCY_ID}'>#{Config.DEFAULT_CURRENCY_ID}</option>") $currencySelect.append $option return setTimeout(@init(),500) #-------------------------------------------------------- # DOM Ready #-------------------------------------------------------- $ -> Config.init(App)
[ { "context": "stalling Oh My Zsh\" && git clone git://github.com/kmcginnes/oh-my-zsh.git ~/.oh-my-zsh'\n brew:\n arche", "end": 1280, "score": 0.9996128082275391, "start": 1271, "tag": "USERNAME", "value": "kmcginnes" }, { "context": "\n # hipchat: 'hipchat'\n # one...
Gruntfile.coffee
kmcginnes/dotfiles
1
home = require 'home-dir' module.exports = (grunt) -> grunt.initConfig config: sublime: path_app_support: home 'Library/Application Support/Sublime Text 3' symlink: options: overwrite: true dotfiles: expand: true src: '**/*.symlink' dest: "#{ home() }/" flatten: true rename: (dest, src) -> finalDest = dest + '.' + src.replace('.symlink','') console.log "#{src} -> #{finalDest}" return finalDest sublime_user: src: 'sublime-text/User' dest: '<%= config.sublime.path_app_support %>/Packages/User' shell: theme_terminal: command: 'open "osx/Smyck.terminal"' # change_shell: # command: 'chsh -s /bin/zsh' # osx_defaults: # command: 'source osx/settings.sh' # sublime_package_control: # command: 'echo "Installing Sublime Text Package Control" && mkdir -p "<%= config.sublime.path_app_support %>/Installed Packages" && curl -o "<%= config.sublime.path_app_support %>/Installed Packages/Package Control.sublime-package" https://sublime.wbond.net/Package%20Control.sublime-package' # oh_my_zsh: # command: 'echo "Installing Oh My Zsh" && git clone git://github.com/kmcginnes/oh-my-zsh.git ~/.oh-my-zsh' brew: archey: 'archey' git: 'git' # git_extras: 'git-extras' nvm: 'nvm' rbenv: 'rbenv' ruby_build: 'ruby-build' plenv: 'plenv' perl_build: 'perl-build' go: 'go' ffmpeg: 'ffmpeg' dos2unix: 'dos2unix' cask: 'caskroom/cask/brew-cask' # brew_tap: # unofficial: 'caskroom/versions' # fonts: 'caskroom/fonts' # brew_cask_app: # alfred: 'alfred' # sublime_text_3: 'sublime-text3' # chrome: 'google-chrome' # github: 'github' # hipchat: 'hipchat' # onepassword: 'onepassword' # evernote: 'evernote' # the_unarchiver: 'the-unarchiver' # vlc: 'vlc' # vmware_fusion: 'vmware-fusion' # dropbox: 'dropbox' # flux: 'flux' # gfxcardstatus: 'gfxcardstatus' # brew_cask_font: # courier_new: 'font-courier-new' # inconsolata: 'font-inconsolata' # noto_sans: 'font-noto-sans' # source_code_pro: 'font-source-code-pro' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-shell' grunt.registerTask 'update', ['symlink'] grunt.registerTask 'default', ['symlink','shell','brew']
93450
home = require 'home-dir' module.exports = (grunt) -> grunt.initConfig config: sublime: path_app_support: home 'Library/Application Support/Sublime Text 3' symlink: options: overwrite: true dotfiles: expand: true src: '**/*.symlink' dest: "#{ home() }/" flatten: true rename: (dest, src) -> finalDest = dest + '.' + src.replace('.symlink','') console.log "#{src} -> #{finalDest}" return finalDest sublime_user: src: 'sublime-text/User' dest: '<%= config.sublime.path_app_support %>/Packages/User' shell: theme_terminal: command: 'open "osx/Smyck.terminal"' # change_shell: # command: 'chsh -s /bin/zsh' # osx_defaults: # command: 'source osx/settings.sh' # sublime_package_control: # command: 'echo "Installing Sublime Text Package Control" && mkdir -p "<%= config.sublime.path_app_support %>/Installed Packages" && curl -o "<%= config.sublime.path_app_support %>/Installed Packages/Package Control.sublime-package" https://sublime.wbond.net/Package%20Control.sublime-package' # oh_my_zsh: # command: 'echo "Installing Oh My Zsh" && git clone git://github.com/kmcginnes/oh-my-zsh.git ~/.oh-my-zsh' brew: archey: 'archey' git: 'git' # git_extras: 'git-extras' nvm: 'nvm' rbenv: 'rbenv' ruby_build: 'ruby-build' plenv: 'plenv' perl_build: 'perl-build' go: 'go' ffmpeg: 'ffmpeg' dos2unix: 'dos2unix' cask: 'caskroom/cask/brew-cask' # brew_tap: # unofficial: 'caskroom/versions' # fonts: 'caskroom/fonts' # brew_cask_app: # alfred: 'alfred' # sublime_text_3: 'sublime-text3' # chrome: 'google-chrome' # github: 'github' # hipchat: 'hipchat' # onepassword: '<PASSWORD>' # evernote: 'evernote' # the_unarchiver: 'the-unarchiver' # vlc: 'vlc' # vmware_fusion: 'vmware-fusion' # dropbox: 'dropbox' # flux: 'flux' # gfxcardstatus: 'gfxcardstatus' # brew_cask_font: # courier_new: 'font-courier-new' # inconsolata: 'font-inconsolata' # noto_sans: 'font-noto-sans' # source_code_pro: 'font-source-code-pro' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-shell' grunt.registerTask 'update', ['symlink'] grunt.registerTask 'default', ['symlink','shell','brew']
true
home = require 'home-dir' module.exports = (grunt) -> grunt.initConfig config: sublime: path_app_support: home 'Library/Application Support/Sublime Text 3' symlink: options: overwrite: true dotfiles: expand: true src: '**/*.symlink' dest: "#{ home() }/" flatten: true rename: (dest, src) -> finalDest = dest + '.' + src.replace('.symlink','') console.log "#{src} -> #{finalDest}" return finalDest sublime_user: src: 'sublime-text/User' dest: '<%= config.sublime.path_app_support %>/Packages/User' shell: theme_terminal: command: 'open "osx/Smyck.terminal"' # change_shell: # command: 'chsh -s /bin/zsh' # osx_defaults: # command: 'source osx/settings.sh' # sublime_package_control: # command: 'echo "Installing Sublime Text Package Control" && mkdir -p "<%= config.sublime.path_app_support %>/Installed Packages" && curl -o "<%= config.sublime.path_app_support %>/Installed Packages/Package Control.sublime-package" https://sublime.wbond.net/Package%20Control.sublime-package' # oh_my_zsh: # command: 'echo "Installing Oh My Zsh" && git clone git://github.com/kmcginnes/oh-my-zsh.git ~/.oh-my-zsh' brew: archey: 'archey' git: 'git' # git_extras: 'git-extras' nvm: 'nvm' rbenv: 'rbenv' ruby_build: 'ruby-build' plenv: 'plenv' perl_build: 'perl-build' go: 'go' ffmpeg: 'ffmpeg' dos2unix: 'dos2unix' cask: 'caskroom/cask/brew-cask' # brew_tap: # unofficial: 'caskroom/versions' # fonts: 'caskroom/fonts' # brew_cask_app: # alfred: 'alfred' # sublime_text_3: 'sublime-text3' # chrome: 'google-chrome' # github: 'github' # hipchat: 'hipchat' # onepassword: 'PI:PASSWORD:<PASSWORD>END_PI' # evernote: 'evernote' # the_unarchiver: 'the-unarchiver' # vlc: 'vlc' # vmware_fusion: 'vmware-fusion' # dropbox: 'dropbox' # flux: 'flux' # gfxcardstatus: 'gfxcardstatus' # brew_cask_font: # courier_new: 'font-courier-new' # inconsolata: 'font-inconsolata' # noto_sans: 'font-noto-sans' # source_code_pro: 'font-source-code-pro' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-shell' grunt.registerTask 'update', ['symlink'] grunt.registerTask 'default', ['symlink','shell','brew']
[ { "context": "],\n \"series\": [\n {\n \"name\": \"M\",\n \"data\": [3, 2, 0]\n },\n ", "end": 708, "score": 0.9821245670318604, "start": 707, "tag": "NAME", "value": "M" }, { "context": "[3, 2, 0]\n },\n {\n \"name\"...
test/histogramTest.coffee
lmaccherone/analize
2
lumenize = require('../') histogram = lumenize.histogram {utils} = require('../') rows = [ {age: 7, sex: 'M'}, {age: 25, sex: 'F'}, {age: 23, sex: 'F'}, {age: 27, sex: 'F'}, {age: 34, sex: 'M'}, {age: 55, sex: 'F'}, {age: 42, sex: 'F'}, {age: 13, sex: 'M'}, {age: 11, sex: 'M'}, {age: 23, sex: 'F'}, {age: 31, sex: 'F'}, {age: 32, sex: 'F'}, {age: 29, sex: 'M'}, {age: 16, sex: 'F'}, {age: 31, sex: 'F'}, {age: 22, sex: 'F'}, {age: 25, sex: 'F'}, ] exports.histogramTest = testDisctiminator: (test) -> h = histogram.discriminated(rows, 'age', 'sex') expected = { "categories": ["7-23", "23-39", "39-56"], "series": [ { "name": "M", "data": [3, 2, 0] }, { "name": "F", "data": [2, 8, 2] } ], "discriminatorValues": ["M", "F"], "stats": [ {"min": 7, "p25": 11, "median": 13, "p75": 29, "max": 34}, {"min": 16, "p25": 23, "median": 26, "p75": 31.25, "max": 55} ], "boxPlotArrays": [ [ 7, 11, 13, 29 , 34], [16, 23, 26, 31.25, 55] ] } test.ok(utils.filterMatch(expected, h)) test.ok(64 <= h.successfulClassificationRate <= 70) test.done() testControlledBucketing: (test) -> buckets = histogram.buckets([], null, null, 1, 0, 100, 100) test.equal(buckets.length, 100) for b, index in buckets test.equal(b.index, index) test.equal(10, histogram.bucket(10.234, buckets).index) test.equal(null, histogram.bucket(100, buckets)) test.done() testCalculatedBucketing: (test) -> buckets = histogram.buckets(rows, 'age', null, 1) expected = [ { index: 0, startOn: null, endBelow: 16, label: '< 16' }, { index: 1, startOn: 16, endBelow: 25, label: '16-25' }, { index: 2, startOn: 25, endBelow: 34, label: '25-34' }, { index: 3, startOn: 34, endBelow: 43, label: '34-43' }, { index: 4, startOn: 43, endBelow: null, label: '>= 43' } ] test.deepEqual(expected, buckets) test.equal(0, histogram.bucket(10.234, buckets).index) test.equal(0, histogram.bucket(-1234567, buckets).index) test.equal(2, histogram.bucket(25, buckets).index) test.equal(2, histogram.bucket(25.24, buckets).index) test.equal(4, histogram.bucket(1234567, buckets).index) h = histogram.histogramFromBuckets(rows, 'age', buckets) counts = (row.count for row in h) expected = [ 3, 4, 7, 2, 1 ] test.deepEqual(counts, expected) h2 = histogram.histogram(rows, 'age', null, 1) test.deepEqual(h, h2) test.done() testBy10: (test) -> buckets = histogram.buckets(rows, 'age', null, 10) expected = [ { index: 0, startOn: null, endBelow: 10, label: '< 10' }, { index: 1, startOn: 10, endBelow: 20, label: '10-20' }, { index: 2, startOn: 20, endBelow: 30, label: '20-30' }, { index: 3, startOn: 30, endBelow: 40, label: '30-40' }, { index: 4, startOn: 40, endBelow: null, label: '>= 40' } ] test.deepEqual(expected, buckets) test.done() testConstantDepth: (test) -> values = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 200, 300, 400, 500] h = histogram.histogram(values, null, histogram.bucketsConstantDepth, 1, null, null, 3) counts = (row.count for row in h) test.deepEqual([5, 5, 5], counts) test.done() testLog: (test) -> values = [0.05, 0.5, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1, 1], counts) test.done() testLogZero: (test) -> values = [0, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1], counts) test.done() testLogHigher: (test) -> values = [500, 5000, 50000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1], counts) test.done() testPercentile: (test) -> values = [] for i in [1..50] values.push(i * 10 - 1000) for i in [1..50] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) test.equal(buckets[49].label, '-504.90000000000003-255') h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 1) values = [] for i in [1..100] values.push(i * 10 - 1000) for i in [1..100] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 2) test.done() testZeroAndOneRows: (test) -> rows = [10] h = histogram.histogram(rows) test.equal(h[0].count, 1) rows = [] h = histogram.histogram(rows) test.equal(h[0].count, 0) test.done() testNullNaNEtc: (test) -> grades = [ {name: 'Joe', average: 105}, # extra credit {name: 'Jeff', average: NaN}, # missed it by that much {name: 'John', average: 1/0}, {name: 'Jess', average: -1/0}, {name: 'Joseph', average: null}, {name: 'Julie', average: undefined}, {name: 'Juan', average: 75}, {name: 'Jill', average: 73}, {name: 'Jon', average: 71}, {name: 'Jorge', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') for bucket, index in buckets if index is 0 test.ok(! bucket.startOn?) else test.equal(utils.type(bucket.startOn), 'number') if index is 99 test.ok(! bucket.endBelow?) else test.equal(utils.type(bucket.endBelow), 'number') test.done() testPercentileExample: (test) -> grades = [ # A 90th percentile and above {name: 'Joe', average: 105}, # extra credit # B 60th percentile and above {name: 'Jeff', average: 104.9}, # missed it by that much {name: 'John', average: 92}, {name: 'Jess', average: 90}, # C 10th percentile and above {name: 'Joseph', average: 87}, {name: 'Julie', average: 87}, {name: 'Juan', average: 75}, {name: 'Jill', average: 73}, {name: 'Jon', average: 71}, # F rest {name: 'Jorge', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') getGrade = (average, buckets) -> percentile = histogram.bucket(average, buckets).percentileHigherIsBetter if percentile >= 90 return 'A' else if percentile >= 60 return 'B' else if percentile >= 10 return 'C' else return 'F' test.equal(getGrade(grades[0].average, buckets), 'A') test.equal(getGrade(grades[1].average, buckets), 'B') test.equal(getGrade(grades[2].average, buckets), 'B') test.equal(getGrade(grades[3].average, buckets), 'B') test.equal(getGrade(grades[4].average, buckets), 'C') test.equal(getGrade(grades[5].average, buckets), 'C') test.equal(getGrade(grades[6].average, buckets), 'C') test.equal(getGrade(grades[7].average, buckets), 'C') test.equal(getGrade(grades[8].average, buckets), 'C') test.equal(getGrade(grades[9].average, buckets), 'F') # 0 Joe A # 1 Jeff B # 2 John B # 3 Jess B # 4 Joseph C # 5 Julie C # 6 Juan C # 7 Jill C # 8 Jon C # 9 Jorge F test.done() testMerge: (test) -> values = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 3) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 2, label: '1-3' }] test.deepEqual(buckets, expected) buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 4) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 3, label: '1-3' }] test.deepEqual(buckets, expected) values = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, null, null, 3) expected = [ { index: 0, startOn: null, endBelow: 2, label: '< 2' }, { index: 1, startOn: 2, endBelow: null, matchingRangeIndexStart: 1, matchingRangeIndexEnd: 2, label: '>= 2'} ] test.deepEqual(buckets, expected) test.done()
165713
lumenize = require('../') histogram = lumenize.histogram {utils} = require('../') rows = [ {age: 7, sex: 'M'}, {age: 25, sex: 'F'}, {age: 23, sex: 'F'}, {age: 27, sex: 'F'}, {age: 34, sex: 'M'}, {age: 55, sex: 'F'}, {age: 42, sex: 'F'}, {age: 13, sex: 'M'}, {age: 11, sex: 'M'}, {age: 23, sex: 'F'}, {age: 31, sex: 'F'}, {age: 32, sex: 'F'}, {age: 29, sex: 'M'}, {age: 16, sex: 'F'}, {age: 31, sex: 'F'}, {age: 22, sex: 'F'}, {age: 25, sex: 'F'}, ] exports.histogramTest = testDisctiminator: (test) -> h = histogram.discriminated(rows, 'age', 'sex') expected = { "categories": ["7-23", "23-39", "39-56"], "series": [ { "name": "<NAME>", "data": [3, 2, 0] }, { "name": "<NAME>", "data": [2, 8, 2] } ], "discriminatorValues": ["M", "F"], "stats": [ {"min": 7, "p25": 11, "median": 13, "p75": 29, "max": 34}, {"min": 16, "p25": 23, "median": 26, "p75": 31.25, "max": 55} ], "boxPlotArrays": [ [ 7, 11, 13, 29 , 34], [16, 23, 26, 31.25, 55] ] } test.ok(utils.filterMatch(expected, h)) test.ok(64 <= h.successfulClassificationRate <= 70) test.done() testControlledBucketing: (test) -> buckets = histogram.buckets([], null, null, 1, 0, 100, 100) test.equal(buckets.length, 100) for b, index in buckets test.equal(b.index, index) test.equal(10, histogram.bucket(10.234, buckets).index) test.equal(null, histogram.bucket(100, buckets)) test.done() testCalculatedBucketing: (test) -> buckets = histogram.buckets(rows, 'age', null, 1) expected = [ { index: 0, startOn: null, endBelow: 16, label: '< 16' }, { index: 1, startOn: 16, endBelow: 25, label: '16-25' }, { index: 2, startOn: 25, endBelow: 34, label: '25-34' }, { index: 3, startOn: 34, endBelow: 43, label: '34-43' }, { index: 4, startOn: 43, endBelow: null, label: '>= 43' } ] test.deepEqual(expected, buckets) test.equal(0, histogram.bucket(10.234, buckets).index) test.equal(0, histogram.bucket(-1234567, buckets).index) test.equal(2, histogram.bucket(25, buckets).index) test.equal(2, histogram.bucket(25.24, buckets).index) test.equal(4, histogram.bucket(1234567, buckets).index) h = histogram.histogramFromBuckets(rows, 'age', buckets) counts = (row.count for row in h) expected = [ 3, 4, 7, 2, 1 ] test.deepEqual(counts, expected) h2 = histogram.histogram(rows, 'age', null, 1) test.deepEqual(h, h2) test.done() testBy10: (test) -> buckets = histogram.buckets(rows, 'age', null, 10) expected = [ { index: 0, startOn: null, endBelow: 10, label: '< 10' }, { index: 1, startOn: 10, endBelow: 20, label: '10-20' }, { index: 2, startOn: 20, endBelow: 30, label: '20-30' }, { index: 3, startOn: 30, endBelow: 40, label: '30-40' }, { index: 4, startOn: 40, endBelow: null, label: '>= 40' } ] test.deepEqual(expected, buckets) test.done() testConstantDepth: (test) -> values = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 200, 300, 400, 500] h = histogram.histogram(values, null, histogram.bucketsConstantDepth, 1, null, null, 3) counts = (row.count for row in h) test.deepEqual([5, 5, 5], counts) test.done() testLog: (test) -> values = [0.05, 0.5, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1, 1], counts) test.done() testLogZero: (test) -> values = [0, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1], counts) test.done() testLogHigher: (test) -> values = [500, 5000, 50000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1], counts) test.done() testPercentile: (test) -> values = [] for i in [1..50] values.push(i * 10 - 1000) for i in [1..50] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) test.equal(buckets[49].label, '-504.90000000000003-255') h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 1) values = [] for i in [1..100] values.push(i * 10 - 1000) for i in [1..100] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 2) test.done() testZeroAndOneRows: (test) -> rows = [10] h = histogram.histogram(rows) test.equal(h[0].count, 1) rows = [] h = histogram.histogram(rows) test.equal(h[0].count, 0) test.done() testNullNaNEtc: (test) -> grades = [ {name: '<NAME>', average: 105}, # extra credit {name: '<NAME>', average: NaN}, # missed it by that much {name: '<NAME>', average: 1/0}, {name: '<NAME>', average: -1/0}, {name: '<NAME>', average: null}, {name: '<NAME>', average: undefined}, {name: '<NAME>', average: 75}, {name: '<NAME>', average: 73}, {name: '<NAME>', average: 71}, {name: '<NAME>', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') for bucket, index in buckets if index is 0 test.ok(! bucket.startOn?) else test.equal(utils.type(bucket.startOn), 'number') if index is 99 test.ok(! bucket.endBelow?) else test.equal(utils.type(bucket.endBelow), 'number') test.done() testPercentileExample: (test) -> grades = [ # A 90th percentile and above {name: '<NAME>', average: 105}, # extra credit # B 60th percentile and above {name: '<NAME>', average: 104.9}, # missed it by that much {name: '<NAME>', average: 92}, {name: '<NAME>', average: 90}, # C 10th percentile and above {name: '<NAME>', average: 87}, {name: '<NAME>', average: 87}, {name: '<NAME>', average: 75}, {name: '<NAME>', average: 73}, {name: '<NAME>', average: 71}, # F rest {name: '<NAME>', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') getGrade = (average, buckets) -> percentile = histogram.bucket(average, buckets).percentileHigherIsBetter if percentile >= 90 return 'A' else if percentile >= 60 return 'B' else if percentile >= 10 return 'C' else return 'F' test.equal(getGrade(grades[0].average, buckets), 'A') test.equal(getGrade(grades[1].average, buckets), 'B') test.equal(getGrade(grades[2].average, buckets), 'B') test.equal(getGrade(grades[3].average, buckets), 'B') test.equal(getGrade(grades[4].average, buckets), 'C') test.equal(getGrade(grades[5].average, buckets), 'C') test.equal(getGrade(grades[6].average, buckets), 'C') test.equal(getGrade(grades[7].average, buckets), 'C') test.equal(getGrade(grades[8].average, buckets), 'C') test.equal(getGrade(grades[9].average, buckets), 'F') # 0 <NAME> # 1 <NAME> # 2 <NAME> # 3 <NAME> # 4 <NAME> # 5 <NAME> # 6 <NAME> # 7 <NAME> # 8 <NAME> # 9 <NAME> test.done() testMerge: (test) -> values = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 3) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 2, label: '1-3' }] test.deepEqual(buckets, expected) buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 4) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 3, label: '1-3' }] test.deepEqual(buckets, expected) values = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, null, null, 3) expected = [ { index: 0, startOn: null, endBelow: 2, label: '< 2' }, { index: 1, startOn: 2, endBelow: null, matchingRangeIndexStart: 1, matchingRangeIndexEnd: 2, label: '>= 2'} ] test.deepEqual(buckets, expected) test.done()
true
lumenize = require('../') histogram = lumenize.histogram {utils} = require('../') rows = [ {age: 7, sex: 'M'}, {age: 25, sex: 'F'}, {age: 23, sex: 'F'}, {age: 27, sex: 'F'}, {age: 34, sex: 'M'}, {age: 55, sex: 'F'}, {age: 42, sex: 'F'}, {age: 13, sex: 'M'}, {age: 11, sex: 'M'}, {age: 23, sex: 'F'}, {age: 31, sex: 'F'}, {age: 32, sex: 'F'}, {age: 29, sex: 'M'}, {age: 16, sex: 'F'}, {age: 31, sex: 'F'}, {age: 22, sex: 'F'}, {age: 25, sex: 'F'}, ] exports.histogramTest = testDisctiminator: (test) -> h = histogram.discriminated(rows, 'age', 'sex') expected = { "categories": ["7-23", "23-39", "39-56"], "series": [ { "name": "PI:NAME:<NAME>END_PI", "data": [3, 2, 0] }, { "name": "PI:NAME:<NAME>END_PI", "data": [2, 8, 2] } ], "discriminatorValues": ["M", "F"], "stats": [ {"min": 7, "p25": 11, "median": 13, "p75": 29, "max": 34}, {"min": 16, "p25": 23, "median": 26, "p75": 31.25, "max": 55} ], "boxPlotArrays": [ [ 7, 11, 13, 29 , 34], [16, 23, 26, 31.25, 55] ] } test.ok(utils.filterMatch(expected, h)) test.ok(64 <= h.successfulClassificationRate <= 70) test.done() testControlledBucketing: (test) -> buckets = histogram.buckets([], null, null, 1, 0, 100, 100) test.equal(buckets.length, 100) for b, index in buckets test.equal(b.index, index) test.equal(10, histogram.bucket(10.234, buckets).index) test.equal(null, histogram.bucket(100, buckets)) test.done() testCalculatedBucketing: (test) -> buckets = histogram.buckets(rows, 'age', null, 1) expected = [ { index: 0, startOn: null, endBelow: 16, label: '< 16' }, { index: 1, startOn: 16, endBelow: 25, label: '16-25' }, { index: 2, startOn: 25, endBelow: 34, label: '25-34' }, { index: 3, startOn: 34, endBelow: 43, label: '34-43' }, { index: 4, startOn: 43, endBelow: null, label: '>= 43' } ] test.deepEqual(expected, buckets) test.equal(0, histogram.bucket(10.234, buckets).index) test.equal(0, histogram.bucket(-1234567, buckets).index) test.equal(2, histogram.bucket(25, buckets).index) test.equal(2, histogram.bucket(25.24, buckets).index) test.equal(4, histogram.bucket(1234567, buckets).index) h = histogram.histogramFromBuckets(rows, 'age', buckets) counts = (row.count for row in h) expected = [ 3, 4, 7, 2, 1 ] test.deepEqual(counts, expected) h2 = histogram.histogram(rows, 'age', null, 1) test.deepEqual(h, h2) test.done() testBy10: (test) -> buckets = histogram.buckets(rows, 'age', null, 10) expected = [ { index: 0, startOn: null, endBelow: 10, label: '< 10' }, { index: 1, startOn: 10, endBelow: 20, label: '10-20' }, { index: 2, startOn: 20, endBelow: 30, label: '20-30' }, { index: 3, startOn: 30, endBelow: 40, label: '30-40' }, { index: 4, startOn: 40, endBelow: null, label: '>= 40' } ] test.deepEqual(expected, buckets) test.done() testConstantDepth: (test) -> values = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 200, 300, 400, 500] h = histogram.histogram(values, null, histogram.bucketsConstantDepth, 1, null, null, 3) counts = (row.count for row in h) test.deepEqual([5, 5, 5], counts) test.done() testLog: (test) -> values = [0.05, 0.5, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1, 1], counts) test.done() testLogZero: (test) -> values = [0, 5, 50, 500, 5000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1, 1, 1], counts) test.done() testLogHigher: (test) -> values = [500, 5000, 50000] h = histogram.histogram(values, null, histogram.bucketsLog) counts = (row.count for row in h) test.deepEqual([1, 1, 1], counts) test.done() testPercentile: (test) -> values = [] for i in [1..50] values.push(i * 10 - 1000) for i in [1..50] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) test.equal(buckets[49].label, '-504.90000000000003-255') h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 1) values = [] for i in [1..100] values.push(i * 10 - 1000) for i in [1..100] values.push(i * 10 + 1000) buckets = histogram.bucketsPercentile(values) h = histogram.histogramFromBuckets(values, null, buckets) counts = (row.count for row in h) for c in counts test.equal(c, 2) test.done() testZeroAndOneRows: (test) -> rows = [10] h = histogram.histogram(rows) test.equal(h[0].count, 1) rows = [] h = histogram.histogram(rows) test.equal(h[0].count, 0) test.done() testNullNaNEtc: (test) -> grades = [ {name: 'PI:NAME:<NAME>END_PI', average: 105}, # extra credit {name: 'PI:NAME:<NAME>END_PI', average: NaN}, # missed it by that much {name: 'PI:NAME:<NAME>END_PI', average: 1/0}, {name: 'PI:NAME:<NAME>END_PI', average: -1/0}, {name: 'PI:NAME:<NAME>END_PI', average: null}, {name: 'PI:NAME:<NAME>END_PI', average: undefined}, {name: 'PI:NAME:<NAME>END_PI', average: 75}, {name: 'PI:NAME:<NAME>END_PI', average: 73}, {name: 'PI:NAME:<NAME>END_PI', average: 71}, {name: 'PI:NAME:<NAME>END_PI', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') for bucket, index in buckets if index is 0 test.ok(! bucket.startOn?) else test.equal(utils.type(bucket.startOn), 'number') if index is 99 test.ok(! bucket.endBelow?) else test.equal(utils.type(bucket.endBelow), 'number') test.done() testPercentileExample: (test) -> grades = [ # A 90th percentile and above {name: 'PI:NAME:<NAME>END_PI', average: 105}, # extra credit # B 60th percentile and above {name: 'PI:NAME:<NAME>END_PI', average: 104.9}, # missed it by that much {name: 'PI:NAME:<NAME>END_PI', average: 92}, {name: 'PI:NAME:<NAME>END_PI', average: 90}, # C 10th percentile and above {name: 'PI:NAME:<NAME>END_PI', average: 87}, {name: 'PI:NAME:<NAME>END_PI', average: 87}, {name: 'PI:NAME:<NAME>END_PI', average: 75}, {name: 'PI:NAME:<NAME>END_PI', average: 73}, {name: 'PI:NAME:<NAME>END_PI', average: 71}, # F rest {name: 'PI:NAME:<NAME>END_PI', average: 32} ] buckets = histogram.bucketsPercentile(grades, 'average') getGrade = (average, buckets) -> percentile = histogram.bucket(average, buckets).percentileHigherIsBetter if percentile >= 90 return 'A' else if percentile >= 60 return 'B' else if percentile >= 10 return 'C' else return 'F' test.equal(getGrade(grades[0].average, buckets), 'A') test.equal(getGrade(grades[1].average, buckets), 'B') test.equal(getGrade(grades[2].average, buckets), 'B') test.equal(getGrade(grades[3].average, buckets), 'B') test.equal(getGrade(grades[4].average, buckets), 'C') test.equal(getGrade(grades[5].average, buckets), 'C') test.equal(getGrade(grades[6].average, buckets), 'C') test.equal(getGrade(grades[7].average, buckets), 'C') test.equal(getGrade(grades[8].average, buckets), 'C') test.equal(getGrade(grades[9].average, buckets), 'F') # 0 PI:NAME:<NAME>END_PI # 1 PI:NAME:<NAME>END_PI # 2 PI:NAME:<NAME>END_PI # 3 PI:NAME:<NAME>END_PI # 4 PI:NAME:<NAME>END_PI # 5 PI:NAME:<NAME>END_PI # 6 PI:NAME:<NAME>END_PI # 7 PI:NAME:<NAME>END_PI # 8 PI:NAME:<NAME>END_PI # 9 PI:NAME:<NAME>END_PI test.done() testMerge: (test) -> values = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 3) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 2, label: '1-3' }] test.deepEqual(buckets, expected) buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, 1, 3, 4) expected = [{ index: 0, startOn: 1, endBelow: 3, matchingRangeIndexStart: 0, matchingRangeIndexEnd: 3, label: '1-3' }] test.deepEqual(buckets, expected) values = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] buckets = histogram.buckets(values, null, histogram.bucketsConstantDepth, null, null, null, 3) expected = [ { index: 0, startOn: null, endBelow: 2, label: '< 2' }, { index: 1, startOn: 2, endBelow: null, matchingRangeIndexStart: 1, matchingRangeIndexEnd: 2, label: '>= 2'} ] test.deepEqual(buckets, expected) test.done()
[ { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nhQEOA6GRDo3EkelYEAQAoKCfocrq8GebAg9zBQmb+jrjPU5n8wULkzedxtgRDoQP\nnmfOpVF7EbdsooQzXrzQrbTKJHkMSTNb22PQvZ6w0p/iwwiNGKA2wCKiQENKNIKq\ngLUs0VX63NV1zmxxbLc+jbBArudrJkTYdRwRXEsqEpYqTsHqGvxhG6uoZo6EdVoE\nAL2iLF5kK+qLUwylTEbLD9c748ltrWovBdso39IRGQuQ8h...
test/files/unbox_cant_verify.iced
thinq4yourself/kbpgp
1
{KeyManager,unbox} = require '../../' msg = """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org hQEOA6GRDo3EkelYEAQAoKCfocrq8GebAg9zBQmb+jrjPU5n8wULkzedxtgRDoQP nmfOpVF7EbdsooQzXrzQrbTKJHkMSTNb22PQvZ6w0p/iwwiNGKA2wCKiQENKNIKq gLUs0VX63NV1zmxxbLc+jbBArudrJkTYdRwRXEsqEpYqTsHqGvxhG6uoZo6EdVoE AL2iLF5kK+qLUwylTEbLD9c748ltrWovBdso39IRGQuQ8hxrw7I2Ikn8fUf5o/XA jWQLTN3a91D5F3aZUrEvFcmzhCKWZGQs+aiA4XOn6CbTOFTLmXQkBXyRL2WybCWH LhapT79mBKsF/ahQOoAbBpLUAR+zBC6pfNWs0qOR7jBP0sBCAaBSMJES4dG9xGyh 5of/uee3o1hNXjjE4DbW6O0NVxpMYfCOh5a/C/LbQpAQuc9yBvqCz2WY4xqMeR8U iSfEIQbh0bz5wHIuPA0HV6ra6lXZCEwqtmM2aVWHx8ooycJrECdc4Ij2rUDzuDda vhylx+yyiaH/2v5+AsIITIvxVgIPBDvb/UiDJPrpE/+AlG/S8Ii+ovxdlNegd1no xPJcCyxxgnvtyEppScPOmEysC+l+WhDB/m+JEL85oBgfpbOpMFEtXRoBXYTehOA8 G7nR8f6cvdJ/SjCr4PjIYQhV/MzAdsQvnh/15OOI/uFi+xrkZ/1Q4/uj2RTSvF4a C3MCYobj =I5z9 -----END PGP MESSAGE----- """ decryption_key = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org lQHhBFMGAboRBAC6X5nu5PxK9eaTRTGI1PUu89SYaDCNf4P82ADVwBy2gQSHZAlH d1esdd5QI2TYvfLBYHelTLk6nfO/JsPFFTPAKiyCA84GO3MBXebs8JBd5VPl3PuY YXk+xUVui/oE2bnS2PzUIPIilWwN1g6O4Olz+D70uuoGV8Og2krKUkzsRwCg+KcF fiJsfgw7to/VXdD651DSZ/0D/3N5l1kiFZvttYSu6VymG76NBnPgbRKH3sYguGPj c8E6GtJ1HrGQiGoiKN3jfYEQcOqil6/A780Yz/3yW6QK3OIJ9mIpNA8uJghWdk9E 3xhm0QrC4e3ECqQgAp5wGTfTaepsvjZxRyvu+xTQje/QMwEk3ElSOfjfq1nzjoE8 15YcBACzroFdReanDhMeRb2xjv8fjr98WqMGVjifPwJ2UEwtV8wPPGDNN63BbhYL RyRxSrUdP3LDKnnNVocNOjOEGzrRtdKRf3S1cB7b+Tc2rphublG1yGIjDeNZ9E9g mTrxr+mBm3WyFlBU3vEE+UJ3YLPQ37ai83CItaT22OY5FNAW3v4DAwIBuwNTyCVg 19Z/bQbO5Vv7myq59sSwfpLCcnjaII3oYjRYum32OrmIl1a2qPzOGpF1BfeyfT43 kin3XbQ1TWF4IFBsYW5jayAocGFzc3dvcmQgaXMgJ21tcHAnKSA8cGxhbmNrQGJl cmxpbi5hYy5kZT6IaAQTEQIAKAUCUwYBugIbAwUJEswDAAYLCQgHAwIGFQgCCQoL BBYCAwECHgECF4AACgkQkQqdjReS9VtG9ACeKf/N+cRCTEjARwbAWl9VAndRTvIA mQE+l+Mv2PF8F3TUVVYl9aAXc3JHnQFYBFMGAboQBADSFqRZ8S7vJLXKW7a22iZR 4ezEGM4Rj+3ldbsgs+BHG3qrtILdWFeiXRfh+0XgSJyhZpRfPYeKdF42I0+JvFzF QE/9pX5LsjeIgeB3P6gMi7IPrF47qWhixQ3F9EvBymlFFCXnJ/9tQsHytIhyXsZH LD9Vti6bLyz8zkuXbRT8CwADBgP+LPUlmmIuuUu7kYMCLDy5ycRGv/x8WamSZlH3 6TBY44+6xIpzOGf1Aoag+e7b+5pJE5+dFfWhfvZpGn9tdLdimA7DVxl/YCeTxoXL 25YCnOhlqVFfWMnVr7Ml3hX0Hl3WXqRQT45ZR7qzfR+8xUvl6jTwYZzYElGIJxa5 hPreyJv+AwMCAbsDU8glYNfWXpn3WV1KYjnXsZwPA1zOth8DoZBvsNFgpJCxQpfI PCeAcnTQQaF0NEEfXtNGKsbwYFdHTD7aXvAs2h05FReITwQYEQIADwUCUwYBugIb DAUJEswDAAAKCRCRCp2NF5L1Wx7xAJ0a2tmT1WhB9+7IEHVkwm0b97EbJQCfcoDT ZbLGiqgjXIjfEuNACFhveec= =66In -----END PGP PRIVATE KEY BLOCK----- """ exports.run = (T,cb) -> await KeyManager.import_from_armored_pgp { armored : decryption_key }, defer err, km T.no_error err await km.unlock_pgp {passphrase : 'mmpp' }, defer err T.no_error err await unbox { armored : msg , keyfetch : km, strict : false }, defer err, literals, warnings T.no_error err wv = warnings.warnings() T.equal wv, [ 'Problem fetching key 11e8aed7fa9fbb74: Error: No keys match the given fingerprint'], "the right warnings" T.equal literals[0].toString(), "hi, this is a test message\n", "the right message decrypted" cb()
127754
{KeyManager,unbox} = require '../../' msg = """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> G<KEY>6cvdJ/SjCr4PjIYQhV/MzAdsQvnh/15OOI/uFi+xrkZ/1Q4/uj2RTSvF4a C3MCYobj =I5z9 -----END PGP MESSAGE----- """ decryption_key = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PRIVATE KEY BLOCK----- """ exports.run = (T,cb) -> await KeyManager.import_from_armored_pgp { armored : decryption_key }, defer err, km T.no_error err await km.unlock_pgp {passphrase : '<PASSWORD>' }, defer err T.no_error err await unbox { armored : msg , keyfetch : km, strict : false }, defer err, literals, warnings T.no_error err wv = warnings.warnings() T.equal wv, [ 'Problem fetching key <KEY>: Error: No keys match the given fingerprint'], "the right warnings" T.equal literals[0].toString(), "hi, this is a test message\n", "the right message decrypted" cb()
true
{KeyManager,unbox} = require '../../' msg = """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI GPI:KEY:<KEY>END_PI6cvdJ/SjCr4PjIYQhV/MzAdsQvnh/15OOI/uFi+xrkZ/1Q4/uj2RTSvF4a C3MCYobj =I5z9 -----END PGP MESSAGE----- """ decryption_key = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PRIVATE KEY BLOCK----- """ exports.run = (T,cb) -> await KeyManager.import_from_armored_pgp { armored : decryption_key }, defer err, km T.no_error err await km.unlock_pgp {passphrase : 'PI:PASSWORD:<PASSWORD>END_PI' }, defer err T.no_error err await unbox { armored : msg , keyfetch : km, strict : false }, defer err, literals, warnings T.no_error err wv = warnings.warnings() T.equal wv, [ 'Problem fetching key PI:KEY:<KEY>END_PI: Error: No keys match the given fingerprint'], "the right warnings" T.equal literals[0].toString(), "hi, this is a test message\n", "the right message decrypted" cb()
[ { "context": "PI for NodeJS - RestifyJS\n\nCopyright (c) 2015-2021 Steven Agyekum <agyekum@posteo.de>\n\nPermission is hereby granted", "end": 158, "score": 0.9998836517333984, "start": 144, "tag": "NAME", "value": "Steven Agyekum" }, { "context": "estifyJS\n\nCopyright (c) 2015-2021...
src/addons/Fs/index.coffee
Burnett01/sys-api
6
### The MIT License (MIT) Product: System API (SysAPI) Description: A modular System-API for NodeJS - RestifyJS Copyright (c) 2015-2021 Steven Agyekum <agyekum@posteo.de> 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. ### fs = require 'fs' path = require 'path' module.exports = { fs: fs: fs path: path readFile: (path, cb) -> fs.readFile(path, 'utf8', (err, data) -> cb(err, data) ) readDir: (base, dirsonly, cb) -> ret = [] files = fs.readdirSync(base) if !files then return cb("error retrving", null) for file, index in files cur_path = path.join(base, file); stat = fs.statSync(cur_path) if(dirsonly && stat.isDirectory()) ret.push(cur_path) cb(null, ret) }
210063
### The MIT License (MIT) Product: System API (SysAPI) Description: A modular System-API for NodeJS - RestifyJS Copyright (c) 2015-2021 <NAME> <<EMAIL>> 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. ### fs = require 'fs' path = require 'path' module.exports = { fs: fs: fs path: path readFile: (path, cb) -> fs.readFile(path, 'utf8', (err, data) -> cb(err, data) ) readDir: (base, dirsonly, cb) -> ret = [] files = fs.readdirSync(base) if !files then return cb("error retrving", null) for file, index in files cur_path = path.join(base, file); stat = fs.statSync(cur_path) if(dirsonly && stat.isDirectory()) ret.push(cur_path) cb(null, ret) }
true
### The MIT License (MIT) Product: System API (SysAPI) Description: A modular System-API for NodeJS - RestifyJS Copyright (c) 2015-2021 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### fs = require 'fs' path = require 'path' module.exports = { fs: fs: fs path: path readFile: (path, cb) -> fs.readFile(path, 'utf8', (err, data) -> cb(err, data) ) readDir: (base, dirsonly, cb) -> ret = [] files = fs.readdirSync(base) if !files then return cb("error retrving", null) for file, index in files cur_path = path.join(base, file); stat = fs.statSync(cur_path) if(dirsonly && stat.isDirectory()) ret.push(cur_path) cb(null, ret) }
[ { "context": "g data.\n The model klass of the library.\n@author: Christopher Thorn <chris@koding.com>\n###\nBase = require '../base'\nm", "end": 236, "score": 0.9998779892921448, "start": 219, "tag": "NAME", "value": "Christopher Thorn" }, { "context": "klass of the library.\n@auth...
node_modules_koding/bongo/lib/model/index.coffee
ezgikaysi/koding
1
### Bongo.js Unfancy models for MongoDB (c) 2011 Koding, Inc. @class: Model @description: A class for modeling, validating, transforming, saving, finding and sharing data. The model klass of the library. @author: Christopher Thorn <chris@koding.com> ### Base = require '../base' module.exports = class Model extends Base ### @dependencies. ### # core {inspect} = require 'util' # contrib mongo = require 'mongodb' Traverse = require 'traverse' {extend, clone} = require 'underscore' MongoOp = require 'mongoop' {sequence} = require 'sinkrow' Inflector = require 'inflector' # lib JsPath = require '../jspath' ObjectId = require '../objectid' Subcollection = require '../subcollection' Validator = require '../validator' # err {SchemaError, IndexError} = require '../errortypes' ### @vars. ### # defineProperty {defineProperty} = Object # native JS casts primitives = [ String Number Boolean ] # native JS constructors natives = [ Object RegExp Date ] @inCollectionBySource =-> return this # this is a stub ### @method: property of the constructor @signature: Model.setDontAutoCastId(true|false) @description: By default, bongo will automatically cast strings that it finds inside a field called "_id" as BSON ObjectIds. This works great for most cases, and adds a layer of convenience (you don't need to import ObjectId and manually cast the value), but could potentially be problematic if you want to store another type of value in the "_id" field, which MongoDB doesn't prohibit you from doing. In that case, set this flag to true (directly, or by invoking this method with the parameter "true"). ### @setDontAutoCastId =(@dontAutoCastId=false)-> ### @method: property of the constructor @signature: setValidators(validators) @todo: implement ### @setValidators =(validators)-> ### @method: property of the constructor @signature: setBricks(validators) @todo: implement ### @setBricks =(bricks)-> ### @method: property of the constructor @signature: Model.setClient(*overload) @overload: @signature: Model.setClient(client) @param: client - an instance of the Db constructor from mongodb native. @overload: @signature: Model.setClient(url) @param: url - of the mongodb. @overload: @signature: Model.setClient(options) @param: options - initializer for the connetion. @options: - server - username - password - database - port @return: the constuctor @description: basically, it registers a connection with the Model class for the purpose of saving and finding data. @todo: do we want an instance method that will allow certain instances to have their own separate connection? It is convenient to have this registered at the class-level, for obvious reasons. It is maybe too abstract, tho. ### @setClient = do -> setClientHelper = (client)-> client .on 'close', => @emit 'dbClientDown' .on 'reconnect', => @emit 'dbClientUp' if @client_? constructor.client_ = client else defineProperty this, 'client_', value: client writable: yes unless Model.client_? Model.setClient client (overload, shouldConnect=yes)-> if overload instanceof mongo.Db setClientHelper this, overload else connStr = if 'string' is typeof overload then overload else {server, username, password, database, port} = overload auth = if username and password then "#{username}:#{password}@" else '' # TODO: this is obviously botched ^. connStr = "mongodb://#{auth}#{server}:#{port}/#{database}" mongo.MongoClient.connect connStr, (err, db) => throw err if err? setClientHelper.call this, db @emit 'dbClientReady' @getClient =-> @client_ or Model.client_ @setCollectionName =(@collection_)-> @getCollectionName =-> @collection_ or= Inflector.decapitalize Inflector.pluralize @name @getCollection =-> client = @getClient() unless client throw new Error \ """ You must set the database client for this constructor, or failing that, you must set a generic client for Model. """ client.collection @getCollectionName() getCollection:-> @constructor.getCollection() @setTeaserFields =(fieldList)-> @teaserFields = {} for field in fieldList @teaserFields[field] = yes ### @method: property of the constructor. @signature: Model.setIndexes([indexes][, callback]) @return: the constructor. ### @setIndexes = do -> ### @vars. @description: index orientation fudge tests ### ascending_ = /^(asc|ascending|1)$/i descending_ = /^(desc|descending|-1)$/i construeOrientation =(attr)-> attr = String(attr).toLowerCase() if ascending_.test attr then 1 else if descending_.test attr then -1 else 0 (indexes, callback)-> @indexes_ = indexes if 'function' is typeof indexes [callback, indexes] = [indexes, callback] constructor = @ if indexes defineProperty constructor, 'indexes', value: indexes else {indexes} = constructor unless indexes throw new Error \ """ No indexes were provided. (At least one is required.) """ figureIndex = sequence (collection, key, attrs, next)-> field = {} def = {} field[key] = null if 'string' is typeof attrs attrs = [attrs] for attr in attrs if orientation = construeOrientation attr field[key] = orientation else def[attr] = yes field[key] or= 1 # ensure the index collection.ensureIndex field, def, (err)-> next? err return return , callback @on 'dbClientReady', -> collection = constructor.getCollection() for own key, attrs of indexes figureIndex collection, key, attrs return constructor ### @method: property of the constructor. @signature: Model.setSchema(schema) ### @describeSchema =-> {keys} = Object {types, subcollections} = this (keys types ? {}) .map (slot)-> type = types[slot].name slot = slot.replace /\.0$/, -> type = [type]; '' [slot, type] .reduce (acc, [slot, type])-> JsPath.setAt acc, slot, type acc , {} ### @method: property of the constructor. @signature: Model.setSchema(schema) @param: schema - ^3 @return: the constructor. @description: sets a constructor property "schema"^3. sets constructor properties for each memo to help quicken traversal of important paths (without walking the entire schema). ### @setSchema = (schema)-> if @ is Model throw new SchemaError "Don't define a schema for Model, which is abstract." # track a reference to the constructor so we can look it up by name. constructor = @ defineProperty constructor, 'validators_', value: clone Validator.inbuilts # store a reference to the human-readable schema defineProperty constructor, 'schema', value: schema # memoize the important bits for easy lookup for own memoName, memo of constructor.getMemosOf schema defineProperty constructor, memoName, enumerable: yes value: memo @ ### @method: property of the constructor. @signature: Model.getMemosOf(schema) @param: schema - ^3 @return: the map of memos by path. @description: walk over the schema, interpreting it along the way and finding the notable items and annotations, and mapping memos of them by their paths; then return the maps of all the memos by by path by memo name. @todo: this implementation is really long. ### accessorNames = ['get','set'] @getMemosOf = (schema)-> constructor = @ memos = paths : {} filters : {} types : {} subcollections : {} subcollectionEmbeds : {} validators : {} annotations : {} primitives : {} natives : {} embeds : {} oids : {} defaults : {} setters : {} getters : {} accessorParents : {} rootProperties : [] new Traverse(schema) .forEach -> {node, path} = @ pathName = path.join '.' memos.paths[pathName] = yes # this path exists in the schema if path.length is 1 if path[0] is 'globalFlags' then #console.log node memos.rootProperties.push pathName if 'function' isnt typeof node if Array.isArray node unless node.length is 1 and 'function' is typeof node[0] throw new SchemaError \ """ Can't interpret #{constructor.name}.schema.#{pathName}. """ else memos.subcollections[pathName] = node[0] else if 'function' is typeof node.type #^5 # type is a described by the "type" property # this opens the doorway for some more complex (than type-only) annotations @update node, yes # we don't want to traverse any deeper into this thing. type = node.type if node.default? memos.defaults[pathName] = node.default if node.filter? memos.filters[pathName] = node.filter # TODO: implement leaf-level broadcastChanges # memos.broadcastChanges[pathName] = # if node.broadcastChanges? # node.broadcastChanges # else yes # memoize any validators leafValidators = [] for own validatorName, validator of constructor.validators_ options = node[validatorName] if options? leafValidators.push new Validator validatorName, validator, options # memoize validators: if leafValidators.length memos.validators[pathName] = leafValidators # memoize any accessors: for accessor in accessorNames if node[accessor] unless 'function' is typeof node[accessor] throw new SchemaError \ """ "#{accessor}" is not a function """ memos["#{accessor}ters"][path] = node[accessor] accessorParentPath = ['_data'].concat path.slice 0, -1 parent = memos.accessorParents[accessorParentPath.join '.'] or= [] parent.push path unless path in parent else if node.name #^4 type = node # memoize any annotations return unless type memos.types[pathName] = type if type is ObjectId memos.oids[pathName] = type else if type in primitives memos.primitives[pathName] = type else if type in natives memos.natives[pathName] = type else memos.annotations[pathName] = type chain = type.inheritanceChain?() if chain and Model in chain isSubcollectionType = path.slice(-1)[0] is '0' if isSubcollectionType memos.subcollectionEmbeds[path.slice(0,-1).join '.'] = type else memos.embeds[pathName] = type return # we don't want to implicitly return anything from the above if-ladder memos ### @method: property of the constructor. @signature: Model.getType(model, path) @param: model - that we're searching @param: path - that we're searching for @description: returns the type (the cast function or constructor) that correlates to the given path of the given model. @todo: reimplement. for now this will work, but it's a bit ugly, and it probably performs badly relative to the optimal. ### @getType = (model, path)-> {constructor} = model {types} = constructor return unless types if type = types[path.join '.'] return type else path = path.slice() tryPath = [] while component = path.shift() tryPath.push component if type = types[tryPath.join '.'] ref = type continue chain = ref?.inheritanceChain?() if chain and Model in chain path.push tryPath.pop() return Model.getType JsPath.getAt(model.data, tryPath), path return ### @method: property of the constructor. @signature: Model.castValue(value, type) @param: value - to be cast. @param: type - for the value to be cast as. @return: the casted value ### @castValue = (value, type)-> unless type? then # console.log '[WARN] castValue is called without a type.' else if type is Array then return value # special case this for mongo's special case else if type is Object or type is RegExp or type in primitives type value else if value instanceof type return value else if type is ObjectId or type is Date try new type value catch e then debugger else chain = type.inheritanceChain?() if chain and Model in chain if value instanceof type value else new type value else if type throw new TypeError \ """ Don't know how to cast value of type "#{value.constructor.name}" to type "#{type.name}". """ ### Querying @description: see ./find.coffee for detailed explanations. ### {@one, @all, @some, @someData, @remove, @removeById, @drop, @cursor, @findAndModify @count, @aggregate, @teasers, @hose, @mapReduce, @assure, @update, @each} = require './find' ### Model::fetchIdBySlug ### @fetchIdBySlug =(slug, callback)-> @someData {slug}, {_id:1}, {limit:1}, (err, cursor)-> if err then callback err else cursor.nextObject (err, doc)-> if err then callback err else unless doc? callback new Error "Unknown slug: #{slug}" else callback null, doc._id ### Feeding @description: see ./feed.coffee ### {@appendToFeed} = require './feed' ### @constructor. @signature: new Model(data) @param: data - with which to initialize the new instance.å @description: create a new Model instance. ### constructor:(data={})-> super data model = this defineProperty model, 'isNew', value : yes writable : yes defineProperty model, 'defaults', value: {} defineProperty model.defaults, 'beenApplied', value : no writable : yes defineProperty model, 'data', value: {} enumerable: yes # allow a maximum of 1 parent to be specified per model # TODO: perhaps we can introduce multidimensionality, but # of course it is a logical impossibility when it comes # to embedding. parent = null defineProperty model, 'parent_', writable: yes # Allow a model to know its path: defineProperty model, 'path_', writable: yes # Root node: defineProperty model, 'rootNode_', writable: yes defineProperty model, 'isRoot_', value: yes writable: yes # Support embedding models directly: isEmbedded_ = no defineProperty model, 'isEmbedded_', set :(value)-> isEmbedded_ = value get :-> isEmbedded_ # Support embedding models into "subcollections": inSubcollection_ = no defineProperty model, 'inSubcollection_', set :(value)-> inSubcollection_ = isEmbedded_ = yes get :-> inSubcollection_ # we need a place to store "setter values" defineProperty model, 'setterValues', value: {} for own parentPath, paths of model.constructor.accessorParents model.defineAccessorsOf parentPath.split('.').slice(1), paths for prop in model.constructor.rootProperties defineRootAccessorOf_ model, prop # import the data, casting values and constructing objects, as appropriate: model.set data # initialize any embedded docs. model.initEmbeds() clone:-> new @constructor @data ### @function. @signature: defineRootAccessorOf_(model, propertyName) @param: model @param: prop - the property name ### defineRootAccessorOf_ =(model, prop)-> {data, defaults} = model unless prop of model defineProperty model, prop, enumerable: yes get :-> if data[prop]? data[prop] else #model.applyDefaults() data[prop] = defaults[prop] set :(value)-> data[prop] = value ### @method. @signature: Model::defineAccessorsOf(parentPath, paths) @param: parentPath - an array of the segments of the path drilling down to, but not including the accessor itself @param: paths - an array of the complete paths of setters redundant, but convenient. this may change. @return: model @description: returns a structure object that has all accessors predefined. ### defineAccessorsOf:(parentPath, paths)-> model = @ {data} = model unless parentPath.length parent = data else parent = JsPath.getAt(data, parentPath) or {} JsPath.setAt data, parentPath, parent for path in paths assignAccessorsByPath_ model, data, parent, path #^* see below. @ ### @function. @signature: assignAccessorsByPath_(model, data, parent, path)^* @param: model - the instance. @param: data - the working tree. @param: parent - the owner of the properties we're setting. @param: path - the full path of the property we're setting. @description: a helper function for Model.defineAccessorsOf() so we don't create functions in the loop. (see above ^*) ### assignAccessorsByPath_ = (model, data, parent, path)-> pathName = path.join '.' prop = path.slice(-1)[0] setter = model.constructor.setters[pathName] getter = model.constructor.getters[pathName] defineProperty parent, prop, enumerable : yes set :(value)-> if setter value = setter.call parent, value #^** model.setterValues[pathName] = value get :-> value = model.setterValues[pathName] if getter value = getter.call parent, value #^** value # ** call accessors in the context of the parent so that # "this" is meaningful. ### @method. @signature: Model::applyDefaults() @param: callback @return: the model.defaults object @description: apply all the defaults throughout the model. call .applyDefaults() on any embedded models encountered in the walk. ### applyDefaults:(isDeep=no)-> model = @ if model.defaults? and not model.defaults.beenApplied # set default values for all fields for own defaultPath, defaultValue of model.constructor.defaults if 'function' is typeof defaultValue defaultValue = defaultValue.call model JsPath.setAt model.defaults, defaultPath, defaultValue model.defaults.beenApplied = yes if isDeep for own embedPath, embedConstructor of model.constructor.embeds JsPath.getAt(model, embedPath)?.applyDefaults() for own subcollectionEmbedPath, subcollectionEmbedAnnotation of model.constructor.subcollectionEmbeds JsPath.getAt(model, subcollectionEmbedPath)?.forEach (embed)-> embed.applyDefaults() model ### @method. @signature: Model::initEmbeds() @description: rather a heavy function that will initialize embedded models and embedded subcollections. Separated this from .applyDefaults(), because the latter should be fleet. ### initEmbeds:-> model = @ # initialize any models that are undefined. for own embedPath, embedConstructor of model.constructor.embeds embedPath = embedPath.split '.' unless JsPath.getAt(model.data, embedPath)? embed = new embedConstructor embed.path_ = embedPath embed.parent_ = JsPath.getAt model, embedPath.slice 0, -1 JsPath.setAt model.defaults, embedPath, embed # initialize any subcollections for own subcollectionEmbedPath, subcollectionEmbedAnnotation of \ model.constructor.subcollectionEmbeds subcollectionEmbedPath = subcollectionEmbedPath.split '.' unless JsPath.getAt(model.data, subcollectionEmbedPath)? parent = JsPath.getAt model, subcollectionEmbedPath.slice 0, -1 subcollection = new Subcollection \ parent, [], subcollectionEmbedAnnotation subcollection.path_ = subcollectionEmbedPath JsPath.setAt model.defaults, subcollectionEmbedPath, subcollection ### @method. @signature: Model::validate(callback) @param: callback @return: errs — that were encountered in the walk. @description: validate the data of "this", emitting events. ### validate:(callback)-> Validator.validate @, callback @validateAt =(path, value, sendMessage = no)-> [isValid, message] = do => if @paths[path]? validators = @validators[path] for { validate, message } in validators try success = validate value catch e then return [no, message] return [!!success, unless success then message] return [yes] else return [no, "unknown field"] return isValid unless sendMessage return { isValid, message } ### @constructor. @signature: Model::getClient() @returns: client - of the constructor. ### getClient:-> @constructor.getClient() ### @constructor. @signature: Model::getClient() @returns: collection name - of the constructor. ### getCollectionName:-> @constructor.getCollectionName() save: require('./save').save ### @method. @signature: Model::saveAtomically(model, callback) @throws: an schemaError ### saveAtomically:(model, callback)-> if @notRoot throw new Error \ "don't call .saveAtomically() on a non-root node." else @save callback # #getMemoByNameAndPath:(memoName, path)-> # {constructor, data} = @ # path = path.slice() # memo = constructor[memoName][path.join '.'] # return [] unless memo # prop = path.pop() # parent = JsPath.getAt data, path # [memo, prop, parent] # #setSubcollection:(path, array)-> # [annotation, prop, parent] = @getMemoByNameAndPath 'subcollections', path # subcollection = new Subcollection @, array, annotation # parent[prop] = subcollection ### @method. @signature: Model::set(data) @param: data - a map of paths to set data to. Use dot notation if you want to reach into objects, as there is no way to recursively merge JS objects without astonishing side effects. Object notation "clobbers" sibling properties. @description: sets properties to the model by path. ### set:(data)-> model = @ {constructor} = model new Traverse(data) .forEach (node)-> return if not node? if node.constructor is ObjectId @update node, yes if Array.isArray node type = constructor.subcollections[@path.join '.'] subcollection = new Subcollection model, node, type @update subcollection else if @path.length type = Model.getType model, @path if type and type isnt Object @update Model.castValue(node, type), yes return # if @node instanceof Model # @update @node, yes # traverse again to set the path # TODO: try to optimize this so we only need to walk once. new Traverse(data) .forEach (node)-> if node instanceof Model # I am not 100% convinced that this assumption will hold true: node.isRoot_ = no node.rootNode_ = model node.path_ = @path node.parent_ = @parent.node @update node return #@node for own path, value of data JsPath.setAt model.data, path, value # TODO: this is a bit ugly: model._id = data._id if data._id ### @function. @signature: attachOuterAccessor_(model, path) @param: model @param: path - the path (inside data) we want to alias. @description: helper to add accessors onto the root level of the model to access the members on the root level of the model's data object. ### attachOuterAccessor_ = (model, path)-> defineProperty model, path, enumerable: yes get :-> model.data[path] set :(value)-> model.data[path] = value shouldBeSaved:(path)-> if path is '_id' then no else console.log path; yes ### @method. @signature Model::get() @description: traverse the model (which implicitly will call any getters), prune nulls and undefineds, return the results of the traversal. ### get:(shouldPrune=no)-> model = @ model.applyDefaults() data = extend {}, model.defaults, if shouldPrune then model.prune() else model.data # this will call the getters and return a new object new Traverse(data).forEach -> if @node instanceof Subcollection @update [].slice.call @node else @update @node?.get?() or @node getId:-> # TODO: implement plugins id = @data._id if 'string' is typeof id new ObjectId id else id equals:(model, deep=no)-> unless deep @getId()?.equals? id if id = model?.getId?() # TODO: I'm not currently interested in "deep", but it might be needed later CT prune:do -> applyFilter =(node, constructor, pathName)-> filter = constructor.filters[pathName] filter node (isHard=no)-> model = @ {constructor} = model method = if isHard then 'forEach' else 'map' prunedData = new Traverse(model.data)[method] (node)-> pathName = @path.join '.' if node instanceof ObjectId @update ObjectId(node+''), yes else if pathName is '_id' # it's the mongo ObjectId @update node, yes else if pathName of constructor.embeds # it's a directly-embedded doc @update node.prune(), yes else if pathName of constructor.subcollectionEmbeds prunedCollection = (embed.prune(isHard) for embed in node) # it's a subcollection of embeds @update prunedCollection, yes else if pathName of constructor.paths # it's a schematical path if pathName of constructor.filters # it needs filtered @update applyFilter(node), yes else if pathName.length # it's schematical @update node, yes else @update node else # never heard of it; pruning! @remove() prunedData updateInstances:(atomically)-> prunedModifier = {} for own op of atomically prunedModifier[op] = {} for own field, val of atomically[op] unless field in ['snapshot','snapshotIds'] # TODO: this is a one-off hack. prunedModifier[op][field] = val if @constructor.getBroadcastable() @emit 'updateInstance', prunedModifier || @ update:(atomically, callback=->)-> model = @ if 'function' is typeof atomically callback = atomically atomically = undefined unless atomically Model::save.call model, (err)-> if err callback err else model.updateInstances() callback null else collection = model.constructor.getCollection() update = _id: model.getId() for own operator, operation of atomically when operator is '$set' for own path, value of operation splittedPath = path.split '.' type = Model.getType model, splittedPath validators = model.constructor.validators[path] if validators?.length for { validate, name, message } in validators when not validate value return callback { message, name, value } if type and type isnt Object value = Model.castValue value, type operation[path] = value { operation } = new MongoOp(atomically) .map(model.applySetters.bind(model)) .applyTo(model) # first update the one in memory. collection.update update, operation, (err)-> # then update the one in the database. if err callback err else model.updateInstances(atomically) callback null applySetters: (operator, operation) -> out = {} for own k, v of operation setter = @constructor.setters[k] if setter? v = setter.call this, v out[k] = v return out @_hardDelete = @remove remove:(callback)-> if @constructor.softDelete Trash = require '../trash' Trash.create this @constructor._hardDelete _id: @getId(), callback @remove:(selector, callback)-> if @softDelete Trash = require '../trash' @some selector, {}, (err, rows)=> Trash.create row for row in rows @_hardDelete selector, callback else @_hardDelete selector, callback ['getAt','setAt','deleteAt'] .forEach (method)=> @::[method] =(path)-> JsPath[method].call null, @data, path ### Footnotes: 1 - ad hoc properties not associated with a schema are fine, but we don't persist them to Mongo. 2 - apply defaults / validations on output (not here). 3 - the human-readable description of the schema, including "type annotations" (JS constructors/primitive casts, really) and validation functions (including some sugared inbuilt ones). 4 - if it has a name, it may be a constructor; this might be botched. 5 - because of overloading, we need to make sure this isn't a field called "validator". 6 - defaults are applied on output. 7 - normal validators only take 1 argument: a value which needs to be validated. There are also a class of so-called "curried" validators that take 2 arguments (e.g. pattern and enum): the first is arbitrarily supplied during schema creation, and the second is the value described above which needs to be validated. ###
37812
### Bongo.js Unfancy models for MongoDB (c) 2011 Koding, Inc. @class: Model @description: A class for modeling, validating, transforming, saving, finding and sharing data. The model klass of the library. @author: <NAME> <<EMAIL>> ### Base = require '../base' module.exports = class Model extends Base ### @dependencies. ### # core {inspect} = require 'util' # contrib mongo = require 'mongodb' Traverse = require 'traverse' {extend, clone} = require 'underscore' MongoOp = require 'mongoop' {sequence} = require 'sinkrow' Inflector = require 'inflector' # lib JsPath = require '../jspath' ObjectId = require '../objectid' Subcollection = require '../subcollection' Validator = require '../validator' # err {SchemaError, IndexError} = require '../errortypes' ### @vars. ### # defineProperty {defineProperty} = Object # native JS casts primitives = [ String Number Boolean ] # native JS constructors natives = [ Object RegExp Date ] @inCollectionBySource =-> return this # this is a stub ### @method: property of the constructor @signature: Model.setDontAutoCastId(true|false) @description: By default, bongo will automatically cast strings that it finds inside a field called "_id" as BSON ObjectIds. This works great for most cases, and adds a layer of convenience (you don't need to import ObjectId and manually cast the value), but could potentially be problematic if you want to store another type of value in the "_id" field, which MongoDB doesn't prohibit you from doing. In that case, set this flag to true (directly, or by invoking this method with the parameter "true"). ### @setDontAutoCastId =(@dontAutoCastId=false)-> ### @method: property of the constructor @signature: setValidators(validators) @todo: implement ### @setValidators =(validators)-> ### @method: property of the constructor @signature: setBricks(validators) @todo: implement ### @setBricks =(bricks)-> ### @method: property of the constructor @signature: Model.setClient(*overload) @overload: @signature: Model.setClient(client) @param: client - an instance of the Db constructor from mongodb native. @overload: @signature: Model.setClient(url) @param: url - of the mongodb. @overload: @signature: Model.setClient(options) @param: options - initializer for the connetion. @options: - server - username - password - database - port @return: the constuctor @description: basically, it registers a connection with the Model class for the purpose of saving and finding data. @todo: do we want an instance method that will allow certain instances to have their own separate connection? It is convenient to have this registered at the class-level, for obvious reasons. It is maybe too abstract, tho. ### @setClient = do -> setClientHelper = (client)-> client .on 'close', => @emit 'dbClientDown' .on 'reconnect', => @emit 'dbClientUp' if @client_? constructor.client_ = client else defineProperty this, 'client_', value: client writable: yes unless Model.client_? Model.setClient client (overload, shouldConnect=yes)-> if overload instanceof mongo.Db setClientHelper this, overload else connStr = if 'string' is typeof overload then overload else {server, username, password, database, port} = overload auth = if username and password then "#{username}:#{password}@" else '' # TODO: this is obviously botched ^. connStr = "mongodb://#{auth}#{server}:#{port}/#{database}" mongo.MongoClient.connect connStr, (err, db) => throw err if err? setClientHelper.call this, db @emit 'dbClientReady' @getClient =-> @client_ or Model.client_ @setCollectionName =(@collection_)-> @getCollectionName =-> @collection_ or= Inflector.decapitalize Inflector.pluralize @name @getCollection =-> client = @getClient() unless client throw new Error \ """ You must set the database client for this constructor, or failing that, you must set a generic client for Model. """ client.collection @getCollectionName() getCollection:-> @constructor.getCollection() @setTeaserFields =(fieldList)-> @teaserFields = {} for field in fieldList @teaserFields[field] = yes ### @method: property of the constructor. @signature: Model.setIndexes([indexes][, callback]) @return: the constructor. ### @setIndexes = do -> ### @vars. @description: index orientation fudge tests ### ascending_ = /^(asc|ascending|1)$/i descending_ = /^(desc|descending|-1)$/i construeOrientation =(attr)-> attr = String(attr).toLowerCase() if ascending_.test attr then 1 else if descending_.test attr then -1 else 0 (indexes, callback)-> @indexes_ = indexes if 'function' is typeof indexes [callback, indexes] = [indexes, callback] constructor = @ if indexes defineProperty constructor, 'indexes', value: indexes else {indexes} = constructor unless indexes throw new Error \ """ No indexes were provided. (At least one is required.) """ figureIndex = sequence (collection, key, attrs, next)-> field = {} def = {} field[key] = null if 'string' is typeof attrs attrs = [attrs] for attr in attrs if orientation = construeOrientation attr field[key] = orientation else def[attr] = yes field[key] or= 1 # ensure the index collection.ensureIndex field, def, (err)-> next? err return return , callback @on 'dbClientReady', -> collection = constructor.getCollection() for own key, attrs of indexes figureIndex collection, key, attrs return constructor ### @method: property of the constructor. @signature: Model.setSchema(schema) ### @describeSchema =-> {keys} = Object {types, subcollections} = this (keys types ? {}) .map (slot)-> type = types[slot].name slot = slot.replace /\.0$/, -> type = [type]; '' [slot, type] .reduce (acc, [slot, type])-> JsPath.setAt acc, slot, type acc , {} ### @method: property of the constructor. @signature: Model.setSchema(schema) @param: schema - ^3 @return: the constructor. @description: sets a constructor property "schema"^3. sets constructor properties for each memo to help quicken traversal of important paths (without walking the entire schema). ### @setSchema = (schema)-> if @ is Model throw new SchemaError "Don't define a schema for Model, which is abstract." # track a reference to the constructor so we can look it up by name. constructor = @ defineProperty constructor, 'validators_', value: clone Validator.inbuilts # store a reference to the human-readable schema defineProperty constructor, 'schema', value: schema # memoize the important bits for easy lookup for own memoName, memo of constructor.getMemosOf schema defineProperty constructor, memoName, enumerable: yes value: memo @ ### @method: property of the constructor. @signature: Model.getMemosOf(schema) @param: schema - ^3 @return: the map of memos by path. @description: walk over the schema, interpreting it along the way and finding the notable items and annotations, and mapping memos of them by their paths; then return the maps of all the memos by by path by memo name. @todo: this implementation is really long. ### accessorNames = ['get','set'] @getMemosOf = (schema)-> constructor = @ memos = paths : {} filters : {} types : {} subcollections : {} subcollectionEmbeds : {} validators : {} annotations : {} primitives : {} natives : {} embeds : {} oids : {} defaults : {} setters : {} getters : {} accessorParents : {} rootProperties : [] new Traverse(schema) .forEach -> {node, path} = @ pathName = path.join '.' memos.paths[pathName] = yes # this path exists in the schema if path.length is 1 if path[0] is 'globalFlags' then #console.log node memos.rootProperties.push pathName if 'function' isnt typeof node if Array.isArray node unless node.length is 1 and 'function' is typeof node[0] throw new SchemaError \ """ Can't interpret #{constructor.name}.schema.#{pathName}. """ else memos.subcollections[pathName] = node[0] else if 'function' is typeof node.type #^5 # type is a described by the "type" property # this opens the doorway for some more complex (than type-only) annotations @update node, yes # we don't want to traverse any deeper into this thing. type = node.type if node.default? memos.defaults[pathName] = node.default if node.filter? memos.filters[pathName] = node.filter # TODO: implement leaf-level broadcastChanges # memos.broadcastChanges[pathName] = # if node.broadcastChanges? # node.broadcastChanges # else yes # memoize any validators leafValidators = [] for own validatorName, validator of constructor.validators_ options = node[validatorName] if options? leafValidators.push new Validator validatorName, validator, options # memoize validators: if leafValidators.length memos.validators[pathName] = leafValidators # memoize any accessors: for accessor in accessorNames if node[accessor] unless 'function' is typeof node[accessor] throw new SchemaError \ """ "#{accessor}" is not a function """ memos["#{accessor}ters"][path] = node[accessor] accessorParentPath = ['_data'].concat path.slice 0, -1 parent = memos.accessorParents[accessorParentPath.join '.'] or= [] parent.push path unless path in parent else if node.name #^4 type = node # memoize any annotations return unless type memos.types[pathName] = type if type is ObjectId memos.oids[pathName] = type else if type in primitives memos.primitives[pathName] = type else if type in natives memos.natives[pathName] = type else memos.annotations[pathName] = type chain = type.inheritanceChain?() if chain and Model in chain isSubcollectionType = path.slice(-1)[0] is '0' if isSubcollectionType memos.subcollectionEmbeds[path.slice(0,-1).join '.'] = type else memos.embeds[pathName] = type return # we don't want to implicitly return anything from the above if-ladder memos ### @method: property of the constructor. @signature: Model.getType(model, path) @param: model - that we're searching @param: path - that we're searching for @description: returns the type (the cast function or constructor) that correlates to the given path of the given model. @todo: reimplement. for now this will work, but it's a bit ugly, and it probably performs badly relative to the optimal. ### @getType = (model, path)-> {constructor} = model {types} = constructor return unless types if type = types[path.join '.'] return type else path = path.slice() tryPath = [] while component = path.shift() tryPath.push component if type = types[tryPath.join '.'] ref = type continue chain = ref?.inheritanceChain?() if chain and Model in chain path.push tryPath.pop() return Model.getType JsPath.getAt(model.data, tryPath), path return ### @method: property of the constructor. @signature: Model.castValue(value, type) @param: value - to be cast. @param: type - for the value to be cast as. @return: the casted value ### @castValue = (value, type)-> unless type? then # console.log '[WARN] castValue is called without a type.' else if type is Array then return value # special case this for mongo's special case else if type is Object or type is RegExp or type in primitives type value else if value instanceof type return value else if type is ObjectId or type is Date try new type value catch e then debugger else chain = type.inheritanceChain?() if chain and Model in chain if value instanceof type value else new type value else if type throw new TypeError \ """ Don't know how to cast value of type "#{value.constructor.name}" to type "#{type.name}". """ ### Querying @description: see ./find.coffee for detailed explanations. ### {@one, @all, @some, @someData, @remove, @removeById, @drop, @cursor, @findAndModify @count, @aggregate, @teasers, @hose, @mapReduce, @assure, @update, @each} = require './find' ### Model::fetchIdBySlug ### @fetchIdBySlug =(slug, callback)-> @someData {slug}, {_id:1}, {limit:1}, (err, cursor)-> if err then callback err else cursor.nextObject (err, doc)-> if err then callback err else unless doc? callback new Error "Unknown slug: #{slug}" else callback null, doc._id ### Feeding @description: see ./feed.coffee ### {@appendToFeed} = require './feed' ### @constructor. @signature: new Model(data) @param: data - with which to initialize the new instance.å @description: create a new Model instance. ### constructor:(data={})-> super data model = this defineProperty model, 'isNew', value : yes writable : yes defineProperty model, 'defaults', value: {} defineProperty model.defaults, 'beenApplied', value : no writable : yes defineProperty model, 'data', value: {} enumerable: yes # allow a maximum of 1 parent to be specified per model # TODO: perhaps we can introduce multidimensionality, but # of course it is a logical impossibility when it comes # to embedding. parent = null defineProperty model, 'parent_', writable: yes # Allow a model to know its path: defineProperty model, 'path_', writable: yes # Root node: defineProperty model, 'rootNode_', writable: yes defineProperty model, 'isRoot_', value: yes writable: yes # Support embedding models directly: isEmbedded_ = no defineProperty model, 'isEmbedded_', set :(value)-> isEmbedded_ = value get :-> isEmbedded_ # Support embedding models into "subcollections": inSubcollection_ = no defineProperty model, 'inSubcollection_', set :(value)-> inSubcollection_ = isEmbedded_ = yes get :-> inSubcollection_ # we need a place to store "setter values" defineProperty model, 'setterValues', value: {} for own parentPath, paths of model.constructor.accessorParents model.defineAccessorsOf parentPath.split('.').slice(1), paths for prop in model.constructor.rootProperties defineRootAccessorOf_ model, prop # import the data, casting values and constructing objects, as appropriate: model.set data # initialize any embedded docs. model.initEmbeds() clone:-> new @constructor @data ### @function. @signature: defineRootAccessorOf_(model, propertyName) @param: model @param: prop - the property name ### defineRootAccessorOf_ =(model, prop)-> {data, defaults} = model unless prop of model defineProperty model, prop, enumerable: yes get :-> if data[prop]? data[prop] else #model.applyDefaults() data[prop] = defaults[prop] set :(value)-> data[prop] = value ### @method. @signature: Model::defineAccessorsOf(parentPath, paths) @param: parentPath - an array of the segments of the path drilling down to, but not including the accessor itself @param: paths - an array of the complete paths of setters redundant, but convenient. this may change. @return: model @description: returns a structure object that has all accessors predefined. ### defineAccessorsOf:(parentPath, paths)-> model = @ {data} = model unless parentPath.length parent = data else parent = JsPath.getAt(data, parentPath) or {} JsPath.setAt data, parentPath, parent for path in paths assignAccessorsByPath_ model, data, parent, path #^* see below. @ ### @function. @signature: assignAccessorsByPath_(model, data, parent, path)^* @param: model - the instance. @param: data - the working tree. @param: parent - the owner of the properties we're setting. @param: path - the full path of the property we're setting. @description: a helper function for Model.defineAccessorsOf() so we don't create functions in the loop. (see above ^*) ### assignAccessorsByPath_ = (model, data, parent, path)-> pathName = path.join '.' prop = path.slice(-1)[0] setter = model.constructor.setters[pathName] getter = model.constructor.getters[pathName] defineProperty parent, prop, enumerable : yes set :(value)-> if setter value = setter.call parent, value #^** model.setterValues[pathName] = value get :-> value = model.setterValues[pathName] if getter value = getter.call parent, value #^** value # ** call accessors in the context of the parent so that # "this" is meaningful. ### @method. @signature: Model::applyDefaults() @param: callback @return: the model.defaults object @description: apply all the defaults throughout the model. call .applyDefaults() on any embedded models encountered in the walk. ### applyDefaults:(isDeep=no)-> model = @ if model.defaults? and not model.defaults.beenApplied # set default values for all fields for own defaultPath, defaultValue of model.constructor.defaults if 'function' is typeof defaultValue defaultValue = defaultValue.call model JsPath.setAt model.defaults, defaultPath, defaultValue model.defaults.beenApplied = yes if isDeep for own embedPath, embedConstructor of model.constructor.embeds JsPath.getAt(model, embedPath)?.applyDefaults() for own subcollectionEmbedPath, subcollectionEmbedAnnotation of model.constructor.subcollectionEmbeds JsPath.getAt(model, subcollectionEmbedPath)?.forEach (embed)-> embed.applyDefaults() model ### @method. @signature: Model::initEmbeds() @description: rather a heavy function that will initialize embedded models and embedded subcollections. Separated this from .applyDefaults(), because the latter should be fleet. ### initEmbeds:-> model = @ # initialize any models that are undefined. for own embedPath, embedConstructor of model.constructor.embeds embedPath = embedPath.split '.' unless JsPath.getAt(model.data, embedPath)? embed = new embedConstructor embed.path_ = embedPath embed.parent_ = JsPath.getAt model, embedPath.slice 0, -1 JsPath.setAt model.defaults, embedPath, embed # initialize any subcollections for own subcollectionEmbedPath, subcollectionEmbedAnnotation of \ model.constructor.subcollectionEmbeds subcollectionEmbedPath = subcollectionEmbedPath.split '.' unless JsPath.getAt(model.data, subcollectionEmbedPath)? parent = JsPath.getAt model, subcollectionEmbedPath.slice 0, -1 subcollection = new Subcollection \ parent, [], subcollectionEmbedAnnotation subcollection.path_ = subcollectionEmbedPath JsPath.setAt model.defaults, subcollectionEmbedPath, subcollection ### @method. @signature: Model::validate(callback) @param: callback @return: errs — that were encountered in the walk. @description: validate the data of "this", emitting events. ### validate:(callback)-> Validator.validate @, callback @validateAt =(path, value, sendMessage = no)-> [isValid, message] = do => if @paths[path]? validators = @validators[path] for { validate, message } in validators try success = validate value catch e then return [no, message] return [!!success, unless success then message] return [yes] else return [no, "unknown field"] return isValid unless sendMessage return { isValid, message } ### @constructor. @signature: Model::getClient() @returns: client - of the constructor. ### getClient:-> @constructor.getClient() ### @constructor. @signature: Model::getClient() @returns: collection name - of the constructor. ### getCollectionName:-> @constructor.getCollectionName() save: require('./save').save ### @method. @signature: Model::saveAtomically(model, callback) @throws: an schemaError ### saveAtomically:(model, callback)-> if @notRoot throw new Error \ "don't call .saveAtomically() on a non-root node." else @save callback # #getMemoByNameAndPath:(memoName, path)-> # {constructor, data} = @ # path = path.slice() # memo = constructor[memoName][path.join '.'] # return [] unless memo # prop = path.pop() # parent = JsPath.getAt data, path # [memo, prop, parent] # #setSubcollection:(path, array)-> # [annotation, prop, parent] = @getMemoByNameAndPath 'subcollections', path # subcollection = new Subcollection @, array, annotation # parent[prop] = subcollection ### @method. @signature: Model::set(data) @param: data - a map of paths to set data to. Use dot notation if you want to reach into objects, as there is no way to recursively merge JS objects without astonishing side effects. Object notation "clobbers" sibling properties. @description: sets properties to the model by path. ### set:(data)-> model = @ {constructor} = model new Traverse(data) .forEach (node)-> return if not node? if node.constructor is ObjectId @update node, yes if Array.isArray node type = constructor.subcollections[@path.join '.'] subcollection = new Subcollection model, node, type @update subcollection else if @path.length type = Model.getType model, @path if type and type isnt Object @update Model.castValue(node, type), yes return # if @node instanceof Model # @update @node, yes # traverse again to set the path # TODO: try to optimize this so we only need to walk once. new Traverse(data) .forEach (node)-> if node instanceof Model # I am not 100% convinced that this assumption will hold true: node.isRoot_ = no node.rootNode_ = model node.path_ = @path node.parent_ = @parent.node @update node return #@node for own path, value of data JsPath.setAt model.data, path, value # TODO: this is a bit ugly: model._id = data._id if data._id ### @function. @signature: attachOuterAccessor_(model, path) @param: model @param: path - the path (inside data) we want to alias. @description: helper to add accessors onto the root level of the model to access the members on the root level of the model's data object. ### attachOuterAccessor_ = (model, path)-> defineProperty model, path, enumerable: yes get :-> model.data[path] set :(value)-> model.data[path] = value shouldBeSaved:(path)-> if path is '_id' then no else console.log path; yes ### @method. @signature Model::get() @description: traverse the model (which implicitly will call any getters), prune nulls and undefineds, return the results of the traversal. ### get:(shouldPrune=no)-> model = @ model.applyDefaults() data = extend {}, model.defaults, if shouldPrune then model.prune() else model.data # this will call the getters and return a new object new Traverse(data).forEach -> if @node instanceof Subcollection @update [].slice.call @node else @update @node?.get?() or @node getId:-> # TODO: implement plugins id = @data._id if 'string' is typeof id new ObjectId id else id equals:(model, deep=no)-> unless deep @getId()?.equals? id if id = model?.getId?() # TODO: I'm not currently interested in "deep", but it might be needed later CT prune:do -> applyFilter =(node, constructor, pathName)-> filter = constructor.filters[pathName] filter node (isHard=no)-> model = @ {constructor} = model method = if isHard then 'forEach' else 'map' prunedData = new Traverse(model.data)[method] (node)-> pathName = @path.join '.' if node instanceof ObjectId @update ObjectId(node+''), yes else if pathName is '_id' # it's the mongo ObjectId @update node, yes else if pathName of constructor.embeds # it's a directly-embedded doc @update node.prune(), yes else if pathName of constructor.subcollectionEmbeds prunedCollection = (embed.prune(isHard) for embed in node) # it's a subcollection of embeds @update prunedCollection, yes else if pathName of constructor.paths # it's a schematical path if pathName of constructor.filters # it needs filtered @update applyFilter(node), yes else if pathName.length # it's schematical @update node, yes else @update node else # never heard of it; pruning! @remove() prunedData updateInstances:(atomically)-> prunedModifier = {} for own op of atomically prunedModifier[op] = {} for own field, val of atomically[op] unless field in ['snapshot','snapshotIds'] # TODO: this is a one-off hack. prunedModifier[op][field] = val if @constructor.getBroadcastable() @emit 'updateInstance', prunedModifier || @ update:(atomically, callback=->)-> model = @ if 'function' is typeof atomically callback = atomically atomically = undefined unless atomically Model::save.call model, (err)-> if err callback err else model.updateInstances() callback null else collection = model.constructor.getCollection() update = _id: model.getId() for own operator, operation of atomically when operator is '$set' for own path, value of operation splittedPath = path.split '.' type = Model.getType model, splittedPath validators = model.constructor.validators[path] if validators?.length for { validate, name, message } in validators when not validate value return callback { message, name, value } if type and type isnt Object value = Model.castValue value, type operation[path] = value { operation } = new MongoOp(atomically) .map(model.applySetters.bind(model)) .applyTo(model) # first update the one in memory. collection.update update, operation, (err)-> # then update the one in the database. if err callback err else model.updateInstances(atomically) callback null applySetters: (operator, operation) -> out = {} for own k, v of operation setter = @constructor.setters[k] if setter? v = setter.call this, v out[k] = v return out @_hardDelete = @remove remove:(callback)-> if @constructor.softDelete Trash = require '../trash' Trash.create this @constructor._hardDelete _id: @getId(), callback @remove:(selector, callback)-> if @softDelete Trash = require '../trash' @some selector, {}, (err, rows)=> Trash.create row for row in rows @_hardDelete selector, callback else @_hardDelete selector, callback ['getAt','setAt','deleteAt'] .forEach (method)=> @::[method] =(path)-> JsPath[method].call null, @data, path ### Footnotes: 1 - ad hoc properties not associated with a schema are fine, but we don't persist them to Mongo. 2 - apply defaults / validations on output (not here). 3 - the human-readable description of the schema, including "type annotations" (JS constructors/primitive casts, really) and validation functions (including some sugared inbuilt ones). 4 - if it has a name, it may be a constructor; this might be botched. 5 - because of overloading, we need to make sure this isn't a field called "validator". 6 - defaults are applied on output. 7 - normal validators only take 1 argument: a value which needs to be validated. There are also a class of so-called "curried" validators that take 2 arguments (e.g. pattern and enum): the first is arbitrarily supplied during schema creation, and the second is the value described above which needs to be validated. ###
true
### Bongo.js Unfancy models for MongoDB (c) 2011 Koding, Inc. @class: Model @description: A class for modeling, validating, transforming, saving, finding and sharing data. The model klass of the library. @author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### Base = require '../base' module.exports = class Model extends Base ### @dependencies. ### # core {inspect} = require 'util' # contrib mongo = require 'mongodb' Traverse = require 'traverse' {extend, clone} = require 'underscore' MongoOp = require 'mongoop' {sequence} = require 'sinkrow' Inflector = require 'inflector' # lib JsPath = require '../jspath' ObjectId = require '../objectid' Subcollection = require '../subcollection' Validator = require '../validator' # err {SchemaError, IndexError} = require '../errortypes' ### @vars. ### # defineProperty {defineProperty} = Object # native JS casts primitives = [ String Number Boolean ] # native JS constructors natives = [ Object RegExp Date ] @inCollectionBySource =-> return this # this is a stub ### @method: property of the constructor @signature: Model.setDontAutoCastId(true|false) @description: By default, bongo will automatically cast strings that it finds inside a field called "_id" as BSON ObjectIds. This works great for most cases, and adds a layer of convenience (you don't need to import ObjectId and manually cast the value), but could potentially be problematic if you want to store another type of value in the "_id" field, which MongoDB doesn't prohibit you from doing. In that case, set this flag to true (directly, or by invoking this method with the parameter "true"). ### @setDontAutoCastId =(@dontAutoCastId=false)-> ### @method: property of the constructor @signature: setValidators(validators) @todo: implement ### @setValidators =(validators)-> ### @method: property of the constructor @signature: setBricks(validators) @todo: implement ### @setBricks =(bricks)-> ### @method: property of the constructor @signature: Model.setClient(*overload) @overload: @signature: Model.setClient(client) @param: client - an instance of the Db constructor from mongodb native. @overload: @signature: Model.setClient(url) @param: url - of the mongodb. @overload: @signature: Model.setClient(options) @param: options - initializer for the connetion. @options: - server - username - password - database - port @return: the constuctor @description: basically, it registers a connection with the Model class for the purpose of saving and finding data. @todo: do we want an instance method that will allow certain instances to have their own separate connection? It is convenient to have this registered at the class-level, for obvious reasons. It is maybe too abstract, tho. ### @setClient = do -> setClientHelper = (client)-> client .on 'close', => @emit 'dbClientDown' .on 'reconnect', => @emit 'dbClientUp' if @client_? constructor.client_ = client else defineProperty this, 'client_', value: client writable: yes unless Model.client_? Model.setClient client (overload, shouldConnect=yes)-> if overload instanceof mongo.Db setClientHelper this, overload else connStr = if 'string' is typeof overload then overload else {server, username, password, database, port} = overload auth = if username and password then "#{username}:#{password}@" else '' # TODO: this is obviously botched ^. connStr = "mongodb://#{auth}#{server}:#{port}/#{database}" mongo.MongoClient.connect connStr, (err, db) => throw err if err? setClientHelper.call this, db @emit 'dbClientReady' @getClient =-> @client_ or Model.client_ @setCollectionName =(@collection_)-> @getCollectionName =-> @collection_ or= Inflector.decapitalize Inflector.pluralize @name @getCollection =-> client = @getClient() unless client throw new Error \ """ You must set the database client for this constructor, or failing that, you must set a generic client for Model. """ client.collection @getCollectionName() getCollection:-> @constructor.getCollection() @setTeaserFields =(fieldList)-> @teaserFields = {} for field in fieldList @teaserFields[field] = yes ### @method: property of the constructor. @signature: Model.setIndexes([indexes][, callback]) @return: the constructor. ### @setIndexes = do -> ### @vars. @description: index orientation fudge tests ### ascending_ = /^(asc|ascending|1)$/i descending_ = /^(desc|descending|-1)$/i construeOrientation =(attr)-> attr = String(attr).toLowerCase() if ascending_.test attr then 1 else if descending_.test attr then -1 else 0 (indexes, callback)-> @indexes_ = indexes if 'function' is typeof indexes [callback, indexes] = [indexes, callback] constructor = @ if indexes defineProperty constructor, 'indexes', value: indexes else {indexes} = constructor unless indexes throw new Error \ """ No indexes were provided. (At least one is required.) """ figureIndex = sequence (collection, key, attrs, next)-> field = {} def = {} field[key] = null if 'string' is typeof attrs attrs = [attrs] for attr in attrs if orientation = construeOrientation attr field[key] = orientation else def[attr] = yes field[key] or= 1 # ensure the index collection.ensureIndex field, def, (err)-> next? err return return , callback @on 'dbClientReady', -> collection = constructor.getCollection() for own key, attrs of indexes figureIndex collection, key, attrs return constructor ### @method: property of the constructor. @signature: Model.setSchema(schema) ### @describeSchema =-> {keys} = Object {types, subcollections} = this (keys types ? {}) .map (slot)-> type = types[slot].name slot = slot.replace /\.0$/, -> type = [type]; '' [slot, type] .reduce (acc, [slot, type])-> JsPath.setAt acc, slot, type acc , {} ### @method: property of the constructor. @signature: Model.setSchema(schema) @param: schema - ^3 @return: the constructor. @description: sets a constructor property "schema"^3. sets constructor properties for each memo to help quicken traversal of important paths (without walking the entire schema). ### @setSchema = (schema)-> if @ is Model throw new SchemaError "Don't define a schema for Model, which is abstract." # track a reference to the constructor so we can look it up by name. constructor = @ defineProperty constructor, 'validators_', value: clone Validator.inbuilts # store a reference to the human-readable schema defineProperty constructor, 'schema', value: schema # memoize the important bits for easy lookup for own memoName, memo of constructor.getMemosOf schema defineProperty constructor, memoName, enumerable: yes value: memo @ ### @method: property of the constructor. @signature: Model.getMemosOf(schema) @param: schema - ^3 @return: the map of memos by path. @description: walk over the schema, interpreting it along the way and finding the notable items and annotations, and mapping memos of them by their paths; then return the maps of all the memos by by path by memo name. @todo: this implementation is really long. ### accessorNames = ['get','set'] @getMemosOf = (schema)-> constructor = @ memos = paths : {} filters : {} types : {} subcollections : {} subcollectionEmbeds : {} validators : {} annotations : {} primitives : {} natives : {} embeds : {} oids : {} defaults : {} setters : {} getters : {} accessorParents : {} rootProperties : [] new Traverse(schema) .forEach -> {node, path} = @ pathName = path.join '.' memos.paths[pathName] = yes # this path exists in the schema if path.length is 1 if path[0] is 'globalFlags' then #console.log node memos.rootProperties.push pathName if 'function' isnt typeof node if Array.isArray node unless node.length is 1 and 'function' is typeof node[0] throw new SchemaError \ """ Can't interpret #{constructor.name}.schema.#{pathName}. """ else memos.subcollections[pathName] = node[0] else if 'function' is typeof node.type #^5 # type is a described by the "type" property # this opens the doorway for some more complex (than type-only) annotations @update node, yes # we don't want to traverse any deeper into this thing. type = node.type if node.default? memos.defaults[pathName] = node.default if node.filter? memos.filters[pathName] = node.filter # TODO: implement leaf-level broadcastChanges # memos.broadcastChanges[pathName] = # if node.broadcastChanges? # node.broadcastChanges # else yes # memoize any validators leafValidators = [] for own validatorName, validator of constructor.validators_ options = node[validatorName] if options? leafValidators.push new Validator validatorName, validator, options # memoize validators: if leafValidators.length memos.validators[pathName] = leafValidators # memoize any accessors: for accessor in accessorNames if node[accessor] unless 'function' is typeof node[accessor] throw new SchemaError \ """ "#{accessor}" is not a function """ memos["#{accessor}ters"][path] = node[accessor] accessorParentPath = ['_data'].concat path.slice 0, -1 parent = memos.accessorParents[accessorParentPath.join '.'] or= [] parent.push path unless path in parent else if node.name #^4 type = node # memoize any annotations return unless type memos.types[pathName] = type if type is ObjectId memos.oids[pathName] = type else if type in primitives memos.primitives[pathName] = type else if type in natives memos.natives[pathName] = type else memos.annotations[pathName] = type chain = type.inheritanceChain?() if chain and Model in chain isSubcollectionType = path.slice(-1)[0] is '0' if isSubcollectionType memos.subcollectionEmbeds[path.slice(0,-1).join '.'] = type else memos.embeds[pathName] = type return # we don't want to implicitly return anything from the above if-ladder memos ### @method: property of the constructor. @signature: Model.getType(model, path) @param: model - that we're searching @param: path - that we're searching for @description: returns the type (the cast function or constructor) that correlates to the given path of the given model. @todo: reimplement. for now this will work, but it's a bit ugly, and it probably performs badly relative to the optimal. ### @getType = (model, path)-> {constructor} = model {types} = constructor return unless types if type = types[path.join '.'] return type else path = path.slice() tryPath = [] while component = path.shift() tryPath.push component if type = types[tryPath.join '.'] ref = type continue chain = ref?.inheritanceChain?() if chain and Model in chain path.push tryPath.pop() return Model.getType JsPath.getAt(model.data, tryPath), path return ### @method: property of the constructor. @signature: Model.castValue(value, type) @param: value - to be cast. @param: type - for the value to be cast as. @return: the casted value ### @castValue = (value, type)-> unless type? then # console.log '[WARN] castValue is called without a type.' else if type is Array then return value # special case this for mongo's special case else if type is Object or type is RegExp or type in primitives type value else if value instanceof type return value else if type is ObjectId or type is Date try new type value catch e then debugger else chain = type.inheritanceChain?() if chain and Model in chain if value instanceof type value else new type value else if type throw new TypeError \ """ Don't know how to cast value of type "#{value.constructor.name}" to type "#{type.name}". """ ### Querying @description: see ./find.coffee for detailed explanations. ### {@one, @all, @some, @someData, @remove, @removeById, @drop, @cursor, @findAndModify @count, @aggregate, @teasers, @hose, @mapReduce, @assure, @update, @each} = require './find' ### Model::fetchIdBySlug ### @fetchIdBySlug =(slug, callback)-> @someData {slug}, {_id:1}, {limit:1}, (err, cursor)-> if err then callback err else cursor.nextObject (err, doc)-> if err then callback err else unless doc? callback new Error "Unknown slug: #{slug}" else callback null, doc._id ### Feeding @description: see ./feed.coffee ### {@appendToFeed} = require './feed' ### @constructor. @signature: new Model(data) @param: data - with which to initialize the new instance.å @description: create a new Model instance. ### constructor:(data={})-> super data model = this defineProperty model, 'isNew', value : yes writable : yes defineProperty model, 'defaults', value: {} defineProperty model.defaults, 'beenApplied', value : no writable : yes defineProperty model, 'data', value: {} enumerable: yes # allow a maximum of 1 parent to be specified per model # TODO: perhaps we can introduce multidimensionality, but # of course it is a logical impossibility when it comes # to embedding. parent = null defineProperty model, 'parent_', writable: yes # Allow a model to know its path: defineProperty model, 'path_', writable: yes # Root node: defineProperty model, 'rootNode_', writable: yes defineProperty model, 'isRoot_', value: yes writable: yes # Support embedding models directly: isEmbedded_ = no defineProperty model, 'isEmbedded_', set :(value)-> isEmbedded_ = value get :-> isEmbedded_ # Support embedding models into "subcollections": inSubcollection_ = no defineProperty model, 'inSubcollection_', set :(value)-> inSubcollection_ = isEmbedded_ = yes get :-> inSubcollection_ # we need a place to store "setter values" defineProperty model, 'setterValues', value: {} for own parentPath, paths of model.constructor.accessorParents model.defineAccessorsOf parentPath.split('.').slice(1), paths for prop in model.constructor.rootProperties defineRootAccessorOf_ model, prop # import the data, casting values and constructing objects, as appropriate: model.set data # initialize any embedded docs. model.initEmbeds() clone:-> new @constructor @data ### @function. @signature: defineRootAccessorOf_(model, propertyName) @param: model @param: prop - the property name ### defineRootAccessorOf_ =(model, prop)-> {data, defaults} = model unless prop of model defineProperty model, prop, enumerable: yes get :-> if data[prop]? data[prop] else #model.applyDefaults() data[prop] = defaults[prop] set :(value)-> data[prop] = value ### @method. @signature: Model::defineAccessorsOf(parentPath, paths) @param: parentPath - an array of the segments of the path drilling down to, but not including the accessor itself @param: paths - an array of the complete paths of setters redundant, but convenient. this may change. @return: model @description: returns a structure object that has all accessors predefined. ### defineAccessorsOf:(parentPath, paths)-> model = @ {data} = model unless parentPath.length parent = data else parent = JsPath.getAt(data, parentPath) or {} JsPath.setAt data, parentPath, parent for path in paths assignAccessorsByPath_ model, data, parent, path #^* see below. @ ### @function. @signature: assignAccessorsByPath_(model, data, parent, path)^* @param: model - the instance. @param: data - the working tree. @param: parent - the owner of the properties we're setting. @param: path - the full path of the property we're setting. @description: a helper function for Model.defineAccessorsOf() so we don't create functions in the loop. (see above ^*) ### assignAccessorsByPath_ = (model, data, parent, path)-> pathName = path.join '.' prop = path.slice(-1)[0] setter = model.constructor.setters[pathName] getter = model.constructor.getters[pathName] defineProperty parent, prop, enumerable : yes set :(value)-> if setter value = setter.call parent, value #^** model.setterValues[pathName] = value get :-> value = model.setterValues[pathName] if getter value = getter.call parent, value #^** value # ** call accessors in the context of the parent so that # "this" is meaningful. ### @method. @signature: Model::applyDefaults() @param: callback @return: the model.defaults object @description: apply all the defaults throughout the model. call .applyDefaults() on any embedded models encountered in the walk. ### applyDefaults:(isDeep=no)-> model = @ if model.defaults? and not model.defaults.beenApplied # set default values for all fields for own defaultPath, defaultValue of model.constructor.defaults if 'function' is typeof defaultValue defaultValue = defaultValue.call model JsPath.setAt model.defaults, defaultPath, defaultValue model.defaults.beenApplied = yes if isDeep for own embedPath, embedConstructor of model.constructor.embeds JsPath.getAt(model, embedPath)?.applyDefaults() for own subcollectionEmbedPath, subcollectionEmbedAnnotation of model.constructor.subcollectionEmbeds JsPath.getAt(model, subcollectionEmbedPath)?.forEach (embed)-> embed.applyDefaults() model ### @method. @signature: Model::initEmbeds() @description: rather a heavy function that will initialize embedded models and embedded subcollections. Separated this from .applyDefaults(), because the latter should be fleet. ### initEmbeds:-> model = @ # initialize any models that are undefined. for own embedPath, embedConstructor of model.constructor.embeds embedPath = embedPath.split '.' unless JsPath.getAt(model.data, embedPath)? embed = new embedConstructor embed.path_ = embedPath embed.parent_ = JsPath.getAt model, embedPath.slice 0, -1 JsPath.setAt model.defaults, embedPath, embed # initialize any subcollections for own subcollectionEmbedPath, subcollectionEmbedAnnotation of \ model.constructor.subcollectionEmbeds subcollectionEmbedPath = subcollectionEmbedPath.split '.' unless JsPath.getAt(model.data, subcollectionEmbedPath)? parent = JsPath.getAt model, subcollectionEmbedPath.slice 0, -1 subcollection = new Subcollection \ parent, [], subcollectionEmbedAnnotation subcollection.path_ = subcollectionEmbedPath JsPath.setAt model.defaults, subcollectionEmbedPath, subcollection ### @method. @signature: Model::validate(callback) @param: callback @return: errs — that were encountered in the walk. @description: validate the data of "this", emitting events. ### validate:(callback)-> Validator.validate @, callback @validateAt =(path, value, sendMessage = no)-> [isValid, message] = do => if @paths[path]? validators = @validators[path] for { validate, message } in validators try success = validate value catch e then return [no, message] return [!!success, unless success then message] return [yes] else return [no, "unknown field"] return isValid unless sendMessage return { isValid, message } ### @constructor. @signature: Model::getClient() @returns: client - of the constructor. ### getClient:-> @constructor.getClient() ### @constructor. @signature: Model::getClient() @returns: collection name - of the constructor. ### getCollectionName:-> @constructor.getCollectionName() save: require('./save').save ### @method. @signature: Model::saveAtomically(model, callback) @throws: an schemaError ### saveAtomically:(model, callback)-> if @notRoot throw new Error \ "don't call .saveAtomically() on a non-root node." else @save callback # #getMemoByNameAndPath:(memoName, path)-> # {constructor, data} = @ # path = path.slice() # memo = constructor[memoName][path.join '.'] # return [] unless memo # prop = path.pop() # parent = JsPath.getAt data, path # [memo, prop, parent] # #setSubcollection:(path, array)-> # [annotation, prop, parent] = @getMemoByNameAndPath 'subcollections', path # subcollection = new Subcollection @, array, annotation # parent[prop] = subcollection ### @method. @signature: Model::set(data) @param: data - a map of paths to set data to. Use dot notation if you want to reach into objects, as there is no way to recursively merge JS objects without astonishing side effects. Object notation "clobbers" sibling properties. @description: sets properties to the model by path. ### set:(data)-> model = @ {constructor} = model new Traverse(data) .forEach (node)-> return if not node? if node.constructor is ObjectId @update node, yes if Array.isArray node type = constructor.subcollections[@path.join '.'] subcollection = new Subcollection model, node, type @update subcollection else if @path.length type = Model.getType model, @path if type and type isnt Object @update Model.castValue(node, type), yes return # if @node instanceof Model # @update @node, yes # traverse again to set the path # TODO: try to optimize this so we only need to walk once. new Traverse(data) .forEach (node)-> if node instanceof Model # I am not 100% convinced that this assumption will hold true: node.isRoot_ = no node.rootNode_ = model node.path_ = @path node.parent_ = @parent.node @update node return #@node for own path, value of data JsPath.setAt model.data, path, value # TODO: this is a bit ugly: model._id = data._id if data._id ### @function. @signature: attachOuterAccessor_(model, path) @param: model @param: path - the path (inside data) we want to alias. @description: helper to add accessors onto the root level of the model to access the members on the root level of the model's data object. ### attachOuterAccessor_ = (model, path)-> defineProperty model, path, enumerable: yes get :-> model.data[path] set :(value)-> model.data[path] = value shouldBeSaved:(path)-> if path is '_id' then no else console.log path; yes ### @method. @signature Model::get() @description: traverse the model (which implicitly will call any getters), prune nulls and undefineds, return the results of the traversal. ### get:(shouldPrune=no)-> model = @ model.applyDefaults() data = extend {}, model.defaults, if shouldPrune then model.prune() else model.data # this will call the getters and return a new object new Traverse(data).forEach -> if @node instanceof Subcollection @update [].slice.call @node else @update @node?.get?() or @node getId:-> # TODO: implement plugins id = @data._id if 'string' is typeof id new ObjectId id else id equals:(model, deep=no)-> unless deep @getId()?.equals? id if id = model?.getId?() # TODO: I'm not currently interested in "deep", but it might be needed later CT prune:do -> applyFilter =(node, constructor, pathName)-> filter = constructor.filters[pathName] filter node (isHard=no)-> model = @ {constructor} = model method = if isHard then 'forEach' else 'map' prunedData = new Traverse(model.data)[method] (node)-> pathName = @path.join '.' if node instanceof ObjectId @update ObjectId(node+''), yes else if pathName is '_id' # it's the mongo ObjectId @update node, yes else if pathName of constructor.embeds # it's a directly-embedded doc @update node.prune(), yes else if pathName of constructor.subcollectionEmbeds prunedCollection = (embed.prune(isHard) for embed in node) # it's a subcollection of embeds @update prunedCollection, yes else if pathName of constructor.paths # it's a schematical path if pathName of constructor.filters # it needs filtered @update applyFilter(node), yes else if pathName.length # it's schematical @update node, yes else @update node else # never heard of it; pruning! @remove() prunedData updateInstances:(atomically)-> prunedModifier = {} for own op of atomically prunedModifier[op] = {} for own field, val of atomically[op] unless field in ['snapshot','snapshotIds'] # TODO: this is a one-off hack. prunedModifier[op][field] = val if @constructor.getBroadcastable() @emit 'updateInstance', prunedModifier || @ update:(atomically, callback=->)-> model = @ if 'function' is typeof atomically callback = atomically atomically = undefined unless atomically Model::save.call model, (err)-> if err callback err else model.updateInstances() callback null else collection = model.constructor.getCollection() update = _id: model.getId() for own operator, operation of atomically when operator is '$set' for own path, value of operation splittedPath = path.split '.' type = Model.getType model, splittedPath validators = model.constructor.validators[path] if validators?.length for { validate, name, message } in validators when not validate value return callback { message, name, value } if type and type isnt Object value = Model.castValue value, type operation[path] = value { operation } = new MongoOp(atomically) .map(model.applySetters.bind(model)) .applyTo(model) # first update the one in memory. collection.update update, operation, (err)-> # then update the one in the database. if err callback err else model.updateInstances(atomically) callback null applySetters: (operator, operation) -> out = {} for own k, v of operation setter = @constructor.setters[k] if setter? v = setter.call this, v out[k] = v return out @_hardDelete = @remove remove:(callback)-> if @constructor.softDelete Trash = require '../trash' Trash.create this @constructor._hardDelete _id: @getId(), callback @remove:(selector, callback)-> if @softDelete Trash = require '../trash' @some selector, {}, (err, rows)=> Trash.create row for row in rows @_hardDelete selector, callback else @_hardDelete selector, callback ['getAt','setAt','deleteAt'] .forEach (method)=> @::[method] =(path)-> JsPath[method].call null, @data, path ### Footnotes: 1 - ad hoc properties not associated with a schema are fine, but we don't persist them to Mongo. 2 - apply defaults / validations on output (not here). 3 - the human-readable description of the schema, including "type annotations" (JS constructors/primitive casts, really) and validation functions (including some sugared inbuilt ones). 4 - if it has a name, it may be a constructor; this might be botched. 5 - because of overloading, we need to make sure this isn't a field called "validator". 6 - defaults are applied on output. 7 - normal validators only take 1 argument: a value which needs to be validated. There are also a class of so-called "curried" validators that take 2 arguments (e.g. pattern and enum): the first is arbitrarily supplied during schema creation, and the second is the value described above which needs to be validated. ###
[ { "context": "til\n\n The MIT License (MIT)\n\n Copyright (c) 2014 Yasuhiro Okuno\n\n Permission is hereby granted, free of charge, ", "end": 88, "score": 0.9998680949211121, "start": 74, "tag": "NAME", "value": "Yasuhiro Okuno" } ]
coffee_lib/crowdutil/subcmd/create-group.coffee
koma75/crowdutil
1
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 Yasuhiro Okuno 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. ### crhelp = require '../helper/crhelper' help = require '../helper/helper' isOptOK = (opts) -> rc = true if( !help.opIsType(opts, '-n', 'string') || !help.isName(opts['-n'][0], false) ) logger.warn 'invalid group name' console.log 'E, invalid group name' rc = false if !help.opIsType(opts, '-d', 'string') # just put an empty string opts['-d'] = [''] return rc exports.run = (options) -> logger.trace 'running : create-group\n\n\n' logger.debug options if !isOptOK(options) return crowd = options['crowd'] crowd.groups.create( options['-n'][0], options['-d'][0], (err) -> if err logger.error err.message console.log "E, failed to create #{options['-n'][0]}" else # check if group is created as intended crhelp.findGroup( crowd, { name: options['-n'][0] }, (err, res) -> if err console.log "W, group creation returned success but could not be found." console.log "W, Confirm at the Crowd admin console for assurance." logger.warn err.message return logger.debug JSON.stringify(res) console.log "I, group created successfully" console.log JSON.stringify(res,null,2) ) )
158488
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### crhelp = require '../helper/crhelper' help = require '../helper/helper' isOptOK = (opts) -> rc = true if( !help.opIsType(opts, '-n', 'string') || !help.isName(opts['-n'][0], false) ) logger.warn 'invalid group name' console.log 'E, invalid group name' rc = false if !help.opIsType(opts, '-d', 'string') # just put an empty string opts['-d'] = [''] return rc exports.run = (options) -> logger.trace 'running : create-group\n\n\n' logger.debug options if !isOptOK(options) return crowd = options['crowd'] crowd.groups.create( options['-n'][0], options['-d'][0], (err) -> if err logger.error err.message console.log "E, failed to create #{options['-n'][0]}" else # check if group is created as intended crhelp.findGroup( crowd, { name: options['-n'][0] }, (err, res) -> if err console.log "W, group creation returned success but could not be found." console.log "W, Confirm at the Crowd admin console for assurance." logger.warn err.message return logger.debug JSON.stringify(res) console.log "I, group created successfully" console.log JSON.stringify(res,null,2) ) )
true
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 PI:NAME:<NAME>END_PI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### crhelp = require '../helper/crhelper' help = require '../helper/helper' isOptOK = (opts) -> rc = true if( !help.opIsType(opts, '-n', 'string') || !help.isName(opts['-n'][0], false) ) logger.warn 'invalid group name' console.log 'E, invalid group name' rc = false if !help.opIsType(opts, '-d', 'string') # just put an empty string opts['-d'] = [''] return rc exports.run = (options) -> logger.trace 'running : create-group\n\n\n' logger.debug options if !isOptOK(options) return crowd = options['crowd'] crowd.groups.create( options['-n'][0], options['-d'][0], (err) -> if err logger.error err.message console.log "E, failed to create #{options['-n'][0]}" else # check if group is created as intended crhelp.findGroup( crowd, { name: options['-n'][0] }, (err, res) -> if err console.log "W, group creation returned success but could not be found." console.log "W, Confirm at the Crowd admin console for assurance." logger.warn err.message return logger.debug JSON.stringify(res) console.log "I, group created successfully" console.log JSON.stringify(res,null,2) ) )
[ { "context": "=========================================\n# Autor: Elena Aguado (Fundació Bit), 2018\n# ==========================", "end": 65, "score": 0.9998784065246582, "start": 53, "tag": "NAME", "value": "Elena Aguado" } ]
source/coffee/series_tweets_filtrats.coffee
Fundacio-Bit/twitter-intranet
0
# ========================================= # Autor: Elena Aguado (Fundació Bit), 2018 # ========================================= # ------------------- # Variables Globales # ------------------- g_brand_list = [] # Función para extraer las marcas de la REST y renderizar resultados # ------------------------------------------------------------------ getBrands = () -> brand_list = [] request = "/rest_utils/brands" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else data.results.forEach (brand) -> brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)}) g_brand_list.push(brand) html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true } $('#form-group-brands').html html_content # -------------------------------------------------------------- # Función para extraer datos de la REST y renderizar resultados # -------------------------------------------------------------- getSeriesDataAndRenderChart = (year, brand) -> request = "/rest_tweets_retweets/series_filtrats/year/#{year}/brand/#{brand}" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else # ================= # Petición REST OK # ================= $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') brandMessage = if brand == '--all--' then 'totes les marques' else brand.charAt(0).toUpperCase() + brand.slice(1) ctx = document.getElementById('seriesChart').getContext('2d') seriesChart = new Chart(ctx, { type: 'line' data: data.results options: responsive: true title: display: true text: "Sèrie temporal de " + brandMessage + " per a l'any " + year tooltips: mode: 'x' intersect: true hover: mode: 'nearest' intersect: true scaleShowValues: true scales: xAxes: [ { gridLines: display: false ticks: source: 'labels' autoSkip: false # display: true scaleLabel: display: true labelString: 'Data' } ] yAxes: [ { gridLines: display: false display: true scaleLabel: display: true labelString: 'Freqüència' } ] }) $('#seriesChart').show() # ----------------------------------------------------- # Extraer las marcas de la REST y renderizar resultados # ----------------------------------------------------- getBrands() (($) -> # Fijamos evento sobre botón de Buscar # ------------------------------------- $('#searchButton').click (event) -> # --------------------------------- # Recogemos valores del formulario # --------------------------------- marca = $('#searchForm select[name="brand"]').val() any = $('#searchForm select[name="year"]').val() # ========================= # Validación de formulario # ========================= if any is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'} else if marca is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'marca'} else # ============== # Validación OK # ============== # controlamos visibilidad de elementos # ------------------------------------- # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') $('#statusPanel').html '<br><br><br><p align="center"><img src="/img/loading_icon.gif">&nbsp;&nbsp;Carregant...</p>' # Petición REST # -------------- getSeriesDataAndRenderChart any, marca return false # Ocultaciones al inicio # ----------------------- $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') ) jQuery
83694
# ========================================= # Autor: <NAME> (Fundació Bit), 2018 # ========================================= # ------------------- # Variables Globales # ------------------- g_brand_list = [] # Función para extraer las marcas de la REST y renderizar resultados # ------------------------------------------------------------------ getBrands = () -> brand_list = [] request = "/rest_utils/brands" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else data.results.forEach (brand) -> brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)}) g_brand_list.push(brand) html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true } $('#form-group-brands').html html_content # -------------------------------------------------------------- # Función para extraer datos de la REST y renderizar resultados # -------------------------------------------------------------- getSeriesDataAndRenderChart = (year, brand) -> request = "/rest_tweets_retweets/series_filtrats/year/#{year}/brand/#{brand}" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else # ================= # Petición REST OK # ================= $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') brandMessage = if brand == '--all--' then 'totes les marques' else brand.charAt(0).toUpperCase() + brand.slice(1) ctx = document.getElementById('seriesChart').getContext('2d') seriesChart = new Chart(ctx, { type: 'line' data: data.results options: responsive: true title: display: true text: "Sèrie temporal de " + brandMessage + " per a l'any " + year tooltips: mode: 'x' intersect: true hover: mode: 'nearest' intersect: true scaleShowValues: true scales: xAxes: [ { gridLines: display: false ticks: source: 'labels' autoSkip: false # display: true scaleLabel: display: true labelString: 'Data' } ] yAxes: [ { gridLines: display: false display: true scaleLabel: display: true labelString: 'Freqüència' } ] }) $('#seriesChart').show() # ----------------------------------------------------- # Extraer las marcas de la REST y renderizar resultados # ----------------------------------------------------- getBrands() (($) -> # Fijamos evento sobre botón de Buscar # ------------------------------------- $('#searchButton').click (event) -> # --------------------------------- # Recogemos valores del formulario # --------------------------------- marca = $('#searchForm select[name="brand"]').val() any = $('#searchForm select[name="year"]').val() # ========================= # Validación de formulario # ========================= if any is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'} else if marca is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'marca'} else # ============== # Validación OK # ============== # controlamos visibilidad de elementos # ------------------------------------- # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') $('#statusPanel').html '<br><br><br><p align="center"><img src="/img/loading_icon.gif">&nbsp;&nbsp;Carregant...</p>' # Petición REST # -------------- getSeriesDataAndRenderChart any, marca return false # Ocultaciones al inicio # ----------------------- $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') ) jQuery
true
# ========================================= # Autor: PI:NAME:<NAME>END_PI (Fundació Bit), 2018 # ========================================= # ------------------- # Variables Globales # ------------------- g_brand_list = [] # Función para extraer las marcas de la REST y renderizar resultados # ------------------------------------------------------------------ getBrands = () -> brand_list = [] request = "/rest_utils/brands" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else data.results.forEach (brand) -> brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)}) g_brand_list.push(brand) html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true } $('#form-group-brands').html html_content # -------------------------------------------------------------- # Función para extraer datos de la REST y renderizar resultados # -------------------------------------------------------------- getSeriesDataAndRenderChart = (year, brand) -> request = "/rest_tweets_retweets/series_filtrats/year/#{year}/brand/#{brand}" $.ajax({url: request, type: "GET"}) .done (data) -> # Chequeamos si la REST ha devuelto un error # ------------------------------------------- if data.error? $('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error} else # ================= # Petición REST OK # ================= $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') brandMessage = if brand == '--all--' then 'totes les marques' else brand.charAt(0).toUpperCase() + brand.slice(1) ctx = document.getElementById('seriesChart').getContext('2d') seriesChart = new Chart(ctx, { type: 'line' data: data.results options: responsive: true title: display: true text: "Sèrie temporal de " + brandMessage + " per a l'any " + year tooltips: mode: 'x' intersect: true hover: mode: 'nearest' intersect: true scaleShowValues: true scales: xAxes: [ { gridLines: display: false ticks: source: 'labels' autoSkip: false # display: true scaleLabel: display: true labelString: 'Data' } ] yAxes: [ { gridLines: display: false display: true scaleLabel: display: true labelString: 'Freqüència' } ] }) $('#seriesChart').show() # ----------------------------------------------------- # Extraer las marcas de la REST y renderizar resultados # ----------------------------------------------------- getBrands() (($) -> # Fijamos evento sobre botón de Buscar # ------------------------------------- $('#searchButton').click (event) -> # --------------------------------- # Recogemos valores del formulario # --------------------------------- marca = $('#searchForm select[name="brand"]').val() any = $('#searchForm select[name="year"]').val() # ========================= # Validación de formulario # ========================= if any is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'any'} else if marca is null setTimeout ( -> $('#statusPanel').html '' ), 1000 $('#statusPanel').html MyApp.templates.commonsFormValidation {form_field: 'marca'} else # ============== # Validación OK # ============== # controlamos visibilidad de elementos # ------------------------------------- # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') $('#statusPanel').html '<br><br><br><p align="center"><img src="/img/loading_icon.gif">&nbsp;&nbsp;Carregant...</p>' # Petición REST # -------------- getSeriesDataAndRenderChart any, marca return false # Ocultaciones al inicio # ----------------------- $('#statusPanel').html '' # Reset the canvas. If not several canvas could appear supperposed $('#seriesChart').remove() $('#chartContainer').append('<canvas id="seriesChart" width="70%" height="20px"></canvas>') ) jQuery
[ { "context": "extFactory.CreateFromKey @network, ECKey.fromWIF(\"KxPT8wdUkxiuenxKcWh8V79pGxRQumQFtYEbYWcw1gRf8wNLm5m3\"), ECPubKey.fromHex req.body.pubkey\n channel", "end": 1801, "score": 0.9997357726097107, "start": 1749, "tag": "KEY", "value": "KxPT8wdUkxiuenxKcWh8V79pGxRQumQFtYEbYWc...
demo/server_controller.coffee
devktor/micropayments.js
0
ChannelServer = require "../channel_server" {ChannelServerContext, ChannelServerContextFactory} = require "../channel_server_context" {Transaction, Address, ECKey, ECPubKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {id:{$in:outputs}}, (err, contextData)=> if err? or not contextData? console.log "contract not found : ",err else context = new ChannelServerContext @network context.fromJSON contextData server = new ChannelServer context if server.initContract hex @db.collection("channel").update {id:contextData.id}, {$set:context.toJSON()}, (err)-> if err? console.log "failed to update context #{contextData.id} : ",err else console.log "channel #{contextData.id} started" undefined getStatus:(req, res)-> @execute req, res, false, (server)-> res.send {status: if !server.context.active then "closed" else if server.context.contractID? then "open" else "pending"} requestChannel:(req, res)-> console.log "req: ",req.body if !req.body.pubkey? res.sendStatus 400 else context = ChannelServerContextFactory.Create @network, ECPubKey.fromHex req.body.pubkey # context = ChannelServerContextFactory.CreateFromKey @network, ECKey.fromWIF("KxPT8wdUkxiuenxKcWh8V79pGxRQumQFtYEbYWcw1gRf8wNLm5m3"), ECPubKey.fromHex req.body.pubkey channelData = context.toJSON() channelData.id = context.getContractAddress().toString() channelData.active = false @db.collection("channel").insert channelData, (err)=> if err? res.sendStatus 500 else @node.registerAddresses channelData.id, (err)=> if err? @db.collection("channel").remove {id:channelData.id}, (err)-> if err? then throw err res.sendStatus 500 else res.send pubkey:context.getServerPubKey() closeChannel:(req, res)-> @execute req, res, false, (server)=> if server.context.paidAmount tx = server.getCloseTransaction() if !tx res.sendStatus 400 else console.log "transaction :",tx.toHex() @node.send tx.toHex(), (err)=> if err? console.log "failed to send transaction: ",err active = true else active = false @db.collection("channel").update {id:server.context.id}, {$set:{active:active}}, (err)-> if err? console.log "failed to update context ",err res.sendStatus 500 else if active console.log "contract not active" res.sendStatus 500 else console.log "channel #{server.context.id} closed, total paid: ",server.context.paidAmount console.log "payment tx: ",tx.getId() res.send {totalPaid:server.context.paidAmount, paymentID:tx.getId()} signRefund:(req, res)-> @execute req, res, true, (server)-> refund = server.signRefund req.body.tx if refund refund = refund.toHex() # console.log "refunds transaction for #{server.context.id} : #{refund}" res.send {hex:refund} else res.sendStatus 400 processPayment:(req, res)-> @execute req, res, true, (server)=> amount = server.processPayment req.body.tx if !amount res.sendStatus 400 else @db.collection("channel").update {id:server.context.id}, {$set:server.context.toJSON()}, (err)-> if err? res.sendStatus 500 else console.log "new payment for #{server.context.id}: #{amount} total #{server.context.paidAmount}" res.send {paidAmount:server.context.paidAmount} execute:(req, res, txRequired, next)-> if !req.body.channel? or (txRequired and !req.body.tx?) res.sendStatus 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err res.sendStatus 500 else if !data? res.sendStatus 404 else context = new ChannelServerContext @network context.fromJSON data context.id = req.body.channel server = new ChannelServer context next server module.exports = Controller
28627
ChannelServer = require "../channel_server" {ChannelServerContext, ChannelServerContextFactory} = require "../channel_server_context" {Transaction, Address, ECKey, ECPubKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {id:{$in:outputs}}, (err, contextData)=> if err? or not contextData? console.log "contract not found : ",err else context = new ChannelServerContext @network context.fromJSON contextData server = new ChannelServer context if server.initContract hex @db.collection("channel").update {id:contextData.id}, {$set:context.toJSON()}, (err)-> if err? console.log "failed to update context #{contextData.id} : ",err else console.log "channel #{contextData.id} started" undefined getStatus:(req, res)-> @execute req, res, false, (server)-> res.send {status: if !server.context.active then "closed" else if server.context.contractID? then "open" else "pending"} requestChannel:(req, res)-> console.log "req: ",req.body if !req.body.pubkey? res.sendStatus 400 else context = ChannelServerContextFactory.Create @network, ECPubKey.fromHex req.body.pubkey # context = ChannelServerContextFactory.CreateFromKey @network, ECKey.fromWIF("<KEY>"), ECPubKey.fromHex req.body.pubkey channelData = context.toJSON() channelData.id = context.getContractAddress().toString() channelData.active = false @db.collection("channel").insert channelData, (err)=> if err? res.sendStatus 500 else @node.registerAddresses channelData.id, (err)=> if err? @db.collection("channel").remove {id:channelData.id}, (err)-> if err? then throw err res.sendStatus 500 else res.send pubkey:context.getServerPubKey() closeChannel:(req, res)-> @execute req, res, false, (server)=> if server.context.paidAmount tx = server.getCloseTransaction() if !tx res.sendStatus 400 else console.log "transaction :",tx.toHex() @node.send tx.toHex(), (err)=> if err? console.log "failed to send transaction: ",err active = true else active = false @db.collection("channel").update {id:server.context.id}, {$set:{active:active}}, (err)-> if err? console.log "failed to update context ",err res.sendStatus 500 else if active console.log "contract not active" res.sendStatus 500 else console.log "channel #{server.context.id} closed, total paid: ",server.context.paidAmount console.log "payment tx: ",tx.getId() res.send {totalPaid:server.context.paidAmount, paymentID:tx.getId()} signRefund:(req, res)-> @execute req, res, true, (server)-> refund = server.signRefund req.body.tx if refund refund = refund.toHex() # console.log "refunds transaction for #{server.context.id} : #{refund}" res.send {hex:refund} else res.sendStatus 400 processPayment:(req, res)-> @execute req, res, true, (server)=> amount = server.processPayment req.body.tx if !amount res.sendStatus 400 else @db.collection("channel").update {id:server.context.id}, {$set:server.context.toJSON()}, (err)-> if err? res.sendStatus 500 else console.log "new payment for #{server.context.id}: #{amount} total #{server.context.paidAmount}" res.send {paidAmount:server.context.paidAmount} execute:(req, res, txRequired, next)-> if !req.body.channel? or (txRequired and !req.body.tx?) res.sendStatus 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err res.sendStatus 500 else if !data? res.sendStatus 404 else context = new ChannelServerContext @network context.fromJSON data context.id = req.body.channel server = new ChannelServer context next server module.exports = Controller
true
ChannelServer = require "../channel_server" {ChannelServerContext, ChannelServerContextFactory} = require "../channel_server_context" {Transaction, Address, ECKey, ECPubKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {id:{$in:outputs}}, (err, contextData)=> if err? or not contextData? console.log "contract not found : ",err else context = new ChannelServerContext @network context.fromJSON contextData server = new ChannelServer context if server.initContract hex @db.collection("channel").update {id:contextData.id}, {$set:context.toJSON()}, (err)-> if err? console.log "failed to update context #{contextData.id} : ",err else console.log "channel #{contextData.id} started" undefined getStatus:(req, res)-> @execute req, res, false, (server)-> res.send {status: if !server.context.active then "closed" else if server.context.contractID? then "open" else "pending"} requestChannel:(req, res)-> console.log "req: ",req.body if !req.body.pubkey? res.sendStatus 400 else context = ChannelServerContextFactory.Create @network, ECPubKey.fromHex req.body.pubkey # context = ChannelServerContextFactory.CreateFromKey @network, ECKey.fromWIF("PI:KEY:<KEY>END_PI"), ECPubKey.fromHex req.body.pubkey channelData = context.toJSON() channelData.id = context.getContractAddress().toString() channelData.active = false @db.collection("channel").insert channelData, (err)=> if err? res.sendStatus 500 else @node.registerAddresses channelData.id, (err)=> if err? @db.collection("channel").remove {id:channelData.id}, (err)-> if err? then throw err res.sendStatus 500 else res.send pubkey:context.getServerPubKey() closeChannel:(req, res)-> @execute req, res, false, (server)=> if server.context.paidAmount tx = server.getCloseTransaction() if !tx res.sendStatus 400 else console.log "transaction :",tx.toHex() @node.send tx.toHex(), (err)=> if err? console.log "failed to send transaction: ",err active = true else active = false @db.collection("channel").update {id:server.context.id}, {$set:{active:active}}, (err)-> if err? console.log "failed to update context ",err res.sendStatus 500 else if active console.log "contract not active" res.sendStatus 500 else console.log "channel #{server.context.id} closed, total paid: ",server.context.paidAmount console.log "payment tx: ",tx.getId() res.send {totalPaid:server.context.paidAmount, paymentID:tx.getId()} signRefund:(req, res)-> @execute req, res, true, (server)-> refund = server.signRefund req.body.tx if refund refund = refund.toHex() # console.log "refunds transaction for #{server.context.id} : #{refund}" res.send {hex:refund} else res.sendStatus 400 processPayment:(req, res)-> @execute req, res, true, (server)=> amount = server.processPayment req.body.tx if !amount res.sendStatus 400 else @db.collection("channel").update {id:server.context.id}, {$set:server.context.toJSON()}, (err)-> if err? res.sendStatus 500 else console.log "new payment for #{server.context.id}: #{amount} total #{server.context.paidAmount}" res.send {paidAmount:server.context.paidAmount} execute:(req, res, txRequired, next)-> if !req.body.channel? or (txRequired and !req.body.tx?) res.sendStatus 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err res.sendStatus 500 else if !data? res.sendStatus 404 else context = new ChannelServerContext @network context.fromJSON data context.id = req.body.channel server = new ChannelServer context next server module.exports = Controller
[ { "context": "calhost:3001'\n MONGO_URL: 'mongodb://127.0.0.1:27017/nfd'\n PORT: 3000\n SCRAPE", "end": 202, "score": 0.9997100830078125, "start": 193, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "RYPT_SALT_LENGTH: 10\n SESSION_SECRET...
config.coffee
craigspaeth/nfd-api
0
module.exports = NODE_ENV: 'development' APP_URL: 'http://localhost:3000' CLIENT_URL: 'http://localhost:3001' MONGO_URL: 'mongodb://127.0.0.1:27017/nfd' PORT: 3000 SCRAPE_PER_MINUTE: 10 SCRAPE_TOTAL_PAGES: 10 VISIT_TIMEOUT: 60000 NEW_RELIC_LICENSE_KEY: '' MIXPANEL_KEY: '' BCRYPT_SALT_LENGTH: 10 SESSION_SECRET: 'n0feedigz' MANDRILL_APIKEY: '' # Override any values with env variables if they exist module.exports[key] = (process.env[key] or val) for key, val of module.exports
128088
module.exports = NODE_ENV: 'development' APP_URL: 'http://localhost:3000' CLIENT_URL: 'http://localhost:3001' MONGO_URL: 'mongodb://127.0.0.1:27017/nfd' PORT: 3000 SCRAPE_PER_MINUTE: 10 SCRAPE_TOTAL_PAGES: 10 VISIT_TIMEOUT: 60000 NEW_RELIC_LICENSE_KEY: '' MIXPANEL_KEY: '' BCRYPT_SALT_LENGTH: 10 SESSION_SECRET: '<KEY>' MANDRILL_APIKEY: '' # Override any values with env variables if they exist module.exports[key] = (process.env[key] or val) for key, val of module.exports
true
module.exports = NODE_ENV: 'development' APP_URL: 'http://localhost:3000' CLIENT_URL: 'http://localhost:3001' MONGO_URL: 'mongodb://127.0.0.1:27017/nfd' PORT: 3000 SCRAPE_PER_MINUTE: 10 SCRAPE_TOTAL_PAGES: 10 VISIT_TIMEOUT: 60000 NEW_RELIC_LICENSE_KEY: '' MIXPANEL_KEY: '' BCRYPT_SALT_LENGTH: 10 SESSION_SECRET: 'PI:KEY:<KEY>END_PI' MANDRILL_APIKEY: '' # Override any values with env variables if they exist module.exports[key] = (process.env[key] or val) for key, val of module.exports
[ { "context": "ply\\nformat binary_big_endian 1.0\\ncomment author: Paraform\\nobj_info 3D colored patch boundaries \\neleme", "end": 188, "score": 0.9340444207191467, "start": 184, "tag": "USERNAME", "value": "Para" }, { "context": "\"\n ply\n format ascii 1.0\n comment made...
jax-engine/spec/javascripts/jax/builtin/meshes/ply/parser_spec.js.coffee
sinisterchipmunk/jax
24
describe "Jax.Mesh.PLY.Parser", -> ply = null describe "parsing binary 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser 'ply\nformat binary_big_endian 1.0\ncomment author: Paraform\nobj_info 3D colored patch boundaries \nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty uchar intensity\nproperty list uchar int vertex_indices\nend_header\n@\xBC\xA0aA<\x9DJA\xDAD\u0013\x99\x03\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03' it "should parse ok", -> expect(ply.vertex[0]).toEqual x: 5.894577503204346, y: 11.788400650024414, z: 27.283239364624023 expect(ply.face[0].vertex_indices).toEqual [1, 2, 3] expect(ply.face[0].intensity).toEqual 0x99 it "stringToBytes", -> stb = Jax.Mesh.PLY.Parser.prototype.stringToBytes expect(stb.call(Jax.Mesh.PLY.Parser.prototype, 'a')).toEqual [97] expect(stb.call(Jax.Mesh.PLY.Parser.prototype, '@\xBC\xA0aA<\x9DJA\xDAD\u0013\xC2UL\xEAB\x865o\xC2e\xCC\xEF@p\b\u0002A\x84\v\u0010A\xEB')).toEqual( [64, 188, 160, 97, 65, 60, 157, 74, 65, 218, 68, 19, 194, 85, 76, 234, 66, 134, 53, 111, 194, 101, 204, 239, 64, 112, 8, 2, 65, 132, 11, 16, 65, 235] ) it "readBinaryValue", -> rbv = Jax.Mesh.PLY.Parser.prototype.readBinaryValue bytes = [64, 188, 160, 97] expect(rbv.call(Jax.Mesh.PLY.Parser.prototype, bytes, 'float', 1)).toEqual(5.894577503204346) describe "parsing ASCII 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser """ ply format ascii 1.0 comment made by Greg Turk comment this file is a cube element vertex 8 property float x property float y property float z element face 6 property list uchar int vertex_index end_header 0 0 0 0 0 1 0 1 1 0 1 0 1 0 0 1 0 1 1 1 1 1 1 0 4 0 1 2 3 4 7 6 5 4 4 0 4 5 1 4 1 5 6 2 4 2 6 7 3 4 3 7 4 0 """ it "should find the format", -> expect(ply.format).toEqual 'ascii' it "should find the version", -> expect(ply.version).toEqual '1.0' it "should find both comments, in order", -> expect(ply.comments).toEqual ['made by Greg Turk', 'this file is a cube'] it "should find 8 vertices", -> expect(ply.vertex.length).toEqual 8 it "should find 6 faces", -> expect(ply.face.length).toEqual 6 it "should detect the vertices in order", -> expect(ply.vertex[0]).toEqual x: 0, y: 0, z: 0 expect(ply.vertex[1]).toEqual x: 0, y: 0, z: 1 expect(ply.vertex[2]).toEqual x: 0, y: 1, z: 1 expect(ply.vertex[3]).toEqual x: 0, y: 1, z: 0 expect(ply.vertex[4]).toEqual x: 1, y: 0, z: 0 expect(ply.vertex[5]).toEqual x: 1, y: 0, z: 1 expect(ply.vertex[6]).toEqual x: 1, y: 1, z: 1 expect(ply.vertex[7]).toEqual x: 1, y: 1, z: 0 it "should detect the vertex indices for each face in order", -> expect(ply.face[0].vertex_index).toEqual [0, 1, 2, 3] expect(ply.face[1].vertex_index).toEqual [7, 6, 5, 4] expect(ply.face[2].vertex_index).toEqual [0, 4, 5, 1] expect(ply.face[3].vertex_index).toEqual [1, 5, 6, 2] expect(ply.face[4].vertex_index).toEqual [2, 6, 7, 3] expect(ply.face[5].vertex_index).toEqual [3, 7, 4, 0]
57252
describe "Jax.Mesh.PLY.Parser", -> ply = null describe "parsing binary 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser 'ply\nformat binary_big_endian 1.0\ncomment author: Paraform\nobj_info 3D colored patch boundaries \nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty uchar intensity\nproperty list uchar int vertex_indices\nend_header\n@\xBC\xA0aA<\x9DJA\xDAD\u0013\x99\x03\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03' it "should parse ok", -> expect(ply.vertex[0]).toEqual x: 5.894577503204346, y: 11.788400650024414, z: 27.283239364624023 expect(ply.face[0].vertex_indices).toEqual [1, 2, 3] expect(ply.face[0].intensity).toEqual 0x99 it "stringToBytes", -> stb = Jax.Mesh.PLY.Parser.prototype.stringToBytes expect(stb.call(Jax.Mesh.PLY.Parser.prototype, 'a')).toEqual [97] expect(stb.call(Jax.Mesh.PLY.Parser.prototype, '@\xBC\xA0aA<\x9DJA\xDAD\u0013\xC2UL\xEAB\x865o\xC2e\xCC\xEF@p\b\u0002A\x84\v\u0010A\xEB')).toEqual( [64, 188, 160, 97, 65, 60, 157, 74, 65, 218, 68, 19, 194, 85, 76, 234, 66, 134, 53, 111, 194, 101, 204, 239, 64, 112, 8, 2, 65, 132, 11, 16, 65, 235] ) it "readBinaryValue", -> rbv = Jax.Mesh.PLY.Parser.prototype.readBinaryValue bytes = [64, 188, 160, 97] expect(rbv.call(Jax.Mesh.PLY.Parser.prototype, bytes, 'float', 1)).toEqual(5.894577503204346) describe "parsing ASCII 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser """ ply format ascii 1.0 comment made by <NAME> comment this file is a cube element vertex 8 property float x property float y property float z element face 6 property list uchar int vertex_index end_header 0 0 0 0 0 1 0 1 1 0 1 0 1 0 0 1 0 1 1 1 1 1 1 0 4 0 1 2 3 4 7 6 5 4 4 0 4 5 1 4 1 5 6 2 4 2 6 7 3 4 3 7 4 0 """ it "should find the format", -> expect(ply.format).toEqual 'ascii' it "should find the version", -> expect(ply.version).toEqual '1.0' it "should find both comments, in order", -> expect(ply.comments).toEqual ['made by <NAME>', 'this file is a cube'] it "should find 8 vertices", -> expect(ply.vertex.length).toEqual 8 it "should find 6 faces", -> expect(ply.face.length).toEqual 6 it "should detect the vertices in order", -> expect(ply.vertex[0]).toEqual x: 0, y: 0, z: 0 expect(ply.vertex[1]).toEqual x: 0, y: 0, z: 1 expect(ply.vertex[2]).toEqual x: 0, y: 1, z: 1 expect(ply.vertex[3]).toEqual x: 0, y: 1, z: 0 expect(ply.vertex[4]).toEqual x: 1, y: 0, z: 0 expect(ply.vertex[5]).toEqual x: 1, y: 0, z: 1 expect(ply.vertex[6]).toEqual x: 1, y: 1, z: 1 expect(ply.vertex[7]).toEqual x: 1, y: 1, z: 0 it "should detect the vertex indices for each face in order", -> expect(ply.face[0].vertex_index).toEqual [0, 1, 2, 3] expect(ply.face[1].vertex_index).toEqual [7, 6, 5, 4] expect(ply.face[2].vertex_index).toEqual [0, 4, 5, 1] expect(ply.face[3].vertex_index).toEqual [1, 5, 6, 2] expect(ply.face[4].vertex_index).toEqual [2, 6, 7, 3] expect(ply.face[5].vertex_index).toEqual [3, 7, 4, 0]
true
describe "Jax.Mesh.PLY.Parser", -> ply = null describe "parsing binary 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser 'ply\nformat binary_big_endian 1.0\ncomment author: Paraform\nobj_info 3D colored patch boundaries \nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty uchar intensity\nproperty list uchar int vertex_indices\nend_header\n@\xBC\xA0aA<\x9DJA\xDAD\u0013\x99\x03\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03' it "should parse ok", -> expect(ply.vertex[0]).toEqual x: 5.894577503204346, y: 11.788400650024414, z: 27.283239364624023 expect(ply.face[0].vertex_indices).toEqual [1, 2, 3] expect(ply.face[0].intensity).toEqual 0x99 it "stringToBytes", -> stb = Jax.Mesh.PLY.Parser.prototype.stringToBytes expect(stb.call(Jax.Mesh.PLY.Parser.prototype, 'a')).toEqual [97] expect(stb.call(Jax.Mesh.PLY.Parser.prototype, '@\xBC\xA0aA<\x9DJA\xDAD\u0013\xC2UL\xEAB\x865o\xC2e\xCC\xEF@p\b\u0002A\x84\v\u0010A\xEB')).toEqual( [64, 188, 160, 97, 65, 60, 157, 74, 65, 218, 68, 19, 194, 85, 76, 234, 66, 134, 53, 111, 194, 101, 204, 239, 64, 112, 8, 2, 65, 132, 11, 16, 65, 235] ) it "readBinaryValue", -> rbv = Jax.Mesh.PLY.Parser.prototype.readBinaryValue bytes = [64, 188, 160, 97] expect(rbv.call(Jax.Mesh.PLY.Parser.prototype, bytes, 'float', 1)).toEqual(5.894577503204346) describe "parsing ASCII 1.0", -> beforeEach -> ply = new Jax.Mesh.PLY.Parser """ ply format ascii 1.0 comment made by PI:NAME:<NAME>END_PI comment this file is a cube element vertex 8 property float x property float y property float z element face 6 property list uchar int vertex_index end_header 0 0 0 0 0 1 0 1 1 0 1 0 1 0 0 1 0 1 1 1 1 1 1 0 4 0 1 2 3 4 7 6 5 4 4 0 4 5 1 4 1 5 6 2 4 2 6 7 3 4 3 7 4 0 """ it "should find the format", -> expect(ply.format).toEqual 'ascii' it "should find the version", -> expect(ply.version).toEqual '1.0' it "should find both comments, in order", -> expect(ply.comments).toEqual ['made by PI:NAME:<NAME>END_PI', 'this file is a cube'] it "should find 8 vertices", -> expect(ply.vertex.length).toEqual 8 it "should find 6 faces", -> expect(ply.face.length).toEqual 6 it "should detect the vertices in order", -> expect(ply.vertex[0]).toEqual x: 0, y: 0, z: 0 expect(ply.vertex[1]).toEqual x: 0, y: 0, z: 1 expect(ply.vertex[2]).toEqual x: 0, y: 1, z: 1 expect(ply.vertex[3]).toEqual x: 0, y: 1, z: 0 expect(ply.vertex[4]).toEqual x: 1, y: 0, z: 0 expect(ply.vertex[5]).toEqual x: 1, y: 0, z: 1 expect(ply.vertex[6]).toEqual x: 1, y: 1, z: 1 expect(ply.vertex[7]).toEqual x: 1, y: 1, z: 0 it "should detect the vertex indices for each face in order", -> expect(ply.face[0].vertex_index).toEqual [0, 1, 2, 3] expect(ply.face[1].vertex_index).toEqual [7, 6, 5, 4] expect(ply.face[2].vertex_index).toEqual [0, 4, 5, 1] expect(ply.face[3].vertex_index).toEqual [1, 5, 6, 2] expect(ply.face[4].vertex_index).toEqual [2, 6, 7, 3] expect(ply.face[5].vertex_index).toEqual [3, 7, 4, 0]
[ { "context": "tivity: 80\n \"exception-reporting\":\n userId: \"c6217e49-ef83-4b4a-8871-89a5cd4439e4\"\n firacode: {}\n welcome:\n showOnStartup: fal", "end": 484, "score": 0.74614417552948, "start": 449, "tag": "PASSWORD", "value": "6217e49-ef83-4b4a-8871-89a5cd4439e4" } ]
home/.atom/config.cson
christensson/environment
0
"*": "atom-ctags": buildTimeout: 30000 "clang-format": executable: "/usr/bin/clang-format" core: autoHideMenuBar: true customFileTypes: "source.cpp": [ "h.template" ] disabledPackages: [ "symbols-view" "atom-ctags" ] packagesWithKeymapsDisabled: [ "autocomplete-clang" ] telemetryConsent: "no" editor: scrollSensitivity: 80 "exception-reporting": userId: "c6217e49-ef83-4b4a-8871-89a5cd4439e4" firacode: {} welcome: showOnStartup: false
47186
"*": "atom-ctags": buildTimeout: 30000 "clang-format": executable: "/usr/bin/clang-format" core: autoHideMenuBar: true customFileTypes: "source.cpp": [ "h.template" ] disabledPackages: [ "symbols-view" "atom-ctags" ] packagesWithKeymapsDisabled: [ "autocomplete-clang" ] telemetryConsent: "no" editor: scrollSensitivity: 80 "exception-reporting": userId: "c<PASSWORD>" firacode: {} welcome: showOnStartup: false
true
"*": "atom-ctags": buildTimeout: 30000 "clang-format": executable: "/usr/bin/clang-format" core: autoHideMenuBar: true customFileTypes: "source.cpp": [ "h.template" ] disabledPackages: [ "symbols-view" "atom-ctags" ] packagesWithKeymapsDisabled: [ "autocomplete-clang" ] telemetryConsent: "no" editor: scrollSensitivity: 80 "exception-reporting": userId: "cPI:PASSWORD:<PASSWORD>END_PI" firacode: {} welcome: showOnStartup: false
[ { "context": "\n\nmodule.exports = {\n\tgetKey: (date) ->\n\t\treturn 'hubot-doughnuts-' + date.toFormat 'YYYYMMDD'\n\t\t\n\tgetCount: (robot", "end": 156, "score": 0.9459953904151917, "start": 141, "tag": "KEY", "value": "hubot-doughnuts" } ]
src/func/counter.coffee
uramonk/hubot-doughnuts
0
require('date-utils'); dateFunc = require('./date') FIRST_DAY = "hubot-doughnuts-firstday" module.exports = { getKey: (date) -> return 'hubot-doughnuts-' + date.toFormat 'YYYYMMDD' getCount: (robot, key) -> count = robot.brain.get key if count == null count = 0 return count getCountToday: (robot) -> date = new Date() key = this.getKey date return this.getCount robot, key getCountYesterday: (robot) -> date = Date.yesterday() key = this.getKey date return this.getCount robot, key getCountWeekFromToday: (robot) -> date = new Date() return this.getCountWeek robot, date getCountWeek: (robot, fromDate) -> count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(-24) daynum = fromDate.getDay() # 土曜日なら終了 if daynum == 6 break return count getCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.getCount robot, key date = date.addHours(24) return count getCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.getCountMonth robot, year, month date = date.addMonths(1) return count getCountTotal: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break return count clearCount: (robot, key) -> count = robot.brain.get key if count == null return count else robot.brain.remove key robot.brain.save return this.getCount robot, key clearCountToday: (robot) -> date = new Date() key = this.getKey date return this.clearCount robot, key clearCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.clearCount robot, key date = date.addHours(24) return count clearCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.clearCountMonth robot, year, month date = date.addMonths(1) return count clearCountAll: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.clearCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break this.clearCount robot, FIRST_DAY return count addCount: (robot, key, addcount) -> count = robot.brain.get key if count == null count = 0 addnum = count + addcount if addnum < 0 addnum = 0 robot.brain.set key, addnum robot.brain.save return robot.brain.get key addCountToday: (robot, addcount) -> date = new Date() key = this.getKey date return this.addCount robot, key, addcount setFirstDay: (robot) -> date = new Date() formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot if firstday == null robot.brain.set FIRST_DAY, formatted robot.brain.save getFirstDay: (robot) -> return robot.brain.get FIRST_DAY setFirstSpecificDay: (robot, ymdString) -> date = new Date(ymdString) formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot firstDate = new Date(firstday) if firstday == null or Date.compare(date, firstDate) == -1 robot.brain.set FIRST_DAY, formatted robot.brain.save }
92066
require('date-utils'); dateFunc = require('./date') FIRST_DAY = "hubot-doughnuts-firstday" module.exports = { getKey: (date) -> return '<KEY>-' + date.toFormat 'YYYYMMDD' getCount: (robot, key) -> count = robot.brain.get key if count == null count = 0 return count getCountToday: (robot) -> date = new Date() key = this.getKey date return this.getCount robot, key getCountYesterday: (robot) -> date = Date.yesterday() key = this.getKey date return this.getCount robot, key getCountWeekFromToday: (robot) -> date = new Date() return this.getCountWeek robot, date getCountWeek: (robot, fromDate) -> count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(-24) daynum = fromDate.getDay() # 土曜日なら終了 if daynum == 6 break return count getCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.getCount robot, key date = date.addHours(24) return count getCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.getCountMonth robot, year, month date = date.addMonths(1) return count getCountTotal: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break return count clearCount: (robot, key) -> count = robot.brain.get key if count == null return count else robot.brain.remove key robot.brain.save return this.getCount robot, key clearCountToday: (robot) -> date = new Date() key = this.getKey date return this.clearCount robot, key clearCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.clearCount robot, key date = date.addHours(24) return count clearCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.clearCountMonth robot, year, month date = date.addMonths(1) return count clearCountAll: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.clearCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break this.clearCount robot, FIRST_DAY return count addCount: (robot, key, addcount) -> count = robot.brain.get key if count == null count = 0 addnum = count + addcount if addnum < 0 addnum = 0 robot.brain.set key, addnum robot.brain.save return robot.brain.get key addCountToday: (robot, addcount) -> date = new Date() key = this.getKey date return this.addCount robot, key, addcount setFirstDay: (robot) -> date = new Date() formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot if firstday == null robot.brain.set FIRST_DAY, formatted robot.brain.save getFirstDay: (robot) -> return robot.brain.get FIRST_DAY setFirstSpecificDay: (robot, ymdString) -> date = new Date(ymdString) formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot firstDate = new Date(firstday) if firstday == null or Date.compare(date, firstDate) == -1 robot.brain.set FIRST_DAY, formatted robot.brain.save }
true
require('date-utils'); dateFunc = require('./date') FIRST_DAY = "hubot-doughnuts-firstday" module.exports = { getKey: (date) -> return 'PI:KEY:<KEY>END_PI-' + date.toFormat 'YYYYMMDD' getCount: (robot, key) -> count = robot.brain.get key if count == null count = 0 return count getCountToday: (robot) -> date = new Date() key = this.getKey date return this.getCount robot, key getCountYesterday: (robot) -> date = Date.yesterday() key = this.getKey date return this.getCount robot, key getCountWeekFromToday: (robot) -> date = new Date() return this.getCountWeek robot, date getCountWeek: (robot, fromDate) -> count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(-24) daynum = fromDate.getDay() # 土曜日なら終了 if daynum == 6 break return count getCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.getCount robot, key date = date.addHours(24) return count getCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.getCountMonth robot, year, month date = date.addMonths(1) return count getCountTotal: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.getCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break return count clearCount: (robot, key) -> count = robot.brain.get key if count == null return count else robot.brain.remove key robot.brain.save return this.getCount robot, key clearCountToday: (robot) -> date = new Date() key = this.getKey date return this.clearCount robot, key clearCountMonth: (robot, year, month) -> # new Dateの時はmonthを-1する date = new Date(year, month - 1, 1) daysInMonth = dateFunc.getDaysInMonth year, month count = 0 for i in [1..daysInMonth] key = this.getKey date count += this.clearCount robot, key date = date.addHours(24) return count clearCountYear: (robot, year) -> date = new Date(year, 0, 1) count = 0 for month in [1..12] count += this.clearCountMonth robot, year, month date = date.addMonths(1) return count clearCountAll: (robot) -> firstday = this.getFirstDay robot if firstday == null return 0 ymd = firstday.split '/' # new Dateの時はmonthを-1する fromDate = new Date(Number(ymd[0]), Number(ymd[1]) - 1, Number(ymd[2])) toDate = new Date() count = 0 while true key = this.getKey fromDate count += this.clearCount robot, key fromDate = fromDate.addHours(24) if Date.compare(fromDate, toDate) == 1 break this.clearCount robot, FIRST_DAY return count addCount: (robot, key, addcount) -> count = robot.brain.get key if count == null count = 0 addnum = count + addcount if addnum < 0 addnum = 0 robot.brain.set key, addnum robot.brain.save return robot.brain.get key addCountToday: (robot, addcount) -> date = new Date() key = this.getKey date return this.addCount robot, key, addcount setFirstDay: (robot) -> date = new Date() formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot if firstday == null robot.brain.set FIRST_DAY, formatted robot.brain.save getFirstDay: (robot) -> return robot.brain.get FIRST_DAY setFirstSpecificDay: (robot, ymdString) -> date = new Date(ymdString) formatted = date.toFormat 'YYYY/MM/DD' firstday = this.getFirstDay robot firstDate = new Date(firstday) if firstday == null or Date.compare(date, firstDate) == -1 robot.brain.set FIRST_DAY, formatted robot.brain.save }
[ { "context": "# Config Variables\ntoken = 'API_TOKEN'\nqueries = [\"overdue\",\"yesterday\",\"today\",\"tomorr", "end": 37, "score": 0.5988792777061462, "start": 28, "tag": "KEY", "value": "API_TOKEN" } ]
todoist.widget/index.coffee
galenandrew/ubersicht-todoist
5
# Config Variables token = 'API_TOKEN' queries = ["overdue","yesterday","today","tomorrow"] # Local/Instance Variables widgetName: 'Todo List' showDebug: false refreshFrequency: 1000 * 60 * 5 # refreshs every 5 minutes # https://api.todoist.com/API/query?queries=["2014-4-29","overdue","p1","p2"]&token=API_TOKEN rawcommand: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" command: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" render: () -> """ <div class='todoist-widget'> <pre class="debug"></pre> <h1 class='todoist-name'>#{@widgetName}</h1> <div class='todoist-wrapper'></div> </div> """ update: (rawoutput, domEl) -> # convert output to JSON try output = JSON.parse rawoutput catch return # grab dom elements container = $(domEl).find '.todoist-wrapper' .empty() debug = $(domEl).find '.debug' .empty() .hide() unless @showDebug is false debug.append rawoutput debug.show() for obj in output @renderList obj, container renderList: (obj, container) -> listHtml = '' # switch list type for header if obj.type is 'overdue' listName = 'Overdue' else switch obj.query when 'yesterday' then listName = 'Yesterday' when 'today' then listName = 'Today' when 'tomorrow' then listName = 'Tomorrow' else listName = 'Items' listHtml += "<h2 class='todoist-list-name'>#{listName}</h2>" unless obj.data.length listHtml += "<p class='todoist-list none'><i class='todoist-item'>No items</i></p>" else listHtml += "<ul class='todoist-list'>" # iterate over list items for item in obj.data listHtml += "<li class='todoist-item priority-#{item.priority}'>#{item.content}</li>" listHtml += "</ul>" container.append listHtml style: """ .todoist-widget margin-left: 10px width: 500px color: #ffffff font-family: Helvetica Neue text-shadow: 0 0 1px rgba(#000, 0.5) font-size: 12px font-weight: 200 h1 font-size: 24px font-weight: 200 border-bottom: 0.5px solid #ffffff h2 font-size: 18px font-weight: 100 .todoist-list-name margin-bottom: 5px .todoist-list margin-top: 5px &.none opacity: 0.2 .todoist-item &.priority-4 font-weight: 900 &.priority-3 font-weight: 400 opacity: 0.8 &.priority-2 font-weight: 200 opacity: 0.7 &.priority-1 font-weight: 150 opacity: 0.6 .debug font-size: 10px word-wrap: break-word position: absolute width: 750px left: 520px """
217009
# Config Variables token = '<KEY>' queries = ["overdue","yesterday","today","tomorrow"] # Local/Instance Variables widgetName: 'Todo List' showDebug: false refreshFrequency: 1000 * 60 * 5 # refreshs every 5 minutes # https://api.todoist.com/API/query?queries=["2014-4-29","overdue","p1","p2"]&token=API_TOKEN rawcommand: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" command: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" render: () -> """ <div class='todoist-widget'> <pre class="debug"></pre> <h1 class='todoist-name'>#{@widgetName}</h1> <div class='todoist-wrapper'></div> </div> """ update: (rawoutput, domEl) -> # convert output to JSON try output = JSON.parse rawoutput catch return # grab dom elements container = $(domEl).find '.todoist-wrapper' .empty() debug = $(domEl).find '.debug' .empty() .hide() unless @showDebug is false debug.append rawoutput debug.show() for obj in output @renderList obj, container renderList: (obj, container) -> listHtml = '' # switch list type for header if obj.type is 'overdue' listName = 'Overdue' else switch obj.query when 'yesterday' then listName = 'Yesterday' when 'today' then listName = 'Today' when 'tomorrow' then listName = 'Tomorrow' else listName = 'Items' listHtml += "<h2 class='todoist-list-name'>#{listName}</h2>" unless obj.data.length listHtml += "<p class='todoist-list none'><i class='todoist-item'>No items</i></p>" else listHtml += "<ul class='todoist-list'>" # iterate over list items for item in obj.data listHtml += "<li class='todoist-item priority-#{item.priority}'>#{item.content}</li>" listHtml += "</ul>" container.append listHtml style: """ .todoist-widget margin-left: 10px width: 500px color: #ffffff font-family: Helvetica Neue text-shadow: 0 0 1px rgba(#000, 0.5) font-size: 12px font-weight: 200 h1 font-size: 24px font-weight: 200 border-bottom: 0.5px solid #ffffff h2 font-size: 18px font-weight: 100 .todoist-list-name margin-bottom: 5px .todoist-list margin-top: 5px &.none opacity: 0.2 .todoist-item &.priority-4 font-weight: 900 &.priority-3 font-weight: 400 opacity: 0.8 &.priority-2 font-weight: 200 opacity: 0.7 &.priority-1 font-weight: 150 opacity: 0.6 .debug font-size: 10px word-wrap: break-word position: absolute width: 750px left: 520px """
true
# Config Variables token = 'PI:KEY:<KEY>END_PI' queries = ["overdue","yesterday","today","tomorrow"] # Local/Instance Variables widgetName: 'Todo List' showDebug: false refreshFrequency: 1000 * 60 * 5 # refreshs every 5 minutes # https://api.todoist.com/API/query?queries=["2014-4-29","overdue","p1","p2"]&token=API_TOKEN rawcommand: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" command: "curl -s 'https://api.todoist.com/API/query?queries=#{encodeURI JSON.stringify @queries}&token=#{@token}'" render: () -> """ <div class='todoist-widget'> <pre class="debug"></pre> <h1 class='todoist-name'>#{@widgetName}</h1> <div class='todoist-wrapper'></div> </div> """ update: (rawoutput, domEl) -> # convert output to JSON try output = JSON.parse rawoutput catch return # grab dom elements container = $(domEl).find '.todoist-wrapper' .empty() debug = $(domEl).find '.debug' .empty() .hide() unless @showDebug is false debug.append rawoutput debug.show() for obj in output @renderList obj, container renderList: (obj, container) -> listHtml = '' # switch list type for header if obj.type is 'overdue' listName = 'Overdue' else switch obj.query when 'yesterday' then listName = 'Yesterday' when 'today' then listName = 'Today' when 'tomorrow' then listName = 'Tomorrow' else listName = 'Items' listHtml += "<h2 class='todoist-list-name'>#{listName}</h2>" unless obj.data.length listHtml += "<p class='todoist-list none'><i class='todoist-item'>No items</i></p>" else listHtml += "<ul class='todoist-list'>" # iterate over list items for item in obj.data listHtml += "<li class='todoist-item priority-#{item.priority}'>#{item.content}</li>" listHtml += "</ul>" container.append listHtml style: """ .todoist-widget margin-left: 10px width: 500px color: #ffffff font-family: Helvetica Neue text-shadow: 0 0 1px rgba(#000, 0.5) font-size: 12px font-weight: 200 h1 font-size: 24px font-weight: 200 border-bottom: 0.5px solid #ffffff h2 font-size: 18px font-weight: 100 .todoist-list-name margin-bottom: 5px .todoist-list margin-top: 5px &.none opacity: 0.2 .todoist-item &.priority-4 font-weight: 900 &.priority-3 font-weight: 400 opacity: 0.8 &.priority-2 font-weight: 200 opacity: 0.7 &.priority-1 font-weight: 150 opacity: 0.6 .debug font-size: 10px word-wrap: break-word position: absolute width: 750px left: 520px """
[ { "context": "### Copyright (c) 2014 Magnus Leo. All rights reserved. ###\n\ncore = require('./modu", "end": 33, "score": 0.9998546838760376, "start": 23, "tag": "NAME", "value": "Magnus Leo" }, { "context": "Background\n\n layers.add new Layer\n id: 'mountains'\n sp...
src/main.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2014 Magnus Leo. All rights reserved. ### core = require('./modules/core') event = require('./modules/event') Layer = require('./classes/Layer') layers = require('./modules/layers') Player = require('./classes/Player') Sprite = require('./classes/Sprite') util = require('./modules/util') view = require('./modules/view') window.addEventListener 'load', -> core.init() # Events event.keydown = (e) -> key = util.KEY_CODES switch e.keyCode when key.R window.location.reload() else player.handleInput(e) event.keyup = (e) -> player.handleInput(e) # Player playerSprite = new Sprite('sprite-olle.png') playerSprite.addAnimation name: 'jumpingLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-4, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'jumpingRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-8, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'runningLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-6, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:33, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'runningRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-9, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:0, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'standingLeft' frames: [ {x:0, y:33, w:19, h:32, offsetX:1, offsetY:0, duration:1} ] isLooping: false playerSprite.addAnimation name: 'standingRight' frames: [ {x:0, y:0, w:19, h:32, offsetX:-1, offsetY:0, duration:1} ] isLooping: false player = new Player sprite: playerSprite posX: 6 posY: 6 colW: 1 colH: 2 speedXMax: 9 accelerationAir: 900 decelerationAir: 900 accelerationGround: 900 decelerationGround: 900 # Camera core.cycleCallback = -> view.cameraPosX = player.posX - 15 # Background layers.add new Layer id: 'mountains' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.5 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 10 tiles: [-1,5,6,-1,-1,-1,-1,-1,-1,-1,20,21,22,23,-1,-1,-1,27,28,-1,36,37,38,39,40,-1,42,43,44,45,52,53,54,55,56,57,58,59,60,61,68,69,70,71,72,73,74,75,76,77,68,68,68,68,68,68,68,68,68,68,7,8,9,10,11,7,8,9,10,11] width: 10 ] layers.add new Layer id: 'cloud 1' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.21 chunks: [ chunkOffsetX: 50 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 30 tileOffsetY: 3 tiles: [0,1,2,3,16,17,18,19] width: 4 ] layers.add new Layer id: 'cloud 2' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.2 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 29 tileOffsetY: 5 tiles: [0,1,2,3,16,17,18,19] width: 4 ] # Ground layers.add new Layer id: 'ground' spritesheet: 'sprite-background.png' chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,32,34,33,35,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,35,-1,-1,-1,-1,-1,-1,-1,48,51,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,34,33,34,33,35,48,49,50,49,50,33,34,35,-1,-1,-1,-1,48,51,-1,-1,-1,-1,32,33,34,50,49,50,49,50,49,50,49,51,48,49,50,49,50,49,50,49,34,33,34,33,50,49,34,33,34,33,50,49,50,50,49,50,49,50,49,50,49,51] width: 30 , chunkOffsetX: 30 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,35,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51] width: 30 ]
140937
### Copyright (c) 2014 <NAME>. All rights reserved. ### core = require('./modules/core') event = require('./modules/event') Layer = require('./classes/Layer') layers = require('./modules/layers') Player = require('./classes/Player') Sprite = require('./classes/Sprite') util = require('./modules/util') view = require('./modules/view') window.addEventListener 'load', -> core.init() # Events event.keydown = (e) -> key = util.KEY_CODES switch e.keyCode when key.R window.location.reload() else player.handleInput(e) event.keyup = (e) -> player.handleInput(e) # Player playerSprite = new Sprite('sprite-olle.png') playerSprite.addAnimation name: 'jumpingLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-4, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'jumpingRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-8, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'runningLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-6, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:33, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'runningRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-9, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:0, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'standingLeft' frames: [ {x:0, y:33, w:19, h:32, offsetX:1, offsetY:0, duration:1} ] isLooping: false playerSprite.addAnimation name: 'standingRight' frames: [ {x:0, y:0, w:19, h:32, offsetX:-1, offsetY:0, duration:1} ] isLooping: false player = new Player sprite: playerSprite posX: 6 posY: 6 colW: 1 colH: 2 speedXMax: 9 accelerationAir: 900 decelerationAir: 900 accelerationGround: 900 decelerationGround: 900 # Camera core.cycleCallback = -> view.cameraPosX = player.posX - 15 # Background layers.add new Layer id: 'mountains' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.5 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 10 tiles: [-1,5,6,-1,-1,-1,-1,-1,-1,-1,20,21,22,23,-1,-1,-1,27,28,-1,36,37,38,39,40,-1,42,43,44,45,52,53,54,55,56,57,58,59,60,61,68,69,70,71,72,73,74,75,76,77,68,68,68,68,68,68,68,68,68,68,7,8,9,10,11,7,8,9,10,11] width: 10 ] layers.add new Layer id: 'cloud 1' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.21 chunks: [ chunkOffsetX: 50 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 30 tileOffsetY: 3 tiles: [0,1,2,3,16,17,18,19] width: 4 ] layers.add new Layer id: 'cloud 2' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.2 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 29 tileOffsetY: 5 tiles: [0,1,2,3,16,17,18,19] width: 4 ] # Ground layers.add new Layer id: 'ground' spritesheet: 'sprite-background.png' chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,32,34,33,35,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,35,-1,-1,-1,-1,-1,-1,-1,48,51,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,34,33,34,33,35,48,49,50,49,50,33,34,35,-1,-1,-1,-1,48,51,-1,-1,-1,-1,32,33,34,50,49,50,49,50,49,50,49,51,48,49,50,49,50,49,50,49,34,33,34,33,50,49,34,33,34,33,50,49,50,50,49,50,49,50,49,50,49,51] width: 30 , chunkOffsetX: 30 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,35,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51] width: 30 ]
true
### Copyright (c) 2014 PI:NAME:<NAME>END_PI. All rights reserved. ### core = require('./modules/core') event = require('./modules/event') Layer = require('./classes/Layer') layers = require('./modules/layers') Player = require('./classes/Player') Sprite = require('./classes/Sprite') util = require('./modules/util') view = require('./modules/view') window.addEventListener 'load', -> core.init() # Events event.keydown = (e) -> key = util.KEY_CODES switch e.keyCode when key.R window.location.reload() else player.handleInput(e) event.keyup = (e) -> player.handleInput(e) # Player playerSprite = new Sprite('sprite-olle.png') playerSprite.addAnimation name: 'jumpingLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-4, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'jumpingRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-8, offsetY:0, duration:0.192} ] isLooping: false playerSprite.addAnimation name: 'runningLeft' frames: [ {x:19, y:33, w:30, h:32, offsetX:-6, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:33, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:33, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'runningRight' frames: [ {x:19, y:0, w:30, h:32, offsetX:-9, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} {x:62, y:0, w:23, h:32, offsetX:-4, offsetY:-1, duration:0.18} {x:49, y:0, w:13, h:32, offsetX:1, offsetY:0, duration:0.13} ] isLooping: true playerSprite.addAnimation name: 'standingLeft' frames: [ {x:0, y:33, w:19, h:32, offsetX:1, offsetY:0, duration:1} ] isLooping: false playerSprite.addAnimation name: 'standingRight' frames: [ {x:0, y:0, w:19, h:32, offsetX:-1, offsetY:0, duration:1} ] isLooping: false player = new Player sprite: playerSprite posX: 6 posY: 6 colW: 1 colH: 2 speedXMax: 9 accelerationAir: 900 decelerationAir: 900 accelerationGround: 900 decelerationGround: 900 # Camera core.cycleCallback = -> view.cameraPosX = player.posX - 15 # Background layers.add new Layer id: 'mountains' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.5 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 10 tiles: [-1,5,6,-1,-1,-1,-1,-1,-1,-1,20,21,22,23,-1,-1,-1,27,28,-1,36,37,38,39,40,-1,42,43,44,45,52,53,54,55,56,57,58,59,60,61,68,69,70,71,72,73,74,75,76,77,68,68,68,68,68,68,68,68,68,68,7,8,9,10,11,7,8,9,10,11] width: 10 ] layers.add new Layer id: 'cloud 1' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.21 chunks: [ chunkOffsetX: 50 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 30 tileOffsetY: 3 tiles: [0,1,2,3,16,17,18,19] width: 4 ] layers.add new Layer id: 'cloud 2' spritesheet: 'sprite-background.png' isLooping: true parallax: 0.2 chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 29 tileOffsetY: 5 tiles: [0,1,2,3,16,17,18,19] width: 4 ] # Ground layers.add new Layer id: 'ground' spritesheet: 'sprite-background.png' chunks: [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,32,34,33,35,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,35,-1,-1,-1,-1,-1,-1,-1,48,51,-1,-1,-1,-1,-1,-1,-1,32,33,34,33,34,33,34,33,35,48,49,50,49,50,33,34,35,-1,-1,-1,-1,48,51,-1,-1,-1,-1,32,33,34,50,49,50,49,50,49,50,49,51,48,49,50,49,50,49,50,49,34,33,34,33,50,49,34,33,34,33,50,49,50,50,49,50,49,50,49,50,49,51] width: 30 , chunkOffsetX: 30 chunkOffsetY: 0 colBoxes: [] tileOffsetX: 0 tileOffsetY: 13 tiles: [-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,34,33,35,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51,48,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,50,49,51] width: 30 ]
[ { "context": " new SvelteOutput()\n\tprocess.env['cielo.name'] = 'John'\n\toOutput.putLine \"<p>\"\n\toOutput.putLine \"my name", "end": 2213, "score": 0.9995478987693787, "start": 2209, "tag": "NAME", "value": "John" }, { "context": "tester.equal 103, oOutput, \"\"\"\n\t\t<p>\n\t\t\...
test/SvelteOutput.test.coffee
johndeighan/svelte-output
0
# SvelteOutput.test.coffee import assert from 'assert' import { say, undef, sep_dash, escapeStr, } from '@jdeighan/coffee-utils' import {log} from '@jdeighan/coffee-utils/log' import {mydir, mkpath} from '@jdeighan/coffee-utils/fs' import {UnitTester} from '@jdeighan/coffee-utils/test' import {loadEnvFrom} from '@jdeighan/env' import {convertCoffee} from '@jdeighan/string-input/coffee' import {convertSASS} from '@jdeighan/string-input/sass' import {SvelteOutput} from '@jdeighan/svelte-output' # ----- Contents of ./.env ----- # cielo.companyName = WayForward Technologies, Inc. # DIR_COMPONENTS = $DIR_ROOT/components # ------------------------------- dir = mydir(`import.meta.url`) process.env.DIR_ROOT = dir loadEnvFrom(dir) convertCoffee false convertSASS false simple = new UnitTester() # --------------------------------------------------------------------------- class OutputTester extends UnitTester transformValue: (oOutput) -> return oOutput.get() normalize: (str) -> return str # disable normalize tester = new OutputTester() # --------------------------------------------------------------------------- # --- Test simple output (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" simple.truthy 44, oOutput.hasSection('html') simple.falsy 45, oOutput.hasSection('script') tester.equal 47, oOutput, """ <p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "</p>" tester.equal 57, oOutput, """ <p> </p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "this is a paragraph", 1 oOutput.putLine "</p>" tester.equal 69, oOutput, """ <p> this is a paragraph </p> """ )() # --------------------------------------------------------------------------- # --- Test interpolation (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" process.env['cielo.LINE'] = 2 oOutput.putLine "this is line {{LINE}}", 1 process.env['cielo.LINE'] = 3 oOutput.putLine "this is line {{LINE}}", 1 oOutput.putLine "</p>" tester.equal 88, oOutput, """ <p> this is line 2 this is line 3 </p> """ )() (()-> oOutput = new SvelteOutput() process.env['cielo.name'] = 'John' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "</p>" tester.equal 103, oOutput, """ <p> my name is John </p> """ )() (()-> oOutput = new SvelteOutput('unit test') process.env['cielo.name'] = 'John' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "my company is {{companyName}}", 1 oOutput.putLine "</p>" tester.equal 120, oOutput, """ <p> my name is John my company is WayForward Technologies, Inc. </p> """ )() # --------------------------------------------------------------------------- # --- Test auto-import of components (()-> oOutput = new SvelteOutput('unit test') oOutput.addComponent 'Para' oOutput.putLine "<Para>" oOutput.putLine "this is a para", 1 oOutput.putLine "</Para>" tester.equal 140, oOutput, """ <Para> this is a para </Para> <script> import Para from '#{process.env.DIR_COMPONENTS}/Para.svelte' </script> """ )() # --------------------------------------------------------------------------- # --- Test script section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putScript "x = 23", 1 simple.truthy 158, oOutput.hasSection('html') simple.truthy 159, oOutput.hasSection('script') simple.falsy 160, oOutput.hasSection('style') tester.equal 162, oOutput, """ <p> this is text </p> <script> x = 23 </script> """ )() # --------------------------------------------------------------------------- # --- Test addImport (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.addImport "import {myfunc} from 'mylib'" simple.truthy 182, oOutput.hasSection('html') simple.truthy 183, oOutput.hasSection('script') simple.falsy 184, oOutput.hasSection('style') tester.equal 186, oOutput, """ <p> this is text </p> <script> import {myfunc} from 'mylib' </script> """ )() # --------------------------------------------------------------------------- # --- Test declaring JS vars (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' simple.truthy 206, oOutput.hasSection('html') simple.truthy 207, oOutput.hasSection('script') simple.falsy 208, oOutput.hasSection('style') tester.equal 210, oOutput, """ <p> this is text </p> <script> import {undef} from '@jdeighan/coffee-utils' name = undef </script> """ )() # --------------------------------------------------------------------------- # --- Test startup section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 simple.truthy 232, oOutput.hasSection('startup') simple.truthy 233, oOutput.hasSection('html') simple.falsy 234, oOutput.hasSection('script') simple.falsy 235, oOutput.hasSection('style') tester.equal 237, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> """ )() # --------------------------------------------------------------------------- # --- Test startup AND script sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 simple.truthy 258, oOutput.hasSection('startup') simple.truthy 259, oOutput.hasSection('html') simple.truthy 260, oOutput.hasSection('script') simple.falsy 261, oOutput.hasSection('style') tester.equal 263, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test style section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "p", 0 oOutput.putStyle "color: red", 1 simple.falsy 287, oOutput.hasSection('startup') simple.truthy 288, oOutput.hasSection('html') simple.falsy 289, oOutput.hasSection('script') simple.truthy 290, oOutput.hasSection('style') tester.equal 292, oOutput, """ <p> this is text </p> <style> p color: red </style> """ )() (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "main\n\toverflow: auto\n\nnav\n\toverflow: auto", 0 simple.falsy 310, oOutput.hasSection('startup') simple.truthy 311, oOutput.hasSection('html') simple.falsy 312, oOutput.hasSection('script') simple.truthy 313, oOutput.hasSection('style') tester.equal 315, oOutput, """ <p> this is text </p> <style> main overflow: auto nav overflow: auto </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 simple.truthy 342, oOutput.hasSection('startup') simple.truthy 343, oOutput.hasSection('html') simple.truthy 344, oOutput.hasSection('script') simple.truthy 345, oOutput.hasSection('style') tester.equal 347, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections # - order of sections doesn't matter (()-> oOutput = new SvelteOutput oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" tester.equal 378, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test assigning JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "this is a sentence") oOutput.putLine "</div>" tester.equal 405, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "this is a sentence" </script> """ )() # --------------------------------------------------------------------------- # --- Test assigning multi-line JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "line 1\nline 2\nline 3") oOutput.putLine "</div>" tester.equal 425, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "line 1\\nline 2\\nline 3" </script> """ )() # --------------------------------------------------------------------------- # --- Test included markdown files (()-> filename = 'test.md' html = "<h1>Contents of #{filename}</h1>" oOutput = new SvelteOutput() oOutput.putLine "<div class=\"markdown\">", 0 oOutput.putJSVar('myhtml', html) oOutput.putLine "{@html myhtml}", 1 oOutput.putLine "</div>" tester.equal 448, oOutput, """ <div class="markdown"> {@html myhtml} </div> <script> myhtml = "<h1>Contents of #{filename}</h1>" </script> """ )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 465, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 475, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test simple anonymous variables (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" var1 = oOutput.addVar(42) var2 = oOutput.addVar("abc") simple.equal 488, var1, '__anonVar0' simple.equal 489, var2, '__anonVar1' )() # --------------------------------------------------------------------------- # --- Test simple anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar('blue') var2 = oOutput.addVar(42) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 501, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = "blue" #{var2} = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test complex anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar([1,2,'x']) var2 = oOutput.addVar({a:12, b:'xyz'}) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 519, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = [1,2,"x"] #{var2} = {"a":12,"b":"xyz"} </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)", "handler") tester.equal 535, oOutput, """ <script> handler = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)") tester.equal 549, oOutput, """ <script> __anonVar0 = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b", "calc") tester.equal 563, oOutput, """ <script> calc = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b") tester.equal 577, oOutput, """ <script> __anonVar0 = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """, 'lItems') tester.equal 595, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' lItems = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML without name (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """) tester.equal 618, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' __anonVar0 = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test auto-import (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' oOutput.putScript "say 'Hi, there'", 1 simple.truthy 641, oOutput.hasSection('html') simple.truthy 642, oOutput.hasSection('script') simple.falsy 643, oOutput.hasSection('style') tester.equal 645, oOutput, """ <p> this is text </p> <script> import {undef,say} from '@jdeighan/coffee-utils' name = undef say 'Hi, there' </script> """ )() # --------------------------------------------------------------------------- # --- Test preprocessing (()-> oOutput = new SvelteOutput oOutput.putScript """ count = 0 doubled <== 2 * count """, 1 simple.falsy 668, oOutput.hasSection('html') simple.truthy 669, oOutput.hasSection('script') simple.falsy 670, oOutput.hasSection('style') tester.equal 672, oOutput, """ <script> count = 0 `$:` doubled = 2 * count </script> """ )()
80597
# SvelteOutput.test.coffee import assert from 'assert' import { say, undef, sep_dash, escapeStr, } from '@jdeighan/coffee-utils' import {log} from '@jdeighan/coffee-utils/log' import {mydir, mkpath} from '@jdeighan/coffee-utils/fs' import {UnitTester} from '@jdeighan/coffee-utils/test' import {loadEnvFrom} from '@jdeighan/env' import {convertCoffee} from '@jdeighan/string-input/coffee' import {convertSASS} from '@jdeighan/string-input/sass' import {SvelteOutput} from '@jdeighan/svelte-output' # ----- Contents of ./.env ----- # cielo.companyName = WayForward Technologies, Inc. # DIR_COMPONENTS = $DIR_ROOT/components # ------------------------------- dir = mydir(`import.meta.url`) process.env.DIR_ROOT = dir loadEnvFrom(dir) convertCoffee false convertSASS false simple = new UnitTester() # --------------------------------------------------------------------------- class OutputTester extends UnitTester transformValue: (oOutput) -> return oOutput.get() normalize: (str) -> return str # disable normalize tester = new OutputTester() # --------------------------------------------------------------------------- # --- Test simple output (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" simple.truthy 44, oOutput.hasSection('html') simple.falsy 45, oOutput.hasSection('script') tester.equal 47, oOutput, """ <p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "</p>" tester.equal 57, oOutput, """ <p> </p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "this is a paragraph", 1 oOutput.putLine "</p>" tester.equal 69, oOutput, """ <p> this is a paragraph </p> """ )() # --------------------------------------------------------------------------- # --- Test interpolation (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" process.env['cielo.LINE'] = 2 oOutput.putLine "this is line {{LINE}}", 1 process.env['cielo.LINE'] = 3 oOutput.putLine "this is line {{LINE}}", 1 oOutput.putLine "</p>" tester.equal 88, oOutput, """ <p> this is line 2 this is line 3 </p> """ )() (()-> oOutput = new SvelteOutput() process.env['cielo.name'] = '<NAME>' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "</p>" tester.equal 103, oOutput, """ <p> my name is <NAME> </p> """ )() (()-> oOutput = new SvelteOutput('unit test') process.env['cielo.name'] = '<NAME>' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "my company is {{companyName}}", 1 oOutput.putLine "</p>" tester.equal 120, oOutput, """ <p> my name is <NAME> my company is WayForward Technologies, Inc. </p> """ )() # --------------------------------------------------------------------------- # --- Test auto-import of components (()-> oOutput = new SvelteOutput('unit test') oOutput.addComponent 'Para' oOutput.putLine "<Para>" oOutput.putLine "this is a para", 1 oOutput.putLine "</Para>" tester.equal 140, oOutput, """ <Para> this is a para </Para> <script> import Para from '#{process.env.DIR_COMPONENTS}/Para.svelte' </script> """ )() # --------------------------------------------------------------------------- # --- Test script section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putScript "x = 23", 1 simple.truthy 158, oOutput.hasSection('html') simple.truthy 159, oOutput.hasSection('script') simple.falsy 160, oOutput.hasSection('style') tester.equal 162, oOutput, """ <p> this is text </p> <script> x = 23 </script> """ )() # --------------------------------------------------------------------------- # --- Test addImport (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.addImport "import {myfunc} from 'mylib'" simple.truthy 182, oOutput.hasSection('html') simple.truthy 183, oOutput.hasSection('script') simple.falsy 184, oOutput.hasSection('style') tester.equal 186, oOutput, """ <p> this is text </p> <script> import {myfunc} from 'mylib' </script> """ )() # --------------------------------------------------------------------------- # --- Test declaring JS vars (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' simple.truthy 206, oOutput.hasSection('html') simple.truthy 207, oOutput.hasSection('script') simple.falsy 208, oOutput.hasSection('style') tester.equal 210, oOutput, """ <p> this is text </p> <script> import {undef} from '@jdeighan/coffee-utils' name = undef </script> """ )() # --------------------------------------------------------------------------- # --- Test startup section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 simple.truthy 232, oOutput.hasSection('startup') simple.truthy 233, oOutput.hasSection('html') simple.falsy 234, oOutput.hasSection('script') simple.falsy 235, oOutput.hasSection('style') tester.equal 237, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> """ )() # --------------------------------------------------------------------------- # --- Test startup AND script sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 simple.truthy 258, oOutput.hasSection('startup') simple.truthy 259, oOutput.hasSection('html') simple.truthy 260, oOutput.hasSection('script') simple.falsy 261, oOutput.hasSection('style') tester.equal 263, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test style section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "p", 0 oOutput.putStyle "color: red", 1 simple.falsy 287, oOutput.hasSection('startup') simple.truthy 288, oOutput.hasSection('html') simple.falsy 289, oOutput.hasSection('script') simple.truthy 290, oOutput.hasSection('style') tester.equal 292, oOutput, """ <p> this is text </p> <style> p color: red </style> """ )() (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "main\n\toverflow: auto\n\nnav\n\toverflow: auto", 0 simple.falsy 310, oOutput.hasSection('startup') simple.truthy 311, oOutput.hasSection('html') simple.falsy 312, oOutput.hasSection('script') simple.truthy 313, oOutput.hasSection('style') tester.equal 315, oOutput, """ <p> this is text </p> <style> main overflow: auto nav overflow: auto </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 simple.truthy 342, oOutput.hasSection('startup') simple.truthy 343, oOutput.hasSection('html') simple.truthy 344, oOutput.hasSection('script') simple.truthy 345, oOutput.hasSection('style') tester.equal 347, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections # - order of sections doesn't matter (()-> oOutput = new SvelteOutput oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" tester.equal 378, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test assigning JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "this is a sentence") oOutput.putLine "</div>" tester.equal 405, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "this is a sentence" </script> """ )() # --------------------------------------------------------------------------- # --- Test assigning multi-line JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "line 1\nline 2\nline 3") oOutput.putLine "</div>" tester.equal 425, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "line 1\\nline 2\\nline 3" </script> """ )() # --------------------------------------------------------------------------- # --- Test included markdown files (()-> filename = 'test.md' html = "<h1>Contents of #{filename}</h1>" oOutput = new SvelteOutput() oOutput.putLine "<div class=\"markdown\">", 0 oOutput.putJSVar('myhtml', html) oOutput.putLine "{@html myhtml}", 1 oOutput.putLine "</div>" tester.equal 448, oOutput, """ <div class="markdown"> {@html myhtml} </div> <script> myhtml = "<h1>Contents of #{filename}</h1>" </script> """ )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 465, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 475, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test simple anonymous variables (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" var1 = oOutput.addVar(42) var2 = oOutput.addVar("abc") simple.equal 488, var1, '__anonVar0' simple.equal 489, var2, '__anonVar1' )() # --------------------------------------------------------------------------- # --- Test simple anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar('blue') var2 = oOutput.addVar(42) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 501, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = "blue" #{var2} = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test complex anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar([1,2,'x']) var2 = oOutput.addVar({a:12, b:'xyz'}) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 519, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = [1,2,"x"] #{var2} = {"a":12,"b":"xyz"} </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)", "handler") tester.equal 535, oOutput, """ <script> handler = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)") tester.equal 549, oOutput, """ <script> __anonVar0 = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b", "calc") tester.equal 563, oOutput, """ <script> calc = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b") tester.equal 577, oOutput, """ <script> __anonVar0 = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """, 'lItems') tester.equal 595, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' lItems = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML without name (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """) tester.equal 618, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' __anonVar0 = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test auto-import (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' oOutput.putScript "say 'Hi, there'", 1 simple.truthy 641, oOutput.hasSection('html') simple.truthy 642, oOutput.hasSection('script') simple.falsy 643, oOutput.hasSection('style') tester.equal 645, oOutput, """ <p> this is text </p> <script> import {undef,say} from '@jdeighan/coffee-utils' name = undef say 'Hi, there' </script> """ )() # --------------------------------------------------------------------------- # --- Test preprocessing (()-> oOutput = new SvelteOutput oOutput.putScript """ count = 0 doubled <== 2 * count """, 1 simple.falsy 668, oOutput.hasSection('html') simple.truthy 669, oOutput.hasSection('script') simple.falsy 670, oOutput.hasSection('style') tester.equal 672, oOutput, """ <script> count = 0 `$:` doubled = 2 * count </script> """ )()
true
# SvelteOutput.test.coffee import assert from 'assert' import { say, undef, sep_dash, escapeStr, } from '@jdeighan/coffee-utils' import {log} from '@jdeighan/coffee-utils/log' import {mydir, mkpath} from '@jdeighan/coffee-utils/fs' import {UnitTester} from '@jdeighan/coffee-utils/test' import {loadEnvFrom} from '@jdeighan/env' import {convertCoffee} from '@jdeighan/string-input/coffee' import {convertSASS} from '@jdeighan/string-input/sass' import {SvelteOutput} from '@jdeighan/svelte-output' # ----- Contents of ./.env ----- # cielo.companyName = WayForward Technologies, Inc. # DIR_COMPONENTS = $DIR_ROOT/components # ------------------------------- dir = mydir(`import.meta.url`) process.env.DIR_ROOT = dir loadEnvFrom(dir) convertCoffee false convertSASS false simple = new UnitTester() # --------------------------------------------------------------------------- class OutputTester extends UnitTester transformValue: (oOutput) -> return oOutput.get() normalize: (str) -> return str # disable normalize tester = new OutputTester() # --------------------------------------------------------------------------- # --- Test simple output (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" simple.truthy 44, oOutput.hasSection('html') simple.falsy 45, oOutput.hasSection('script') tester.equal 47, oOutput, """ <p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "</p>" tester.equal 57, oOutput, """ <p> </p> """ )() (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" oOutput.putLine "this is a paragraph", 1 oOutput.putLine "</p>" tester.equal 69, oOutput, """ <p> this is a paragraph </p> """ )() # --------------------------------------------------------------------------- # --- Test interpolation (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" process.env['cielo.LINE'] = 2 oOutput.putLine "this is line {{LINE}}", 1 process.env['cielo.LINE'] = 3 oOutput.putLine "this is line {{LINE}}", 1 oOutput.putLine "</p>" tester.equal 88, oOutput, """ <p> this is line 2 this is line 3 </p> """ )() (()-> oOutput = new SvelteOutput() process.env['cielo.name'] = 'PI:NAME:<NAME>END_PI' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "</p>" tester.equal 103, oOutput, """ <p> my name is PI:NAME:<NAME>END_PI </p> """ )() (()-> oOutput = new SvelteOutput('unit test') process.env['cielo.name'] = 'PI:NAME:<NAME>END_PI' oOutput.putLine "<p>" oOutput.putLine "my name is {{name}}", 1 oOutput.putLine "my company is {{companyName}}", 1 oOutput.putLine "</p>" tester.equal 120, oOutput, """ <p> my name is PI:NAME:<NAME>END_PI my company is WayForward Technologies, Inc. </p> """ )() # --------------------------------------------------------------------------- # --- Test auto-import of components (()-> oOutput = new SvelteOutput('unit test') oOutput.addComponent 'Para' oOutput.putLine "<Para>" oOutput.putLine "this is a para", 1 oOutput.putLine "</Para>" tester.equal 140, oOutput, """ <Para> this is a para </Para> <script> import Para from '#{process.env.DIR_COMPONENTS}/Para.svelte' </script> """ )() # --------------------------------------------------------------------------- # --- Test script section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putScript "x = 23", 1 simple.truthy 158, oOutput.hasSection('html') simple.truthy 159, oOutput.hasSection('script') simple.falsy 160, oOutput.hasSection('style') tester.equal 162, oOutput, """ <p> this is text </p> <script> x = 23 </script> """ )() # --------------------------------------------------------------------------- # --- Test addImport (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.addImport "import {myfunc} from 'mylib'" simple.truthy 182, oOutput.hasSection('html') simple.truthy 183, oOutput.hasSection('script') simple.falsy 184, oOutput.hasSection('style') tester.equal 186, oOutput, """ <p> this is text </p> <script> import {myfunc} from 'mylib' </script> """ )() # --------------------------------------------------------------------------- # --- Test declaring JS vars (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' simple.truthy 206, oOutput.hasSection('html') simple.truthy 207, oOutput.hasSection('script') simple.falsy 208, oOutput.hasSection('style') tester.equal 210, oOutput, """ <p> this is text </p> <script> import {undef} from '@jdeighan/coffee-utils' name = undef </script> """ )() # --------------------------------------------------------------------------- # --- Test startup section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 simple.truthy 232, oOutput.hasSection('startup') simple.truthy 233, oOutput.hasSection('html') simple.falsy 234, oOutput.hasSection('script') simple.falsy 235, oOutput.hasSection('style') tester.equal 237, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> """ )() # --------------------------------------------------------------------------- # --- Test startup AND script sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 simple.truthy 258, oOutput.hasSection('startup') simple.truthy 259, oOutput.hasSection('html') simple.truthy 260, oOutput.hasSection('script') simple.falsy 261, oOutput.hasSection('style') tester.equal 263, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test style section (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "p", 0 oOutput.putStyle "color: red", 1 simple.falsy 287, oOutput.hasSection('startup') simple.truthy 288, oOutput.hasSection('html') simple.falsy 289, oOutput.hasSection('script') simple.truthy 290, oOutput.hasSection('style') tester.equal 292, oOutput, """ <p> this is text </p> <style> p color: red </style> """ )() (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStyle "main\n\toverflow: auto\n\nnav\n\toverflow: auto", 0 simple.falsy 310, oOutput.hasSection('startup') simple.truthy 311, oOutput.hasSection('html') simple.falsy 312, oOutput.hasSection('script') simple.truthy 313, oOutput.hasSection('style') tester.equal 315, oOutput, """ <p> this is text </p> <style> main overflow: auto nav overflow: auto </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 simple.truthy 342, oOutput.hasSection('startup') simple.truthy 343, oOutput.hasSection('html') simple.truthy 344, oOutput.hasSection('script') simple.truthy 345, oOutput.hasSection('style') tester.equal 347, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test startup, script AND style sections # - order of sections doesn't matter (()-> oOutput = new SvelteOutput oOutput.putStartup "x = 23", 1 oOutput.putScript "x = 42", 1 oOutput.putStyle "p", 1 oOutput.putStyle "color: red", 2 oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" tester.equal 378, oOutput, """ <script context="module"> x = 23 </script> <p> this is text </p> <script> x = 42 </script> <style> p color: red </style> """ )() # --------------------------------------------------------------------------- # --- Test assigning JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "this is a sentence") oOutput.putLine "</div>" tester.equal 405, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "this is a sentence" </script> """ )() # --------------------------------------------------------------------------- # --- Test assigning multi-line JS Vars (()-> oOutput = new SvelteOutput() oOutput.putLine "<div>" oOutput.putLine "<p>a paragraph</p>", 1 oOutput.putJSVar('str', "line 1\nline 2\nline 3") oOutput.putLine "</div>" tester.equal 425, oOutput, """ <div> <p>a paragraph</p> </div> <script> str = "line 1\\nline 2\\nline 3" </script> """ )() # --------------------------------------------------------------------------- # --- Test included markdown files (()-> filename = 'test.md' html = "<h1>Contents of #{filename}</h1>" oOutput = new SvelteOutput() oOutput.putLine "<div class=\"markdown\">", 0 oOutput.putJSVar('myhtml', html) oOutput.putLine "{@html myhtml}", 1 oOutput.putLine "</div>" tester.equal 448, oOutput, """ <div class="markdown"> {@html myhtml} </div> <script> myhtml = "<h1>Contents of #{filename}</h1>" </script> """ )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 465, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test expressions (()-> oOutput = new SvelteOutput() oOutput.putCmdWithExpr "{#if ", "loggedIn?", "}" simple.equal 475, oOutput.get(), "{#if loggedIn?}" )() # --------------------------------------------------------------------------- # --- Test simple anonymous variables (()-> oOutput = new SvelteOutput() oOutput.putLine "<p>" var1 = oOutput.addVar(42) var2 = oOutput.addVar("abc") simple.equal 488, var1, '__anonVar0' simple.equal 489, var2, '__anonVar1' )() # --------------------------------------------------------------------------- # --- Test simple anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar('blue') var2 = oOutput.addVar(42) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 501, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = "blue" #{var2} = 42 </script> """ )() # --------------------------------------------------------------------------- # --- Test complex anonymous variable output (()-> oOutput = new SvelteOutput() var1 = oOutput.addVar([1,2,'x']) var2 = oOutput.addVar({a:12, b:'xyz'}) oOutput.putLine "<p bgColor={#{var1}} height={#{var2}}>" tester.equal 519, oOutput, """ <p bgColor={#{var1}} height={#{var2}}> <script> #{var1} = [1,2,"x"] #{var2} = {"a":12,"b":"xyz"} </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)", "handler") tester.equal 535, oOutput, """ <script> handler = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("() -> console.log(hItems)") tester.equal 549, oOutput, """ <script> __anonVar0 = () -> console.log(hItems) </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b", "calc") tester.equal 563, oOutput, """ <script> calc = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addFunction with parameters without name (()-> oOutput = new SvelteOutput() oOutput.addFunction("(a, b) -> a + b") tester.equal 577, oOutput, """ <script> __anonVar0 = (a, b) -> a + b </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """, 'lItems') tester.equal 595, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' lItems = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test addTAML without name (()-> oOutput = new SvelteOutput() oOutput.addTAML(""" --- - a - b """) tester.equal 618, oOutput, """ <script> import {taml} from '@jdeighan/string-input/taml' __anonVar0 = taml(\"\"\" --- - a - b \"\"\") </script> """ )() # --------------------------------------------------------------------------- # --- Test auto-import (()-> oOutput = new SvelteOutput oOutput.putLine "<p>" oOutput.putLine "this is text", 1 oOutput.putLine "</p>" oOutput.declareJSVar 'name' oOutput.putScript "say 'Hi, there'", 1 simple.truthy 641, oOutput.hasSection('html') simple.truthy 642, oOutput.hasSection('script') simple.falsy 643, oOutput.hasSection('style') tester.equal 645, oOutput, """ <p> this is text </p> <script> import {undef,say} from '@jdeighan/coffee-utils' name = undef say 'Hi, there' </script> """ )() # --------------------------------------------------------------------------- # --- Test preprocessing (()-> oOutput = new SvelteOutput oOutput.putScript """ count = 0 doubled <== 2 * count """, 1 simple.falsy 668, oOutput.hasSection('html') simple.truthy 669, oOutput.hasSection('script') simple.falsy 670, oOutput.hasSection('style') tester.equal 672, oOutput, """ <script> count = 0 `$:` doubled = 2 * count </script> """ )()
[ { "context": "#################\n# Copyright (C) 2014-2015 by Vaughn Iverson\n# ddp-login is free software released under t", "end": 124, "score": 0.9997830390930176, "start": 110, "tag": "NAME", "value": "Vaughn Iverson" }, { "context": " email\n when \"Username...
test/index.coffee
vsivsi/ddp-login
51
############################################################################ # Copyright (C) 2014-2015 by Vaughn Iverson # ddp-login is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ # Unit tests assert = require('chai').assert rewire = require 'rewire' sinon = require 'sinon' login = null login = rewire '../src/index.coffee' read = (obj, cb) -> process.nextTick () -> val = switch obj.prompt when "Email: " email when "Username: " user when "Account: " account when "Password: " pass else throw new Error 'Bad prompt in read mock' cb null, val, false class DDP connect: (cb) -> # console.log "DDP Connecting..." process.nextTick cb close: (cb) -> # console.log "DDP Closing..." call: (method, params, cb) -> process.nextTick () -> unless method is 'login' return cb methodNotFoundError obj = params[0] if obj.resume? # Token based auth if obj.resume is goodToken return cb null, { token: goodToken } else return cb loggedOutError else if obj.user? and obj.password? # password if obj.password.digest? unless obj.password.algorithm is 'sha-256' return cb unrecognizedOptionsError else unless typeof obj.password is 'string' return cb unrecognizedOptionsError if obj.user.username? # username based if obj.user.username is user and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else if obj.user.username is srpUser if obj.srp? and obj.password.digest is goodDigest if obj.srp is 'c398c8dce734b1a6e7959bf90067985a1291e9f32a62edf15efb5adc760e40ce' return cb null, { token: migrationToken } else return cb matchFailedError else return cb oldPasswordFormatError else return cb matchFailedError else if obj.user.email # email based if obj.user.email is email and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else return cb matchFailedError else return cb unrecognizedOptionsError else return cb unrecognizedOptionsError login.__set__ 'read', read login.__set__ 'DDP', DDP goodToken = 'Ge1KTcEL8MbPc7hq_M5OkOwKHtNzbCdiDqaEoUNux22' migrationToken = 'Cn55fidCmxKykJsQd4VPUU0aHIOGom0HjdOELYkM8Vg' badToken = 'slkf90sfj3fls9j930fjfssjf9jf3fjs_fssh82344f' matchFailedError = "error":400 "reason":"Match failed" "message":"Match failed [400]" "errorType":"Meteor.Error" loggedOutError = "error":403 "reason":"You've been logged out by the server. Please log in again." "message":"You've been logged out by the server. Please log in again. [403]" "errorType":"Meteor.Error" methodNotFoundError = "error":404 "reason":"Method not found" "message":"Method not found [404]" "errorType":"Meteor.Error" unrecognizedOptionsError = "error":400 "reason":"Unrecognized options for login request" "message":"Unrecognized options for login request [400]" "errorType":"Meteor.Error" oldPasswordFormatError = "error":400 "reason":"old password format" "details":'{"format":"srp","identity":"h_UZJgkIqF-NYPR-NSJzHvZWH9MuHb689eLzy741nXq"}' "message":"old password format [400]" "errorType":"Meteor.Error" user = 'Bozo' email = 'bozo@clowns.com' account = null srpUser = 'Crusty' goodpass = 'secure' goodDigest = '6a934b45144e3758911efa29ed68fb2d420fa7bd568739cdcda9251fa9609b1e' okpass = 'justok' badpass = 'insecure' pass = null ddp = new DDP() describe 'ddp-login', () -> describe 'API', () -> before () -> login.__set__ console: error: (m) -> describe 'login with SRP account migration', () -> it 'should return a valid authToken when an account migration is successful', (done) -> pass = goodpass account = srpUser login ddp, { method: "account" }, (e, res) -> assert.ifError e assert.equal res.token, migrationToken, 'Wrong token returned' done() afterEach () -> pass = null it 'should throw when invoked without a valid callback', () -> assert.throws login, /Valid callback must be provided to ddp-login/ it 'should require a valid ddp parameter', () -> login null, (e) -> assert.throws (() -> throw e), /Invalid DDP parameter/ it 'should reject unsupported login methods', () -> login { call: (->), connect: (->), close: (->)}, { method: 'bogus' }, (e) -> assert.throws (() -> throw e), /Unsupported DDP login method/ it 'should recognize valid email addresses', () -> isEmail = login.__get__ 'isEmail' assert.isTrue isEmail(email), 'Valid email #1' assert.isTrue isEmail('CAPS.CAPS@DOMAIN.MUSEUM'), 'Valid email #2' assert.isFalse isEmail('not an email'), 'Invalid email #1' assert.isFalse isEmail('bozo@clown'), 'Invalid email #2' assert.isFalse isEmail('bozo@clown@clowns.com'), 'Invalid email #3' describe 'authToken handling', () -> it 'should return an existing valid authToken in the default environment variable', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.METEOR_TOKEN = undefined done() it 'should return an existing valid authToken in a specified environment variable', (done) -> process.env.TEST_TOKEN = goodToken login ddp, { env: 'TEST_TOKEN' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.TEST_TOKEN = undefined done() describe 'login with token only', () -> it 'should return a valid authToken when successful', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, { method: 'token' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token' }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token', retry: 3 }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> process.env.METEOR_TOKEN = undefined describe 'login with email', () -> it 'should return a valid authToken when successful', (done) -> pass = goodpass account = email login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to email', (done) -> pass = goodpass login ddp, { method: 'email' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: email, pass: goodpass }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = badpass account = email sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 11 ddp.call.restore() done() it 'should successfully authenticate with plaintext credentials', (done) -> pass = okpass account = email login ddp, { plaintext: true }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = badpass account = email sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 7 ddp.call.restore() done() afterEach () -> pass = null account = null describe 'login with username', () -> it 'should return a valid authToken when successful', (done) -> pass = goodpass account = user login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to username', (done) -> pass = goodpass login ddp, { method: 'username' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: user, pass: goodpass }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = badpass account = user sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = badpass account = user sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> pass = null account = null after () -> login.__set__ console: console describe 'Command line', () -> newLogin = () -> login = rewire '../src/index.coffee' login.__set__ 'read', read login.__set__ "DDP", DDP beforeEach () -> newLogin() it 'should support logging in with all default parameters with username', (done) -> pass = goodpass account = user token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should support logging in with all default parameters with email', (done) -> pass = goodpass account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad credentials', (done) -> pass = badpass account = email token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: [] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should support logging in with username', (done) -> pass = goodpass token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad username credentials', (done) -> pass = badpass token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should properly pass host and port to DDP', (done) -> pass = goodpass account = email token = null spyDDP = sinon.spy(DDP) login.__set__ "DDP", spyDDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--host', 'localhost', '--port', '3333'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken assert spyDDP.calledWithExactly host: 'localhost' port: 3333 use_ssl: false use_ejson: true done() login._command_line() it 'should succeed when a good token is in the default env var', (done) -> pass = badpass token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: [] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in the default env var and method is "token"', (done) -> pass = badpass token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var', (done) -> pass = badpass token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var and method is "token"', (done) -> pass = badpass token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a bad token is in a specified env var', (done) -> pass = goodpass account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should fail logging in with bad token when method is "token"', (done) -> pass = goodpass login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: METEOR_TOKEN: badToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should fail logging in with bad token in specified env var when method is "token"', (done) -> pass = goodpass login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should retry 5 times by default', (done) -> pass = badpass token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 6 DDP.prototype.call.restore() done() login._command_line() it 'should retry the specified number of times', (done) -> pass = badpass token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--retry', '3'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 4 DDP.prototype.call.restore() done() login._command_line() afterEach () -> pass = null account = null
20957
############################################################################ # Copyright (C) 2014-2015 by <NAME> # ddp-login is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ # Unit tests assert = require('chai').assert rewire = require 'rewire' sinon = require 'sinon' login = null login = rewire '../src/index.coffee' read = (obj, cb) -> process.nextTick () -> val = switch obj.prompt when "Email: " email when "Username: " user when "Account: " account when "Password: " pass else throw new Error 'Bad prompt in read mock' cb null, val, false class DDP connect: (cb) -> # console.log "DDP Connecting..." process.nextTick cb close: (cb) -> # console.log "DDP Closing..." call: (method, params, cb) -> process.nextTick () -> unless method is 'login' return cb methodNotFoundError obj = params[0] if obj.resume? # Token based auth if obj.resume is goodToken return cb null, { token: goodToken } else return cb loggedOutError else if obj.user? and obj.password? # password if obj.password.digest? unless obj.password.algorithm is 'sha-256' return cb unrecognizedOptionsError else unless typeof obj.password is 'string' return cb unrecognizedOptionsError if obj.user.username? # username based if obj.user.username is user and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else if obj.user.username is srpUser if obj.srp? and obj.password.digest is goodDigest if obj.srp is 'c398c8dce734b1a6e7959bf90067985a1291e9f32a62edf15efb5adc760e40ce' return cb null, { token: migrationToken } else return cb matchFailedError else return cb oldPasswordFormatError else return cb matchFailedError else if obj.user.email # email based if obj.user.email is email and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else return cb matchFailedError else return cb unrecognizedOptionsError else return cb unrecognizedOptionsError login.__set__ 'read', read login.__set__ 'DDP', DDP goodToken = '<KEY>' migrationToken = '<KEY>' badToken = '<KEY>' matchFailedError = "error":400 "reason":"Match failed" "message":"Match failed [400]" "errorType":"Meteor.Error" loggedOutError = "error":403 "reason":"You've been logged out by the server. Please log in again." "message":"You've been logged out by the server. Please log in again. [403]" "errorType":"Meteor.Error" methodNotFoundError = "error":404 "reason":"Method not found" "message":"Method not found [404]" "errorType":"Meteor.Error" unrecognizedOptionsError = "error":400 "reason":"Unrecognized options for login request" "message":"Unrecognized options for login request [400]" "errorType":"Meteor.Error" oldPasswordFormatError = "error":400 "reason":"old password format" "details":'{"format":"srp","identity":"<KEY>"}' "message":"old password format [400]" "errorType":"Meteor.Error" user = 'Bozo' email = '<EMAIL>' account = null srpUser = 'Crusty' goodpass = '<PASSWORD>' goodDigest = '6a934b45144e3758911efa29ed68fb2d420fa7bd568739cdcda92<PASSWORD>1<PASSWORD>9<PASSWORD>' okpass = '<PASSWORD>' badpass = '<PASSWORD>' pass = null ddp = new DDP() describe 'ddp-login', () -> describe 'API', () -> before () -> login.__set__ console: error: (m) -> describe 'login with SRP account migration', () -> it 'should return a valid authToken when an account migration is successful', (done) -> pass = <PASSWORD> account = srpUser login ddp, { method: "account" }, (e, res) -> assert.ifError e assert.equal res.token, migrationToken, 'Wrong token returned' done() afterEach () -> pass = null it 'should throw when invoked without a valid callback', () -> assert.throws login, /Valid callback must be provided to ddp-login/ it 'should require a valid ddp parameter', () -> login null, (e) -> assert.throws (() -> throw e), /Invalid DDP parameter/ it 'should reject unsupported login methods', () -> login { call: (->), connect: (->), close: (->)}, { method: 'bogus' }, (e) -> assert.throws (() -> throw e), /Unsupported DDP login method/ it 'should recognize valid email addresses', () -> isEmail = login.__get__ 'isEmail' assert.isTrue isEmail(email), 'Valid email #1' assert.isTrue isEmail('CAPS.CAPS@DOMAIN.MUSEUM'), 'Valid email #2' assert.isFalse isEmail('not an email'), 'Invalid email #1' assert.isFalse isEmail('bo<EMAIL>'), 'Invalid email #2' assert.isFalse isEmail('<EMAIL>'), 'Invalid email #3' describe 'authToken handling', () -> it 'should return an existing valid authToken in the default environment variable', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.METEOR_TOKEN = undefined done() it 'should return an existing valid authToken in a specified environment variable', (done) -> process.env.TEST_TOKEN = goodToken login ddp, { env: 'TEST_TOKEN' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.TEST_TOKEN = undefined done() describe 'login with token only', () -> it 'should return a valid authToken when successful', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, { method: 'token' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token' }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token', retry: 3 }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> process.env.METEOR_TOKEN = undefined describe 'login with email', () -> it 'should return a valid authToken when successful', (done) -> pass = <PASSWORD> account = email login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to email', (done) -> pass = <PASSWORD> login ddp, { method: 'email' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: email, pass: <PASSWORD> }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = <PASSWORD> account = email sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 11 ddp.call.restore() done() it 'should successfully authenticate with plaintext credentials', (done) -> pass = <PASSWORD> account = email login ddp, { plaintext: true }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = <PASSWORD> account = email sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 7 ddp.call.restore() done() afterEach () -> pass = null account = null describe 'login with username', () -> it 'should return a valid authToken when successful', (done) -> pass = <PASSWORD> account = user login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to username', (done) -> pass = <PASSWORD> login ddp, { method: 'username' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: user, pass: <PASSWORD> }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = <PASSWORD> account = user sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = <PASSWORD> account = user sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> pass = null account = null after () -> login.__set__ console: console describe 'Command line', () -> newLogin = () -> login = rewire '../src/index.coffee' login.__set__ 'read', read login.__set__ "DDP", DDP beforeEach () -> newLogin() it 'should support logging in with all default parameters with username', (done) -> pass = <PASSWORD> account = user token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should support logging in with all default parameters with email', (done) -> pass = <PASSWORD> account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad credentials', (done) -> pass = <PASSWORD> account = email token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: [] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should support logging in with username', (done) -> pass = <PASSWORD> token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad username credentials', (done) -> pass = <PASSWORD> token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should properly pass host and port to DDP', (done) -> pass = <PASSWORD> account = email token = null spyDDP = sinon.spy(DDP) login.__set__ "DDP", spyDDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--host', 'localhost', '--port', '3333'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken assert spyDDP.calledWithExactly host: 'localhost' port: 3333 use_ssl: false use_ejson: true done() login._command_line() it 'should succeed when a good token is in the default env var', (done) -> pass = <PASSWORD> token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: [] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in the default env var and method is "token"', (done) -> pass = <PASSWORD> token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var', (done) -> pass = <PASSWORD> token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var and method is "token"', (done) -> pass = <PASSWORD> token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a bad token is in a specified env var', (done) -> pass = <PASSWORD> account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should fail logging in with bad token when method is "token"', (done) -> pass = <PASSWORD> login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: METEOR_TOKEN: badToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should fail logging in with bad token in specified env var when method is "token"', (done) -> pass = <PASSWORD> login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should retry 5 times by default', (done) -> pass = <PASSWORD> token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 6 DDP.prototype.call.restore() done() login._command_line() it 'should retry the specified number of times', (done) -> pass = <PASSWORD> token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--retry', '3'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 4 DDP.prototype.call.restore() done() login._command_line() afterEach () -> pass = null account = null
true
############################################################################ # Copyright (C) 2014-2015 by PI:NAME:<NAME>END_PI # ddp-login is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ # Unit tests assert = require('chai').assert rewire = require 'rewire' sinon = require 'sinon' login = null login = rewire '../src/index.coffee' read = (obj, cb) -> process.nextTick () -> val = switch obj.prompt when "Email: " email when "Username: " user when "Account: " account when "Password: " pass else throw new Error 'Bad prompt in read mock' cb null, val, false class DDP connect: (cb) -> # console.log "DDP Connecting..." process.nextTick cb close: (cb) -> # console.log "DDP Closing..." call: (method, params, cb) -> process.nextTick () -> unless method is 'login' return cb methodNotFoundError obj = params[0] if obj.resume? # Token based auth if obj.resume is goodToken return cb null, { token: goodToken } else return cb loggedOutError else if obj.user? and obj.password? # password if obj.password.digest? unless obj.password.algorithm is 'sha-256' return cb unrecognizedOptionsError else unless typeof obj.password is 'string' return cb unrecognizedOptionsError if obj.user.username? # username based if obj.user.username is user and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else if obj.user.username is srpUser if obj.srp? and obj.password.digest is goodDigest if obj.srp is 'c398c8dce734b1a6e7959bf90067985a1291e9f32a62edf15efb5adc760e40ce' return cb null, { token: migrationToken } else return cb matchFailedError else return cb oldPasswordFormatError else return cb matchFailedError else if obj.user.email # email based if obj.user.email is email and (obj.password is okpass or obj.password.digest is goodDigest) return cb null, { token: goodToken } else return cb matchFailedError else return cb unrecognizedOptionsError else return cb unrecognizedOptionsError login.__set__ 'read', read login.__set__ 'DDP', DDP goodToken = 'PI:KEY:<KEY>END_PI' migrationToken = 'PI:KEY:<KEY>END_PI' badToken = 'PI:KEY:<KEY>END_PI' matchFailedError = "error":400 "reason":"Match failed" "message":"Match failed [400]" "errorType":"Meteor.Error" loggedOutError = "error":403 "reason":"You've been logged out by the server. Please log in again." "message":"You've been logged out by the server. Please log in again. [403]" "errorType":"Meteor.Error" methodNotFoundError = "error":404 "reason":"Method not found" "message":"Method not found [404]" "errorType":"Meteor.Error" unrecognizedOptionsError = "error":400 "reason":"Unrecognized options for login request" "message":"Unrecognized options for login request [400]" "errorType":"Meteor.Error" oldPasswordFormatError = "error":400 "reason":"old password format" "details":'{"format":"srp","identity":"PI:KEY:<KEY>END_PI"}' "message":"old password format [400]" "errorType":"Meteor.Error" user = 'Bozo' email = 'PI:EMAIL:<EMAIL>END_PI' account = null srpUser = 'Crusty' goodpass = 'PI:PASSWORD:<PASSWORD>END_PI' goodDigest = '6a934b45144e3758911efa29ed68fb2d420fa7bd568739cdcda92PI:PASSWORD:<PASSWORD>END_PI1PI:PASSWORD:<PASSWORD>END_PI9PI:PASSWORD:<PASSWORD>END_PI' okpass = 'PI:PASSWORD:<PASSWORD>END_PI' badpass = 'PI:PASSWORD:<PASSWORD>END_PI' pass = null ddp = new DDP() describe 'ddp-login', () -> describe 'API', () -> before () -> login.__set__ console: error: (m) -> describe 'login with SRP account migration', () -> it 'should return a valid authToken when an account migration is successful', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = srpUser login ddp, { method: "account" }, (e, res) -> assert.ifError e assert.equal res.token, migrationToken, 'Wrong token returned' done() afterEach () -> pass = null it 'should throw when invoked without a valid callback', () -> assert.throws login, /Valid callback must be provided to ddp-login/ it 'should require a valid ddp parameter', () -> login null, (e) -> assert.throws (() -> throw e), /Invalid DDP parameter/ it 'should reject unsupported login methods', () -> login { call: (->), connect: (->), close: (->)}, { method: 'bogus' }, (e) -> assert.throws (() -> throw e), /Unsupported DDP login method/ it 'should recognize valid email addresses', () -> isEmail = login.__get__ 'isEmail' assert.isTrue isEmail(email), 'Valid email #1' assert.isTrue isEmail('CAPS.CAPS@DOMAIN.MUSEUM'), 'Valid email #2' assert.isFalse isEmail('not an email'), 'Invalid email #1' assert.isFalse isEmail('boPI:EMAIL:<EMAIL>END_PI'), 'Invalid email #2' assert.isFalse isEmail('PI:EMAIL:<EMAIL>END_PI'), 'Invalid email #3' describe 'authToken handling', () -> it 'should return an existing valid authToken in the default environment variable', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.METEOR_TOKEN = undefined done() it 'should return an existing valid authToken in a specified environment variable', (done) -> process.env.TEST_TOKEN = goodToken login ddp, { env: 'TEST_TOKEN' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' process.env.TEST_TOKEN = undefined done() describe 'login with token only', () -> it 'should return a valid authToken when successful', (done) -> process.env.METEOR_TOKEN = goodToken login ddp, { method: 'token' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token' }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> process.env.METEOR_TOKEN = badToken sinon.spy ddp, 'call' login ddp, { method: 'token', retry: 3 }, (e, res) -> assert.equal e, loggedOutError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> process.env.METEOR_TOKEN = undefined describe 'login with email', () -> it 'should return a valid authToken when successful', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to email', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI login ddp, { method: 'email' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: email, pass: PI:PASSWORD:<PASSWORD>END_PI }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 11 ddp.call.restore() done() it 'should successfully authenticate with plaintext credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email login ddp, { plaintext: true }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 7 ddp.call.restore() done() afterEach () -> pass = null account = null describe 'login with username', () -> it 'should return a valid authToken when successful', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = user login ddp, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should also work when method is set to username', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI login ddp, { method: 'username' }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should work when account and pass are provided as options', (done) -> login ddp, { account: user, pass: PI:PASSWORD:<PASSWORD>END_PI }, (e, res) -> assert.ifError e assert.equal res.token, goodToken, 'Wrong token returned' done() it 'should retry 5 times by default and then fail with bad credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = user sinon.spy ddp, 'call' login ddp, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 6 ddp.call.restore() done() it 'should retry the specified number of times and then fail with bad credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = user sinon.spy ddp, 'call' login ddp, { retry: 3 }, (e, res) -> assert.equal e, matchFailedError assert.equal ddp.call.callCount, 4 ddp.call.restore() done() afterEach () -> pass = null account = null after () -> login.__set__ console: console describe 'Command line', () -> newLogin = () -> login = rewire '../src/index.coffee' login.__set__ 'read', read login.__set__ "DDP", DDP beforeEach () -> newLogin() it 'should support logging in with all default parameters with username', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = user token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should support logging in with all default parameters with email', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: [] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: [] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should support logging in with username', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken done() login._command_line() it 'should fail logging in with bad username credentials', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: {} argv: ['node', 'ddp-login', '--method', 'username'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should properly pass host and port to DDP', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email token = null spyDDP = sinon.spy(DDP) login.__set__ "DDP", spyDDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: {} argv: ['node', 'ddp-login', '--host', 'localhost', '--port', '3333'] exit: (n) -> assert.equal n, 0 assert.equal token, goodToken assert spyDDP.calledWithExactly host: 'localhost' port: 3333 use_ssl: false use_ejson: true done() login._command_line() it 'should succeed when a good token is in the default env var', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: [] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in the default env var and method is "token"', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: METEOR_TOKEN: goodToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a good token is in a specified env var and method is "token"', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null login.__set__ "DDP", DDP login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: goodToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should succeed when a bad token is in a specified env var', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI account = email token = null login.__set__ console: log: (m) -> token = m warn: console.warn process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 0, 'wrong return code' assert.equal token, goodToken, 'Bad token' done() login._command_line() it 'should fail logging in with bad token when method is "token"', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: METEOR_TOKEN: badToken argv: ['node', 'ddp-login', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should fail logging in with bad token in specified env var when method is "token"', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--method', 'token'] exit: (n) -> assert.equal n, 1 done() login._command_line() it 'should retry 5 times by default', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 6 DDP.prototype.call.restore() done() login._command_line() it 'should retry the specified number of times', (done) -> pass = PI:PASSWORD:<PASSWORD>END_PI token = null sinon.spy DDP.prototype, 'call' login.__set__ console: log: (m) -> token = m error: (m) -> warn: console.warn dir: (o) -> process: env: TEST_TOKEN: badToken argv: ['node', 'ddp-login', '--env', 'TEST_TOKEN', '--retry', '3'] exit: (n) -> assert.equal n, 1 assert.equal DDP.prototype.call.callCount, 4 DDP.prototype.call.restore() done() login._command_line() afterEach () -> pass = null account = null
[ { "context": "ime Completions converted from https://github.com/Southclaw/pawn-sublime-language\n# Converter created by Rena", "end": 111, "score": 0.8921931385993958, "start": 102, "tag": "USERNAME", "value": "Southclaw" }, { "context": "hclaw/pawn-sublime-language\n# Converter crea...
snippets/SIF.GEID.pwn.cson
Wuzi/language-pawn
4
# SIF.GEID.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by Renato "Hii" Garcia # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'mkgeid': 'prefix': 'mkgeid' 'body': 'mkgeid(${1:id}, ${2:result[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'b64_encode': 'prefix': 'b64_encode' 'body': 'b64_encode(${1:data[]}, ${2:data_len}, ${3:result[]}, ${4:result_len})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
188683
# SIF.GEID.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by <NAME> "<NAME> # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'mkgeid': 'prefix': 'mkgeid' 'body': 'mkgeid(${1:id}, ${2:result[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'b64_encode': 'prefix': 'b64_encode' 'body': 'b64_encode(${1:data[]}, ${2:data_len}, ${3:result[]}, ${4:result_len})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
true
# SIF.GEID.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'mkgeid': 'prefix': 'mkgeid' 'body': 'mkgeid(${1:id}, ${2:result[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'b64_encode': 'prefix': 'b64_encode' 'body': 'b64_encode(${1:data[]}, ${2:data_len}, ${3:result[]}, ${4:result_len})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
[ { "context": " a given user or the owner of the token. \r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass UserRolesRoute ", "end": 605, "score": 0.9998613595962524, "start": 593, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/router/routes/rpc/auth/UserRolesRoute.coffee
qrefdev/qref
0
RpcRoute = require('../../../RpcRoute') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') QRefDatabase = require('../../../../db/QRefDatabase') async = require('async') ### Service route that retrieves role membership. @example Service Methods (see {UserRolesRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/auth/userRoles @BODY - (Required) UserRolesRpcRequest Retrieves the roles assigned to a given user or the owner of the token. @author Nathan Klick @copyright QRef 2012 ### class UserRolesRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/userRoles' }, { method: 'GET', path: '/userRoles' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.body.token UserAuth.userFromToken(token, (err, user) => if err? or not user? resp = new RpcResponse(null) resp.failure('Forbidden', 403) res.json(resp, 200) return userId = null if req.body?.user? userId = req.body.user else userId = user._id @.getUserRoles(userId, (err, roles) -> if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(roles) res.json(resp, 200) return ) ) getUserRoles: (userId, callback) => db = QRefDatabase.instance() db.User.findById(userId, (err, user) -> if err? callback(err, []) return if not user? callback(new Error("User was not found."), []) return roleNames = [] async.forEach(user.roles, (item, cb) -> db.Role.findById(item, (err, role) -> if err? cb(err) return if not role? cb(null) return roleNames.push(role.roleName) cb(null) ) , (err) -> if err? callback(err, []) return callback(null, roleNames) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UserRolesRoute()
224983
RpcRoute = require('../../../RpcRoute') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') QRefDatabase = require('../../../../db/QRefDatabase') async = require('async') ### Service route that retrieves role membership. @example Service Methods (see {UserRolesRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/auth/userRoles @BODY - (Required) UserRolesRpcRequest Retrieves the roles assigned to a given user or the owner of the token. @author <NAME> @copyright QRef 2012 ### class UserRolesRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/userRoles' }, { method: 'GET', path: '/userRoles' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.body.token UserAuth.userFromToken(token, (err, user) => if err? or not user? resp = new RpcResponse(null) resp.failure('Forbidden', 403) res.json(resp, 200) return userId = null if req.body?.user? userId = req.body.user else userId = user._id @.getUserRoles(userId, (err, roles) -> if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(roles) res.json(resp, 200) return ) ) getUserRoles: (userId, callback) => db = QRefDatabase.instance() db.User.findById(userId, (err, user) -> if err? callback(err, []) return if not user? callback(new Error("User was not found."), []) return roleNames = [] async.forEach(user.roles, (item, cb) -> db.Role.findById(item, (err, role) -> if err? cb(err) return if not role? cb(null) return roleNames.push(role.roleName) cb(null) ) , (err) -> if err? callback(err, []) return callback(null, roleNames) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UserRolesRoute()
true
RpcRoute = require('../../../RpcRoute') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') QRefDatabase = require('../../../../db/QRefDatabase') async = require('async') ### Service route that retrieves role membership. @example Service Methods (see {UserRolesRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/auth/userRoles @BODY - (Required) UserRolesRpcRequest Retrieves the roles assigned to a given user or the owner of the token. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class UserRolesRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/userRoles' }, { method: 'GET', path: '/userRoles' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.body.token UserAuth.userFromToken(token, (err, user) => if err? or not user? resp = new RpcResponse(null) resp.failure('Forbidden', 403) res.json(resp, 200) return userId = null if req.body?.user? userId = req.body.user else userId = user._id @.getUserRoles(userId, (err, roles) -> if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(roles) res.json(resp, 200) return ) ) getUserRoles: (userId, callback) => db = QRefDatabase.instance() db.User.findById(userId, (err, user) -> if err? callback(err, []) return if not user? callback(new Error("User was not found."), []) return roleNames = [] async.forEach(user.roles, (item, cb) -> db.Role.findById(item, (err, role) -> if err? cb(err) return if not role? cb(null) return roleNames.push(role.roleName) cb(null) ) , (err) -> if err? callback(err, []) return callback(null, roleNames) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UserRolesRoute()
[ { "context": "da database for genomic variation frequencies.\n#\n# Martijn Vermaat <m.vermaat.hg@lumc.nl>\n#\n# Licensed under the MIT", "end": 103, "score": 0.9998811483383179, "start": 88, "tag": "NAME", "value": "Martijn Vermaat" }, { "context": "nomic variation frequencies.\n#\n#...
scripts/api.coffee
varda/aule-test
1
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # Martijn Vermaat <m.vermaat.hg@lumc.nl> # # Licensed under the MIT license, see the LICENSE file. # Todo: Cache resources. $ = require 'jquery' URI = require 'urijs' config = require 'config' # Accepted server API versions. ACCEPT_VERSION = '>=3.0.0,<4.0.0' # Create HTTP Basic Authentication header value. makeBasicAuth = (login, password) -> 'Basic ' + window.btoa (login + ':' + password) # Add HTTP Basic Authentication header to request. addAuth = (r, login, password) -> r.setRequestHeader 'Authorization', makeBasicAuth login, password if login # Add Accept-Version header to request. addVersion = (r) -> r.setRequestHeader 'Accept-Version', ACCEPT_VERSION # Add Range header to request for collection resources. addRangeForPage = (page, page_size=config.PAGE_SIZE) -> start = page * page_size end = start + page_size - 1 (r) -> r.setRequestHeader 'Range', "items=#{ start }-#{ end }" # Normalize ajax error handling. ajaxError = (handler) -> (xhr) -> try error = ($.parseJSON xhr.responseText).error catch e if not xhr.status error = code: 'connection_error', message: 'Unable to connect to server' else if xhr.status == 503 error = code: 'maintenance', message: 'The server is currently undergoing maintenance' else error = code: 'response_error', message: "Unable to parse server response (status: #{xhr.status} #{xhr.statusText})" console.log 'Unable to parse server response' console.log xhr.responseText handler? error.code, error.message class Api constructor: (@root) -> init: ({success, error}) => @request @root, error: error success: (r) => if r.root.status != 'ok' error? 'response_error', 'Unexpected response from server' return @uris = root: @root authentication: r.root.authentication.uri genome: r.root.genome.uri annotations: r.root.annotation_collection.uri coverages: r.root.coverage_collection.uri data_sources: r.root.data_source_collection.uri groups: r.root.group_collection.uri samples: r.root.sample_collection.uri tokens: r.root.token_collection.uri users: r.root.user_collection.uri variants: r.root.variant_collection.uri variations: r.root.variation_collection.uri success?() annotation: (uri, options={}) => # Todo: Proper URI construction. uri += '?embed=original_data_source,annotated_data_source' success = options.success options.success = (data) -> success? data.annotation @request uri, options annotations: (options={}) => uri = @uris.annotations + '?embed=original_data_source,annotated_data_source' if options.filter == 'own' uri += "&annotated_data_source.user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'annotation', options create_annotation: (options={}) => options.data = name: options.name data_source: options.data_source queries: [name: 'QUERY', expression: options.query] success = options.success options.success = (data) -> success? data.annotation options.method = 'POST' @request @uris.annotations, options authenticate: (@login, @password, {success, error}) => @current_user = null @request @uris.authentication, success: (r) => if r.authentication.authenticated @current_user = r.authentication.user success?() else error? 'authentication_error', "Unable to authenticate with login '#{@login}' and password '***'" error: error coverages: (options={}) => uri = @uris.coverages + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'coverage', options data_source: (uri, options={}) => uri += '?embed=user' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.data_source @request uri, options data_sources: (options={}) => uri = @uris.data_sources if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'data_source', options create_data_source: (options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'POST' @request @uris.data_sources, options edit_data_source: (uri, options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'PATCH' @request uri, options delete_data_source: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options genome: (options={}) => success = options.success options.success = (data) -> success? data.genome @request @uris.genome, options group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group @request uri, options groups: (options={}) => @collection @uris.groups, 'group', options create_group: (options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'POST' @request @uris.groups, options edit_group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'PATCH' @request uri, options delete_group: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options sample: (uri, options={}) => uri += '?embed=user,groups' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.sample @request uri, options samples: (options={}) => uri = @uris.samples if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" if options.filter == 'public' uri += '?public=true' if options.group? uri += "?groups=#{ encodeURIComponent options.group }" @collection uri, 'sample', options create_sample: (options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'POST' @request @uris.samples, options edit_sample: (uri, options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'PATCH' @request uri, options delete_sample: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token @request uri, options tokens: (options={}) => uri = @uris.tokens if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'token', options create_token: (options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'POST' @request @uris.tokens, options edit_token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'PATCH' @request uri, options delete_token: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user @request uri, options users: (options={}) => @collection @uris.users, 'user', options create_user: (options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'POST' @request @uris.users, options edit_user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'PATCH' @request uri, options delete_user: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options variations: (options={}) => uri = @uris.variations + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'variation', options variant: (uri, options={}) => # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" success = options.success # We only support one query, so we flatten the query results. success = options.success options.success = (data) -> variant = data.variant variant.coverage = variant.annotations.QUERY.coverage variant.frequency = variant.annotations.QUERY.frequency variant.frequency_het = variant.annotations.QUERY.frequency_het variant.frequency_hom = variant.annotations.QUERY.frequency_hom success? variant @request uri, options variants: (options={}) => uri = @uris.variants # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" # We only support one query, so we flatten the query results. success = options.success options.success = (items, pagination) -> for item in items item.coverage = item.annotations.QUERY.coverage item.frequency = item.annotations.QUERY.frequency item.frequency_het = item.annotations.QUERY.frequency_het item.frequency_hom = item.annotations.QUERY.frequency_hom success items, pagination @collection uri, 'variant', options create_variant: (options={}) => success = options.success options.success = (data) -> success? data.variant options.method = 'POST' @request @uris.variants, options collection: (uri, type, options={}) => options.page_number ?= 0 options.page_size ?= config.PAGE_SIZE @request uri, beforeSend: addRangeForPage options.page_number, config.PAGE_SIZE success: (data, status, xhr) -> range = xhr.getResponseHeader 'Content-Range' total = parseInt (range.split '/')[1] pagination = total: Math.ceil total / options.page_size current: options.page_number options.success? data["#{ type }_collection"].items, pagination error: (code, message) -> if code == 'unsatisfiable_range' options.success? [], total: 0, current: 0 else options.error? code, message data: options.data request: (uri, options={}) => uri = URI(uri).absoluteTo(@root).toString() $.ajax uri, beforeSend: (r) => addAuth r, @login, @password addVersion r options.beforeSend? r data: JSON.stringify options.data success: options.success error: ajaxError options.error dataType: 'json' type: options.method ? 'GET' contentType: 'application/json; charset=utf-8' if options.data? return module.exports = Api
24187
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # <NAME> <<EMAIL>> # # Licensed under the MIT license, see the LICENSE file. # Todo: Cache resources. $ = require 'jquery' URI = require 'urijs' config = require 'config' # Accepted server API versions. ACCEPT_VERSION = '>=3.0.0,<4.0.0' # Create HTTP Basic Authentication header value. makeBasicAuth = (login, password) -> 'Basic ' + window.btoa (login + ':' + password) # Add HTTP Basic Authentication header to request. addAuth = (r, login, password) -> r.setRequestHeader 'Authorization', makeBasicAuth login, password if login # Add Accept-Version header to request. addVersion = (r) -> r.setRequestHeader 'Accept-Version', ACCEPT_VERSION # Add Range header to request for collection resources. addRangeForPage = (page, page_size=config.PAGE_SIZE) -> start = page * page_size end = start + page_size - 1 (r) -> r.setRequestHeader 'Range', "items=#{ start }-#{ end }" # Normalize ajax error handling. ajaxError = (handler) -> (xhr) -> try error = ($.parseJSON xhr.responseText).error catch e if not xhr.status error = code: 'connection_error', message: 'Unable to connect to server' else if xhr.status == 503 error = code: 'maintenance', message: 'The server is currently undergoing maintenance' else error = code: 'response_error', message: "Unable to parse server response (status: #{xhr.status} #{xhr.statusText})" console.log 'Unable to parse server response' console.log xhr.responseText handler? error.code, error.message class Api constructor: (@root) -> init: ({success, error}) => @request @root, error: error success: (r) => if r.root.status != 'ok' error? 'response_error', 'Unexpected response from server' return @uris = root: @root authentication: r.root.authentication.uri genome: r.root.genome.uri annotations: r.root.annotation_collection.uri coverages: r.root.coverage_collection.uri data_sources: r.root.data_source_collection.uri groups: r.root.group_collection.uri samples: r.root.sample_collection.uri tokens: r.root.token_collection.uri users: r.root.user_collection.uri variants: r.root.variant_collection.uri variations: r.root.variation_collection.uri success?() annotation: (uri, options={}) => # Todo: Proper URI construction. uri += '?embed=original_data_source,annotated_data_source' success = options.success options.success = (data) -> success? data.annotation @request uri, options annotations: (options={}) => uri = @uris.annotations + '?embed=original_data_source,annotated_data_source' if options.filter == 'own' uri += "&annotated_data_source.user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'annotation', options create_annotation: (options={}) => options.data = name: options.name data_source: options.data_source queries: [name: 'QUERY', expression: options.query] success = options.success options.success = (data) -> success? data.annotation options.method = 'POST' @request @uris.annotations, options authenticate: (@login, @password, {success, error}) => @current_user = null @request @uris.authentication, success: (r) => if r.authentication.authenticated @current_user = r.authentication.user success?() else error? 'authentication_error', "Unable to authenticate with login '#{@login}' and password '<PASSWORD>***'" error: error coverages: (options={}) => uri = @uris.coverages + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'coverage', options data_source: (uri, options={}) => uri += '?embed=user' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.data_source @request uri, options data_sources: (options={}) => uri = @uris.data_sources if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'data_source', options create_data_source: (options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'POST' @request @uris.data_sources, options edit_data_source: (uri, options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'PATCH' @request uri, options delete_data_source: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options genome: (options={}) => success = options.success options.success = (data) -> success? data.genome @request @uris.genome, options group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group @request uri, options groups: (options={}) => @collection @uris.groups, 'group', options create_group: (options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'POST' @request @uris.groups, options edit_group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'PATCH' @request uri, options delete_group: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options sample: (uri, options={}) => uri += '?embed=user,groups' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.sample @request uri, options samples: (options={}) => uri = @uris.samples if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" if options.filter == 'public' uri += '?public=true' if options.group? uri += "?groups=#{ encodeURIComponent options.group }" @collection uri, 'sample', options create_sample: (options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'POST' @request @uris.samples, options edit_sample: (uri, options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'PATCH' @request uri, options delete_sample: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token @request uri, options tokens: (options={}) => uri = @uris.tokens if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'token', options create_token: (options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'POST' @request @uris.tokens, options edit_token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'PATCH' @request uri, options delete_token: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user @request uri, options users: (options={}) => @collection @uris.users, 'user', options create_user: (options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'POST' @request @uris.users, options edit_user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'PATCH' @request uri, options delete_user: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options variations: (options={}) => uri = @uris.variations + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'variation', options variant: (uri, options={}) => # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" success = options.success # We only support one query, so we flatten the query results. success = options.success options.success = (data) -> variant = data.variant variant.coverage = variant.annotations.QUERY.coverage variant.frequency = variant.annotations.QUERY.frequency variant.frequency_het = variant.annotations.QUERY.frequency_het variant.frequency_hom = variant.annotations.QUERY.frequency_hom success? variant @request uri, options variants: (options={}) => uri = @uris.variants # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" # We only support one query, so we flatten the query results. success = options.success options.success = (items, pagination) -> for item in items item.coverage = item.annotations.QUERY.coverage item.frequency = item.annotations.QUERY.frequency item.frequency_het = item.annotations.QUERY.frequency_het item.frequency_hom = item.annotations.QUERY.frequency_hom success items, pagination @collection uri, 'variant', options create_variant: (options={}) => success = options.success options.success = (data) -> success? data.variant options.method = 'POST' @request @uris.variants, options collection: (uri, type, options={}) => options.page_number ?= 0 options.page_size ?= config.PAGE_SIZE @request uri, beforeSend: addRangeForPage options.page_number, config.PAGE_SIZE success: (data, status, xhr) -> range = xhr.getResponseHeader 'Content-Range' total = parseInt (range.split '/')[1] pagination = total: Math.ceil total / options.page_size current: options.page_number options.success? data["#{ type }_collection"].items, pagination error: (code, message) -> if code == 'unsatisfiable_range' options.success? [], total: 0, current: 0 else options.error? code, message data: options.data request: (uri, options={}) => uri = URI(uri).absoluteTo(@root).toString() $.ajax uri, beforeSend: (r) => addAuth r, @login, @password addVersion r options.beforeSend? r data: JSON.stringify options.data success: options.success error: ajaxError options.error dataType: 'json' type: options.method ? 'GET' contentType: 'application/json; charset=utf-8' if options.data? return module.exports = Api
true
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Licensed under the MIT license, see the LICENSE file. # Todo: Cache resources. $ = require 'jquery' URI = require 'urijs' config = require 'config' # Accepted server API versions. ACCEPT_VERSION = '>=3.0.0,<4.0.0' # Create HTTP Basic Authentication header value. makeBasicAuth = (login, password) -> 'Basic ' + window.btoa (login + ':' + password) # Add HTTP Basic Authentication header to request. addAuth = (r, login, password) -> r.setRequestHeader 'Authorization', makeBasicAuth login, password if login # Add Accept-Version header to request. addVersion = (r) -> r.setRequestHeader 'Accept-Version', ACCEPT_VERSION # Add Range header to request for collection resources. addRangeForPage = (page, page_size=config.PAGE_SIZE) -> start = page * page_size end = start + page_size - 1 (r) -> r.setRequestHeader 'Range', "items=#{ start }-#{ end }" # Normalize ajax error handling. ajaxError = (handler) -> (xhr) -> try error = ($.parseJSON xhr.responseText).error catch e if not xhr.status error = code: 'connection_error', message: 'Unable to connect to server' else if xhr.status == 503 error = code: 'maintenance', message: 'The server is currently undergoing maintenance' else error = code: 'response_error', message: "Unable to parse server response (status: #{xhr.status} #{xhr.statusText})" console.log 'Unable to parse server response' console.log xhr.responseText handler? error.code, error.message class Api constructor: (@root) -> init: ({success, error}) => @request @root, error: error success: (r) => if r.root.status != 'ok' error? 'response_error', 'Unexpected response from server' return @uris = root: @root authentication: r.root.authentication.uri genome: r.root.genome.uri annotations: r.root.annotation_collection.uri coverages: r.root.coverage_collection.uri data_sources: r.root.data_source_collection.uri groups: r.root.group_collection.uri samples: r.root.sample_collection.uri tokens: r.root.token_collection.uri users: r.root.user_collection.uri variants: r.root.variant_collection.uri variations: r.root.variation_collection.uri success?() annotation: (uri, options={}) => # Todo: Proper URI construction. uri += '?embed=original_data_source,annotated_data_source' success = options.success options.success = (data) -> success? data.annotation @request uri, options annotations: (options={}) => uri = @uris.annotations + '?embed=original_data_source,annotated_data_source' if options.filter == 'own' uri += "&annotated_data_source.user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'annotation', options create_annotation: (options={}) => options.data = name: options.name data_source: options.data_source queries: [name: 'QUERY', expression: options.query] success = options.success options.success = (data) -> success? data.annotation options.method = 'POST' @request @uris.annotations, options authenticate: (@login, @password, {success, error}) => @current_user = null @request @uris.authentication, success: (r) => if r.authentication.authenticated @current_user = r.authentication.user success?() else error? 'authentication_error', "Unable to authenticate with login '#{@login}' and password 'PI:PASSWORD:<PASSWORD>END_PI***'" error: error coverages: (options={}) => uri = @uris.coverages + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'coverage', options data_source: (uri, options={}) => uri += '?embed=user' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.data_source @request uri, options data_sources: (options={}) => uri = @uris.data_sources if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'data_source', options create_data_source: (options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'POST' @request @uris.data_sources, options edit_data_source: (uri, options={}) => success = options.success options.success = (data) -> success? data.data_source options.method = 'PATCH' @request uri, options delete_data_source: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options genome: (options={}) => success = options.success options.success = (data) -> success? data.genome @request @uris.genome, options group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group @request uri, options groups: (options={}) => @collection @uris.groups, 'group', options create_group: (options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'POST' @request @uris.groups, options edit_group: (uri, options={}) => success = options.success options.success = (data) -> success? data.group options.method = 'PATCH' @request uri, options delete_group: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options sample: (uri, options={}) => uri += '?embed=user,groups' # Todo: Proper URI construction. success = options.success options.success = (data) -> success? data.sample @request uri, options samples: (options={}) => uri = @uris.samples if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" if options.filter == 'public' uri += '?public=true' if options.group? uri += "?groups=#{ encodeURIComponent options.group }" @collection uri, 'sample', options create_sample: (options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'POST' @request @uris.samples, options edit_sample: (uri, options={}) => success = options.success options.success = (data) -> success? data.sample options.method = 'PATCH' @request uri, options delete_sample: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token @request uri, options tokens: (options={}) => uri = @uris.tokens if options.filter == 'own' uri += "?user=#{ encodeURIComponent @current_user?.uri }" @collection uri, 'token', options create_token: (options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'POST' @request @uris.tokens, options edit_token: (uri, options={}) => success = options.success options.success = (data) -> success? data.token options.method = 'PATCH' @request uri, options delete_token: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user @request uri, options users: (options={}) => @collection @uris.users, 'user', options create_user: (options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'POST' @request @uris.users, options edit_user: (uri, options={}) => success = options.success options.success = (data) -> success? data.user options.method = 'PATCH' @request uri, options delete_user: (uri, options={}) => success = options.success options.success = (data) -> success?() options.method = 'DELETE' @request uri, options variations: (options={}) => uri = @uris.variations + '?embed=data_source' if options.sample? uri += "&sample=#{ encodeURIComponent options.sample }" @collection uri, 'variation', options variant: (uri, options={}) => # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" success = options.success # We only support one query, so we flatten the query results. success = options.success options.success = (data) -> variant = data.variant variant.coverage = variant.annotations.QUERY.coverage variant.frequency = variant.annotations.QUERY.frequency variant.frequency_het = variant.annotations.QUERY.frequency_het variant.frequency_hom = variant.annotations.QUERY.frequency_hom success? variant @request uri, options variants: (options={}) => uri = @uris.variants # The queries structure is too complex to send as a regular query string # parameter and we cannot send a request body with GET, so we use the # __json__ query string parameter workaround. json = queries: [name: 'QUERY', expression: options.query] region: options.region uri += "?__json__=#{ encodeURIComponent (JSON.stringify json) }" # We only support one query, so we flatten the query results. success = options.success options.success = (items, pagination) -> for item in items item.coverage = item.annotations.QUERY.coverage item.frequency = item.annotations.QUERY.frequency item.frequency_het = item.annotations.QUERY.frequency_het item.frequency_hom = item.annotations.QUERY.frequency_hom success items, pagination @collection uri, 'variant', options create_variant: (options={}) => success = options.success options.success = (data) -> success? data.variant options.method = 'POST' @request @uris.variants, options collection: (uri, type, options={}) => options.page_number ?= 0 options.page_size ?= config.PAGE_SIZE @request uri, beforeSend: addRangeForPage options.page_number, config.PAGE_SIZE success: (data, status, xhr) -> range = xhr.getResponseHeader 'Content-Range' total = parseInt (range.split '/')[1] pagination = total: Math.ceil total / options.page_size current: options.page_number options.success? data["#{ type }_collection"].items, pagination error: (code, message) -> if code == 'unsatisfiable_range' options.success? [], total: 0, current: 0 else options.error? code, message data: options.data request: (uri, options={}) => uri = URI(uri).absoluteTo(@root).toString() $.ajax uri, beforeSend: (r) => addAuth r, @login, @password addVersion r options.beforeSend? r data: JSON.stringify options.data success: options.success error: ajaxError options.error dataType: 'json' type: options.method ? 'GET' contentType: 'application/json; charset=utf-8' if options.data? return module.exports = Api
[ { "context": "localhost'\nDEFAULT_PORT = 5001\nDEFAULT_ACCOUNT = 'admin'\nDEFAULT_PASSWD = 'password'\nDEFAULT_API_VERSION ", "end": 147, "score": 0.9895458817481995, "start": 142, "tag": "USERNAME", "value": "admin" }, { "context": " 5001\nDEFAULT_ACCOUNT = 'admin'\nDEFAULT_PASSWD =...
src/cli/syno.coffee
Havock94/syno
0
CONFIG_DIR = '.syno' CONFIG_FILE = 'config.yaml' DEFAULT_PROTOCOL = 'https' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 5001 DEFAULT_ACCOUNT = 'admin' DEFAULT_PASSWD = 'password' DEFAULT_API_VERSION = '6.0.2' program = require 'commander' fs = require 'fs' url = require 'url' nconf = require 'nconf' ospath = require 'ospath' yaml = require 'js-yaml' Syno = require '../dist/syno' os = require 'os' execute = (api, cmd, options)-> console.log '[DEBUG] : Method name configured : %s', cmd if program.debug console.log '[DEBUG] : JSON payload configured : %s', options.payload if options.payload and program.debug console.log '[DEBUG] : Prettify output detected' if options.pretty and program.debug try payload = JSON.parse(options.payload or '{}') catch exception console.log '[ERROR] : JSON Exception : %s', exception process.exit 1 syno[api][cmd] payload, (err, data) -> console.log '[ERROR] : %s', err if err if options.pretty data = JSON.stringify data, undefined, 2 else data = JSON.stringify data console.log data if data syno.auth.logout() process.exit 0 show_methods_available = (api)-> console.log ' Available methods:' console.log '' syno[api]['getMethods'] {}, (data) -> console.log " $ syno #{api} #{method}" for method in data console.log ' None' if data.length is 0 console.log '' main = program .version '2.1.0' .description 'Synology Rest API Command Line' .option '-c, --config <path>', "DSM Configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Commands:' console.log '' console.log ' diskstationmanager|dsm [options] <method> DSM API' console.log ' filestation|fs [options] <method> DSM File Station API' console.log ' downloadstation|dl [options] <method> DSM Download Station API' console.log ' audiostation|as [options] <method> DSM Audio Station API' console.log ' videostation|vs [options] <method> DSM Video Station API' console.log ' videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm getInfo' console.log ' $ syno filestation|fs getInfo' console.log ' $ syno downloadstation|dl getInfo' console.log ' $ syno audiostation|as getInfo' console.log ' $ syno videostation|vs getInfo' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":5}\' --pretty' console.log ' $ syno surveillancestation|ss getInfo' console.log '' program.parse process.argv if program.args.length is 0 program.help() else if (program.args.length > 0 and program.args[0] isnt 'diskstationmanager' and program.args[0] isnt 'filestation' and program.args[0] isnt 'downloadstation' and program.args[0] isnt 'audiostation' and program.args[0] isnt 'videostation' and program.args[0] isnt 'videostationdtv' and program.args[0] isnt 'surveillancestation' and program.args[0] isnt 'dsm' and program.args[0] isnt 'fs' and program.args[0] isnt 'dl' and program.args[0] isnt 'as' and program.args[0] isnt 'vs' and program.args[0] isnt 'dtv' and program.args[0] isnt 'ss') console.log '' console.log " [ERROR] : #{program.args[0]} is not a valid command !" console.log '' console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm [options] <method> DSM API' console.log ' $ syno filestation|fs [options] <method> DSM File Station API' console.log ' $ syno downloadstation|dl [options] <method> DSM Download Station API' console.log ' $ syno audiostation|as [options] <method> DSM Audio Station API' console.log ' $ syno videostation|vs [options] <method> DSM Video Station API' console.log ' $ syno videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' $ syno surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' process.exit 1 # Load cmd line args and environment vars nconf.argv().file file: ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options if program.url console.log '[DEBUG] : Params URL detected : %s.', program.url if program.debug url_resolved = url.parse program.url url_resolved = url.parse DEFAULT_PROTOCOL + '://' + program.url if not url_resolved.protocol url_resolved.protocol = url_resolved.protocol.slice(0, -1) if url_resolved.protocol isnt 'http' and url_resolved.protocol isnt 'https' console.log '[ERROR] : Invalid Protocol URL detected : %s.', url_resolved.protocol process.exit 1 nconf.set 'url:protocol', url_resolved.protocol nconf.set 'url:host', url_resolved.hostname or DEFAULT_HOST nconf.set 'url:port', url_resolved.port or DEFAULT_PORT nconf.set 'url:account', if url_resolved.auth then url_resolved.auth.split(':')[0] else DEFAULT_ACCOUNT nconf.set 'url:passwd', if url_resolved.auth then url_resolved.auth.split(':')[1] else DEFAULT_PASSWD nconf.set 'url:apiVersion', main.api or DEFAULT_API_VERSION else if program.config console.log '[DEBUG] : Load config file : %s', program.config if program.debug try fs.accessSync program.config catch console.log '[ERROR] : Config file : %s not found', program.config process.exit 1 nconf.file file: program.config format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options nconf.overrides url: apiVersion: main.api or DEFAULT_API_VERSION else # If no directory -> create directory and save the file try fs.accessSync ospath.home() + "/#{CONFIG_DIR}" catch console.log '[DEBUG] : Default configuration directory does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}" if program.debug fs.mkdirSync ospath.home() + "/#{CONFIG_DIR}" try fs.accessSync ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" catch console.log '[DEBUG] : Default configuration file does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" if program.debug nconf.set 'url:protocol', DEFAULT_PROTOCOL nconf.set 'url:host', DEFAULT_HOST nconf.set 'url:port', DEFAULT_PORT nconf.set 'url:account', DEFAULT_ACCOUNT nconf.set 'url:passwd', DEFAULT_PASSWD nconf.set 'url:apiVersion', DEFAULT_API_VERSION nconf.save() nconf.overrides url: apiVersion: (nconf.get 'url:apiVersion') or main.api or DEFAULT_API_VERSION nconf.defaults url: protocol: DEFAULT_PROTOCOL host: DEFAULT_HOST port: DEFAULT_PORT account: DEFAULT_ACCOUNT passwd: DEFAULT_PASSWD apiVersion: DEFAULT_API_VERSION if program.debug console.log '[DEBUG] : DSM Connection URL configured : %s://%s:%s@%s:%s', nconf.get('url:protocol'), nconf.get('url:account'), nconf.get('url:passwd'), nconf.get('url:host'), nconf.get('url:port') syno = new Syno protocol: process.env.SYNO_PROTOCOL or nconf.get 'url:protocol' host: process.env.SYNO_HOST or nconf.get 'url:host' port: process.env.SYNO_PORT or nconf.get 'url:port' account: process.env.SYNO_ACCOUNT or nconf.get 'url:account' passwd: process.env.SYNO_PASSWORD or nconf.get 'url:passwd' apiVersion: process.env.SYNO_API_VERSION or nconf.get 'url:apiVersion' debug: process.env.SYNO_DEBUG or main.debug ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or main.ignoreCertificateErrors program .command 'diskstationmanager <method>' .alias 'dsm' .description 'DSM API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm startFindme' console.log ' $ syno diskstationmanager|dsm getInfo --pretty\'' console.log ' $ syno diskstationmanagercore|dsm listUsers' console.log ' $ syno diskstationmanagercore|dsm listPackages' console.log '' show_methods_available 'dsm' .action (cmd, options) -> console.log '[DEBUG] : DSM API command selected' if program.debug execute 'dsm', cmd, options program .command 'filestation <method>' .alias 'fs' .description 'DSM File Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno filestation|fs listSharings' console.log ' $ syno filestation|fs list --pretty --payload \'{"folder_path":"/path/to/folder"}\'' console.log '' show_methods_available 'fs' .action (cmd, options) -> console.log '[DEBUG] : DSM File Station API command selected' if program.debug execute 'fs', cmd, options program .command 'downloadstation <method>' .alias 'dl' .description 'DSM Download Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno downloadstation|dl createTask --payload \'{"uri":"magnet|ed2k|ftp(s)|http(s)://link"}\'' console.log ' $ syno downloadstation|dl listTasks' console.log ' $ syno downloadstation|dl listTasks --payload \'{"limit":1}\'' console.log ' $ syno downloadstation|dl getInfoTask --pretty --payload \'{"id":"task_id"}\'' console.log '' show_methods_available 'dl' .action (cmd, options) -> console.log '[DEBUG] : DSM Download Station API command selected' if program.debug execute 'dl', cmd, options program .command('audiostation <method>') .alias('as') .description('DSM Audio Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno audiostation|as listSongs --payload \'{"limit":1}\'' console.log ' $ syno audiostation|as listAlbums' console.log ' $ syno audiostation|as searchSong --payload \'{"title":"victoria"}\'' console.log '' show_methods_available 'as' .action (cmd, options) -> console.log '[DEBUG] : DSM Audio Station API command selected' if program.debug execute 'as', cmd, options program .command('videostation <method>') .alias('vs') .description('DSM Video Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostation|vs listMovies --payload \'{"limit":1}\'' console.log ' $ syno videostation|vs getInfoTvShow --payload \'{"id":"episode_id"}\'' console.log '' show_methods_available 'vs' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station API command selected' if program.debug execute 'vs', cmd, options program .command('videostationdtv <method>') .alias('dtv') .description('DSM Video Station DTV API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":1}\'' console.log ' $ syno videostationdtv|dtv getInfoTuner --payload \'{"id":"tuner_id"}\'' console.log '' show_methods_available 'dtv' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station DTV API command selected' if program.debug execute 'dtv', cmd, options program .command('surveillancestation <method>') .alias('ss') .description('DSM Surveillance Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno surveillancestation|ss listCameras' console.log ' $ syno surveillancestation|ss getInfoCamera --payload \'{"cameraIds":4}\'' console.log ' $ syno surveillancestation|ss zoomPtz --payload \'{"cameraId":4, "control": "in"}\'' console.log '' show_methods_available 'ss' .action (cmd, options) -> console.log '[DEBUG] : DSM Surveillance Station API command selected' if program.debug execute 'ss', cmd, options program.parse process.argv
182519
CONFIG_DIR = '.syno' CONFIG_FILE = 'config.yaml' DEFAULT_PROTOCOL = 'https' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 5001 DEFAULT_ACCOUNT = 'admin' DEFAULT_PASSWD = '<PASSWORD>' DEFAULT_API_VERSION = '6.0.2' program = require 'commander' fs = require 'fs' url = require 'url' nconf = require 'nconf' ospath = require 'ospath' yaml = require 'js-yaml' Syno = require '../dist/syno' os = require 'os' execute = (api, cmd, options)-> console.log '[DEBUG] : Method name configured : %s', cmd if program.debug console.log '[DEBUG] : JSON payload configured : %s', options.payload if options.payload and program.debug console.log '[DEBUG] : Prettify output detected' if options.pretty and program.debug try payload = JSON.parse(options.payload or '{}') catch exception console.log '[ERROR] : JSON Exception : %s', exception process.exit 1 syno[api][cmd] payload, (err, data) -> console.log '[ERROR] : %s', err if err if options.pretty data = JSON.stringify data, undefined, 2 else data = JSON.stringify data console.log data if data syno.auth.logout() process.exit 0 show_methods_available = (api)-> console.log ' Available methods:' console.log '' syno[api]['getMethods'] {}, (data) -> console.log " $ syno #{api} #{method}" for method in data console.log ' None' if data.length is 0 console.log '' main = program .version '2.1.0' .description 'Synology Rest API Command Line' .option '-c, --config <path>', "DSM Configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Commands:' console.log '' console.log ' diskstationmanager|dsm [options] <method> DSM API' console.log ' filestation|fs [options] <method> DSM File Station API' console.log ' downloadstation|dl [options] <method> DSM Download Station API' console.log ' audiostation|as [options] <method> DSM Audio Station API' console.log ' videostation|vs [options] <method> DSM Video Station API' console.log ' videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm getInfo' console.log ' $ syno filestation|fs getInfo' console.log ' $ syno downloadstation|dl getInfo' console.log ' $ syno audiostation|as getInfo' console.log ' $ syno videostation|vs getInfo' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":5}\' --pretty' console.log ' $ syno surveillancestation|ss getInfo' console.log '' program.parse process.argv if program.args.length is 0 program.help() else if (program.args.length > 0 and program.args[0] isnt 'diskstationmanager' and program.args[0] isnt 'filestation' and program.args[0] isnt 'downloadstation' and program.args[0] isnt 'audiostation' and program.args[0] isnt 'videostation' and program.args[0] isnt 'videostationdtv' and program.args[0] isnt 'surveillancestation' and program.args[0] isnt 'dsm' and program.args[0] isnt 'fs' and program.args[0] isnt 'dl' and program.args[0] isnt 'as' and program.args[0] isnt 'vs' and program.args[0] isnt 'dtv' and program.args[0] isnt 'ss') console.log '' console.log " [ERROR] : #{program.args[0]} is not a valid command !" console.log '' console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm [options] <method> DSM API' console.log ' $ syno filestation|fs [options] <method> DSM File Station API' console.log ' $ syno downloadstation|dl [options] <method> DSM Download Station API' console.log ' $ syno audiostation|as [options] <method> DSM Audio Station API' console.log ' $ syno videostation|vs [options] <method> DSM Video Station API' console.log ' $ syno videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' $ syno surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' process.exit 1 # Load cmd line args and environment vars nconf.argv().file file: ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options if program.url console.log '[DEBUG] : Params URL detected : %s.', program.url if program.debug url_resolved = url.parse program.url url_resolved = url.parse DEFAULT_PROTOCOL + '://' + program.url if not url_resolved.protocol url_resolved.protocol = url_resolved.protocol.slice(0, -1) if url_resolved.protocol isnt 'http' and url_resolved.protocol isnt 'https' console.log '[ERROR] : Invalid Protocol URL detected : %s.', url_resolved.protocol process.exit 1 nconf.set 'url:protocol', url_resolved.protocol nconf.set 'url:host', url_resolved.hostname or DEFAULT_HOST nconf.set 'url:port', url_resolved.port or DEFAULT_PORT nconf.set 'url:account', if url_resolved.auth then url_resolved.auth.split(':')[0] else DEFAULT_ACCOUNT nconf.set 'url:passwd', if url_resolved.auth then url_resolved.auth.split(':')[1] else DEFAULT_PASSWD nconf.set 'url:apiVersion', main.api or DEFAULT_API_VERSION else if program.config console.log '[DEBUG] : Load config file : %s', program.config if program.debug try fs.accessSync program.config catch console.log '[ERROR] : Config file : %s not found', program.config process.exit 1 nconf.file file: program.config format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options nconf.overrides url: apiVersion: main.api or DEFAULT_API_VERSION else # If no directory -> create directory and save the file try fs.accessSync ospath.home() + "/#{CONFIG_DIR}" catch console.log '[DEBUG] : Default configuration directory does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}" if program.debug fs.mkdirSync ospath.home() + "/#{CONFIG_DIR}" try fs.accessSync ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" catch console.log '[DEBUG] : Default configuration file does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" if program.debug nconf.set 'url:protocol', DEFAULT_PROTOCOL nconf.set 'url:host', DEFAULT_HOST nconf.set 'url:port', DEFAULT_PORT nconf.set 'url:account', DEFAULT_ACCOUNT nconf.set 'url:passwd', DEFAULT_PASSWD nconf.set 'url:apiVersion', DEFAULT_API_VERSION nconf.save() nconf.overrides url: apiVersion: (nconf.get 'url:apiVersion') or main.api or DEFAULT_API_VERSION nconf.defaults url: protocol: DEFAULT_PROTOCOL host: DEFAULT_HOST port: DEFAULT_PORT account: DEFAULT_ACCOUNT passwd: <PASSWORD> apiVersion: DEFAULT_API_VERSION if program.debug console.log '[DEBUG] : DSM Connection URL configured : %s://%s:%s@%s:%s', nconf.get('url:protocol'), nconf.get('url:account'), nconf.get('url:passwd'), nconf.get('url:host'), nconf.get('url:port') syno = new Syno protocol: process.env.SYNO_PROTOCOL or nconf.get 'url:protocol' host: process.env.SYNO_HOST or nconf.get 'url:host' port: process.env.SYNO_PORT or nconf.get 'url:port' account: process.env.SYNO_ACCOUNT or nconf.get 'url:account' passwd: process.env.SYNO_PASSWORD or nconf.get 'url:passwd' apiVersion: process.env.SYNO_API_VERSION or nconf.get 'url:apiVersion' debug: process.env.SYNO_DEBUG or main.debug ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or main.ignoreCertificateErrors program .command 'diskstationmanager <method>' .alias 'dsm' .description 'DSM API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm startFindme' console.log ' $ syno diskstationmanager|dsm getInfo --pretty\'' console.log ' $ syno diskstationmanagercore|dsm listUsers' console.log ' $ syno diskstationmanagercore|dsm listPackages' console.log '' show_methods_available 'dsm' .action (cmd, options) -> console.log '[DEBUG] : DSM API command selected' if program.debug execute 'dsm', cmd, options program .command 'filestation <method>' .alias 'fs' .description 'DSM File Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno filestation|fs listSharings' console.log ' $ syno filestation|fs list --pretty --payload \'{"folder_path":"/path/to/folder"}\'' console.log '' show_methods_available 'fs' .action (cmd, options) -> console.log '[DEBUG] : DSM File Station API command selected' if program.debug execute 'fs', cmd, options program .command 'downloadstation <method>' .alias 'dl' .description 'DSM Download Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno downloadstation|dl createTask --payload \'{"uri":"magnet|ed2k|ftp(s)|http(s)://link"}\'' console.log ' $ syno downloadstation|dl listTasks' console.log ' $ syno downloadstation|dl listTasks --payload \'{"limit":1}\'' console.log ' $ syno downloadstation|dl getInfoTask --pretty --payload \'{"id":"task_id"}\'' console.log '' show_methods_available 'dl' .action (cmd, options) -> console.log '[DEBUG] : DSM Download Station API command selected' if program.debug execute 'dl', cmd, options program .command('audiostation <method>') .alias('as') .description('DSM Audio Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno audiostation|as listSongs --payload \'{"limit":1}\'' console.log ' $ syno audiostation|as listAlbums' console.log ' $ syno audiostation|as searchSong --payload \'{"title":"victoria"}\'' console.log '' show_methods_available 'as' .action (cmd, options) -> console.log '[DEBUG] : DSM Audio Station API command selected' if program.debug execute 'as', cmd, options program .command('videostation <method>') .alias('vs') .description('DSM Video Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostation|vs listMovies --payload \'{"limit":1}\'' console.log ' $ syno videostation|vs getInfoTvShow --payload \'{"id":"episode_id"}\'' console.log '' show_methods_available 'vs' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station API command selected' if program.debug execute 'vs', cmd, options program .command('videostationdtv <method>') .alias('dtv') .description('DSM Video Station DTV API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":1}\'' console.log ' $ syno videostationdtv|dtv getInfoTuner --payload \'{"id":"tuner_id"}\'' console.log '' show_methods_available 'dtv' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station DTV API command selected' if program.debug execute 'dtv', cmd, options program .command('surveillancestation <method>') .alias('ss') .description('DSM Surveillance Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno surveillancestation|ss listCameras' console.log ' $ syno surveillancestation|ss getInfoCamera --payload \'{"cameraIds":4}\'' console.log ' $ syno surveillancestation|ss zoomPtz --payload \'{"cameraId":4, "control": "in"}\'' console.log '' show_methods_available 'ss' .action (cmd, options) -> console.log '[DEBUG] : DSM Surveillance Station API command selected' if program.debug execute 'ss', cmd, options program.parse process.argv
true
CONFIG_DIR = '.syno' CONFIG_FILE = 'config.yaml' DEFAULT_PROTOCOL = 'https' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 5001 DEFAULT_ACCOUNT = 'admin' DEFAULT_PASSWD = 'PI:PASSWORD:<PASSWORD>END_PI' DEFAULT_API_VERSION = '6.0.2' program = require 'commander' fs = require 'fs' url = require 'url' nconf = require 'nconf' ospath = require 'ospath' yaml = require 'js-yaml' Syno = require '../dist/syno' os = require 'os' execute = (api, cmd, options)-> console.log '[DEBUG] : Method name configured : %s', cmd if program.debug console.log '[DEBUG] : JSON payload configured : %s', options.payload if options.payload and program.debug console.log '[DEBUG] : Prettify output detected' if options.pretty and program.debug try payload = JSON.parse(options.payload or '{}') catch exception console.log '[ERROR] : JSON Exception : %s', exception process.exit 1 syno[api][cmd] payload, (err, data) -> console.log '[ERROR] : %s', err if err if options.pretty data = JSON.stringify data, undefined, 2 else data = JSON.stringify data console.log data if data syno.auth.logout() process.exit 0 show_methods_available = (api)-> console.log ' Available methods:' console.log '' syno[api]['getMethods'] {}, (data) -> console.log " $ syno #{api} #{method}" for method in data console.log ' None' if data.length is 0 console.log '' main = program .version '2.1.0' .description 'Synology Rest API Command Line' .option '-c, --config <path>', "DSM Configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Commands:' console.log '' console.log ' diskstationmanager|dsm [options] <method> DSM API' console.log ' filestation|fs [options] <method> DSM File Station API' console.log ' downloadstation|dl [options] <method> DSM Download Station API' console.log ' audiostation|as [options] <method> DSM Audio Station API' console.log ' videostation|vs [options] <method> DSM Video Station API' console.log ' videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm getInfo' console.log ' $ syno filestation|fs getInfo' console.log ' $ syno downloadstation|dl getInfo' console.log ' $ syno audiostation|as getInfo' console.log ' $ syno videostation|vs getInfo' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":5}\' --pretty' console.log ' $ syno surveillancestation|ss getInfo' console.log '' program.parse process.argv if program.args.length is 0 program.help() else if (program.args.length > 0 and program.args[0] isnt 'diskstationmanager' and program.args[0] isnt 'filestation' and program.args[0] isnt 'downloadstation' and program.args[0] isnt 'audiostation' and program.args[0] isnt 'videostation' and program.args[0] isnt 'videostationdtv' and program.args[0] isnt 'surveillancestation' and program.args[0] isnt 'dsm' and program.args[0] isnt 'fs' and program.args[0] isnt 'dl' and program.args[0] isnt 'as' and program.args[0] isnt 'vs' and program.args[0] isnt 'dtv' and program.args[0] isnt 'ss') console.log '' console.log " [ERROR] : #{program.args[0]} is not a valid command !" console.log '' console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm [options] <method> DSM API' console.log ' $ syno filestation|fs [options] <method> DSM File Station API' console.log ' $ syno downloadstation|dl [options] <method> DSM Download Station API' console.log ' $ syno audiostation|as [options] <method> DSM Audio Station API' console.log ' $ syno videostation|vs [options] <method> DSM Video Station API' console.log ' $ syno videostationdtv|dtv [options] <method> DSM Video Station DTV API' console.log ' $ syno surveillancestation|ss [options] <method> DSM Surveillance Station API' console.log '' process.exit 1 # Load cmd line args and environment vars nconf.argv().file file: ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options if program.url console.log '[DEBUG] : Params URL detected : %s.', program.url if program.debug url_resolved = url.parse program.url url_resolved = url.parse DEFAULT_PROTOCOL + '://' + program.url if not url_resolved.protocol url_resolved.protocol = url_resolved.protocol.slice(0, -1) if url_resolved.protocol isnt 'http' and url_resolved.protocol isnt 'https' console.log '[ERROR] : Invalid Protocol URL detected : %s.', url_resolved.protocol process.exit 1 nconf.set 'url:protocol', url_resolved.protocol nconf.set 'url:host', url_resolved.hostname or DEFAULT_HOST nconf.set 'url:port', url_resolved.port or DEFAULT_PORT nconf.set 'url:account', if url_resolved.auth then url_resolved.auth.split(':')[0] else DEFAULT_ACCOUNT nconf.set 'url:passwd', if url_resolved.auth then url_resolved.auth.split(':')[1] else DEFAULT_PASSWD nconf.set 'url:apiVersion', main.api or DEFAULT_API_VERSION else if program.config console.log '[DEBUG] : Load config file : %s', program.config if program.debug try fs.accessSync program.config catch console.log '[ERROR] : Config file : %s not found', program.config process.exit 1 nconf.file file: program.config format: stringify: (obj, options) -> yaml.safeDump obj, options parse: (obj, options) -> yaml.safeLoad obj, options nconf.overrides url: apiVersion: main.api or DEFAULT_API_VERSION else # If no directory -> create directory and save the file try fs.accessSync ospath.home() + "/#{CONFIG_DIR}" catch console.log '[DEBUG] : Default configuration directory does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}" if program.debug fs.mkdirSync ospath.home() + "/#{CONFIG_DIR}" try fs.accessSync ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" catch console.log '[DEBUG] : Default configuration file does not exist : %s. Creating...', ospath.home() + "/#{CONFIG_DIR}/#{CONFIG_FILE}" if program.debug nconf.set 'url:protocol', DEFAULT_PROTOCOL nconf.set 'url:host', DEFAULT_HOST nconf.set 'url:port', DEFAULT_PORT nconf.set 'url:account', DEFAULT_ACCOUNT nconf.set 'url:passwd', DEFAULT_PASSWD nconf.set 'url:apiVersion', DEFAULT_API_VERSION nconf.save() nconf.overrides url: apiVersion: (nconf.get 'url:apiVersion') or main.api or DEFAULT_API_VERSION nconf.defaults url: protocol: DEFAULT_PROTOCOL host: DEFAULT_HOST port: DEFAULT_PORT account: DEFAULT_ACCOUNT passwd: PI:PASSWORD:<PASSWORD>END_PI apiVersion: DEFAULT_API_VERSION if program.debug console.log '[DEBUG] : DSM Connection URL configured : %s://%s:%s@%s:%s', nconf.get('url:protocol'), nconf.get('url:account'), nconf.get('url:passwd'), nconf.get('url:host'), nconf.get('url:port') syno = new Syno protocol: process.env.SYNO_PROTOCOL or nconf.get 'url:protocol' host: process.env.SYNO_HOST or nconf.get 'url:host' port: process.env.SYNO_PORT or nconf.get 'url:port' account: process.env.SYNO_ACCOUNT or nconf.get 'url:account' passwd: process.env.SYNO_PASSWORD or nconf.get 'url:passwd' apiVersion: process.env.SYNO_API_VERSION or nconf.get 'url:apiVersion' debug: process.env.SYNO_DEBUG or main.debug ignoreCertificateErrors: process.env.SYNO_IGNORE_CERTIFICATE_ERRORS or main.ignoreCertificateErrors program .command 'diskstationmanager <method>' .alias 'dsm' .description 'DSM API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno diskstationmanager|dsm startFindme' console.log ' $ syno diskstationmanager|dsm getInfo --pretty\'' console.log ' $ syno diskstationmanagercore|dsm listUsers' console.log ' $ syno diskstationmanagercore|dsm listPackages' console.log '' show_methods_available 'dsm' .action (cmd, options) -> console.log '[DEBUG] : DSM API command selected' if program.debug execute 'dsm', cmd, options program .command 'filestation <method>' .alias 'fs' .description 'DSM File Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno filestation|fs listSharings' console.log ' $ syno filestation|fs list --pretty --payload \'{"folder_path":"/path/to/folder"}\'' console.log '' show_methods_available 'fs' .action (cmd, options) -> console.log '[DEBUG] : DSM File Station API command selected' if program.debug execute 'fs', cmd, options program .command 'downloadstation <method>' .alias 'dl' .description 'DSM Download Station API' .option '-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}" .option '-u, --url <url>', "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}" .option '-p, --payload <payload>', 'JSON Payload' .option '-P, --pretty', 'Prettyprint JSON Output' .option '-d, --debug', 'Enabling Debugging Output' .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno downloadstation|dl createTask --payload \'{"uri":"magnet|ed2k|ftp(s)|http(s)://link"}\'' console.log ' $ syno downloadstation|dl listTasks' console.log ' $ syno downloadstation|dl listTasks --payload \'{"limit":1}\'' console.log ' $ syno downloadstation|dl getInfoTask --pretty --payload \'{"id":"task_id"}\'' console.log '' show_methods_available 'dl' .action (cmd, options) -> console.log '[DEBUG] : DSM Download Station API command selected' if program.debug execute 'dl', cmd, options program .command('audiostation <method>') .alias('as') .description('DSM Audio Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno audiostation|as listSongs --payload \'{"limit":1}\'' console.log ' $ syno audiostation|as listAlbums' console.log ' $ syno audiostation|as searchSong --payload \'{"title":"victoria"}\'' console.log '' show_methods_available 'as' .action (cmd, options) -> console.log '[DEBUG] : DSM Audio Station API command selected' if program.debug execute 'as', cmd, options program .command('videostation <method>') .alias('vs') .description('DSM Video Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostation|vs listMovies --payload \'{"limit":1}\'' console.log ' $ syno videostation|vs getInfoTvShow --payload \'{"id":"episode_id"}\'' console.log '' show_methods_available 'vs' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station API command selected' if program.debug execute 'vs', cmd, options program .command('videostationdtv <method>') .alias('dtv') .description('DSM Video Station DTV API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno videostationdtv|dtv listChannels --payload \'{"limit":1}\'' console.log ' $ syno videostationdtv|dtv getInfoTuner --payload \'{"id":"tuner_id"}\'' console.log '' show_methods_available 'dtv' .action (cmd, options) -> console.log '[DEBUG] : DSM Video Station DTV API command selected' if program.debug execute 'dtv', cmd, options program .command('surveillancestation <method>') .alias('ss') .description('DSM Surveillance Station API') .option('-c, --config <path>', "DSM configuration file. Default to ~/#{CONFIG_DIR}/#{CONFIG_FILE}") .option('-u, --url <url>' , "DSM URL. Default to #{DEFAULT_PROTOCOL}://#{DEFAULT_ACCOUNT}:#{DEFAULT_PASSWD}@#{DEFAULT_HOST}:#{DEFAULT_PORT}") .option('-p, --payload <payload>', 'JSON Payload') .option('-P, --pretty', 'Prettyprint JSON Output') .option('-d, --debug', 'Enabling Debugging Output') .option '-a, --api <version>', "DSM API Version. Default to #{DEFAULT_API_VERSION}" .option '-i, --ignore-certificate-errors', 'Ignore certificate errors' .on '--help', -> console.log ' Examples:' console.log '' console.log ' $ syno surveillancestation|ss listCameras' console.log ' $ syno surveillancestation|ss getInfoCamera --payload \'{"cameraIds":4}\'' console.log ' $ syno surveillancestation|ss zoomPtz --payload \'{"cameraId":4, "control": "in"}\'' console.log '' show_methods_available 'ss' .action (cmd, options) -> console.log '[DEBUG] : DSM Surveillance Station API command selected' if program.debug execute 'ss', cmd, options program.parse process.argv
[ { "context": " \"git commit -m '.'\"\n \"git remote add heroku git@heroku.com:#{app}.git\"\n \"git push -fu heroku master\"\n ", "end": 6556, "score": 0.9832938313484192, "start": 6542, "tag": "EMAIL", "value": "git@heroku.com" } ]
gulpfile.coffee
geekjuice/StahkPhotos
8
### Modules ### _ = require('lodash') chalk = require('chalk') gulp = require('gulp') clean = require('gulp-rimraf') cjsx = require('gulp-cjsx') filter = require('gulp-filter') iif = require('gulp-if') imagemin = require('gulp-imagemin') jade = require('gulp-jade') plumber = require('gulp-plumber') rename = require('gulp-rename') sass = require('gulp-ruby-sass') nodemon = require('gulp-nodemon') uglify = require('gulp-uglify') sync = require('browser-sync') { spawn } = require('child_process') ### Variables ### env = require('./env.json') data = _.extend({}, env) ### Directory Paths ### _src = './src' _build = './_build' DIR = modules: './node_modules' src: root: _src html: "#{_src}/frontend/html" js: "#{_src}/frontend/js" css: "#{_src}/frontend/css" img: "#{_src}/frontend/img" misc: "#{_src}/frontend/misc" vendor: "#{_src}/frontend/vendor" backend: "#{_src}/backend" shared: "#{_src}/shared" build: root: _build public: "#{_build}/public" js: "#{_build}/public/js" css: "#{_build}/public/css" img: "#{_build}/public/img" vendor: js: "#{_build}/public/js/vendor" css: "#{_build}/public/css/vendor" ### Task Manager ### _do = (src='', dest='', task='', filename='') -> _copy = task is '' _sass = /sass/.test task _jade = /jade/.test task _coffee = /coffee|cjsx/.test task _uglify = /uglify/.test task _imagemin = /imagemin/.test task _rename = /rename/.test task _dev = /dev/.test task if _sass sass(src, {compass: true, style: 'compressed', sourcemap: false}) # Sass .pipe(do plumber) # Plumber .pipe(gulp.dest(dest)) # Destination .pipe(filter('**/*.css')) # Filter CSS .pipe(sync.reload(stream: true)) # BrowserSync else gulp.src(src) .pipe(do plumber) # Plumber .pipe(iif(_jade, jade({data, pretty: true}))) # Jade .pipe(iif(_coffee, cjsx(bare: true))) # Coffee/React .pipe(iif(_uglify and not _dev, uglify(compress: drop_debugger: false))) # Uglify .pipe(iif(_imagemin and not _dev, imagemin(progressive: true))) # Imagemin .pipe(iif(_rename and !!filename, rename(basename: filename))) # Rename .pipe(gulp.dest(dest)) # Destination ### Clean ### gulp.task 'clean', -> gulp.src(DIR.build.root, {read: false}).pipe(clean()) gulp.task 'clean:modules', -> gulp.src([DIR.modules, DIR.src.vendor], {read: false}).pipe(clean()) gulp.task 'clean:all', ['clean', 'clean:modules'] ### Vendor Files ### gulp.task 'vendor', -> _do("#{DIR.src.vendor}/requirejs/require.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/zepto/zepto.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/lodash/lodash.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/react/react-with-addons.js", DIR.build.vendor.js, 'uglify rename', 'react') _do("#{DIR.src.vendor}/flux/dist/Flux.js", DIR.build.vendor.js, 'uglify rename', 'flux') _do("#{DIR.src.vendor}/eventEmitter/eventEmitter.js", DIR.build.vendor.js, 'uglify rename', 'event') _do("#{DIR.src.vendor}/backbone/backbone.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/bluebird/js/browser/bluebird.js", DIR.build.vendor.js, 'uglify rename', 'bluebird') _do("#{DIR.src.vendor}/prism/prism.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/prism/themes/prism.css", DIR.build.vendor.css) ### Tasks ### gulp.task 'misc', -> _do("#{DIR.src.misc}/**/*", DIR.build.public) gulp.task 'html', -> _do(["#{DIR.src.html}/**/*.jade", "!#{DIR.src.html}/**/_*.jade"], DIR.build.public, 'jade') gulp.task 'css', -> _do(DIR.src.css, DIR.build.css, 'sass') gulp.task 'js', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx uglify') gulp.task 'img', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin') gulp.task 'js:dev', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx dev') gulp.task 'img:dev', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin dev') gulp.task 'backend', -> _do(["!#{DIR.src.backend}/**/*.coffee", "#{DIR.src.backend}/**/*"], DIR.build.root) _do("#{DIR.src.backend}/**/*.coffee", DIR.build.root, 'cjsx uglify') gulp.task 'shared', -> _do("#{DIR.src.shared}/**/*.coffee", DIR.build.js, 'coffee') _do("#{DIR.src.shared}/**/*.coffee", DIR.build.root, 'coffee') ### Build ### gulp.task 'build:backend', ['shared', 'backend'] gulp.task 'build:static:dev', ['shared', 'misc', 'html', 'css', 'js:dev', 'img:dev'] gulp.task 'build:static:prod', ['vendor', 'shared', 'misc', 'html', 'js', 'css', 'img'] gulp.task 'build:dev', ['build:static:dev', 'build:backend'] gulp.task 'build:prod', ['build:static:prod', 'build:backend'] ### Watch/BrowserSync ### gulp.task 'watch', ['watch:backend', 'watch:static'] gulp.task 'watch:backend', ['nodemon'], -> gulp.watch ["!#{DIR.src.backend}/public", "#{DIR.src.backend}/**/*"], ['backend', sync.reload] gulp.task 'nodemon', ['build:backend'], -> nodemon script: "#{DIR.build.root}/server.js" ignore: ["#{DIR.build.public[2..]}/", "#{DIR.modules[2..]}/"] nodeArgs: ['--debug'] env: NODE_ENV: 'development' DEBUG: 'StahkPhotos' gulp.task 'watch:static', ['browser-sync'], -> gulp.watch "#{DIR.src.css}/**/*.sass", ['css'] gulp.watch "#{DIR.src.js}/**/*.{coffee,cjsx}", ['js:dev', sync.reload] gulp.watch "#{DIR.src.html}/**/*.jade", ['html', sync.reload] gulp.watch "#{DIR.src.shared}/**/*.coffee", ['shared', sync.reload] gulp.task 'browser-sync', ['build:static:dev'], -> sync proxy: "localhost:#{env.PORT}" port: env.BROWSERSYNC_PORT open: false notify: false ### Deploy Heroku ### write = (data) -> process.stdout.write(chalk.white(data.toString())) run = (cmd, cwd, cb) -> opts = if cwd then { cwd } else {} parts = cmd.split(/\s+/g) p = spawn(parts[0], parts[1..], opts) p.stdout.on('data', write) p.stderr.on('data', write) p.on 'exit', (code) -> if code err = new Error("command #{cmd} exited [code: #{code}]") err = _.extend {}, err, { code, cmd } cb?(err or null) series = (cmds, cwd, cb) -> do execNext = -> run cmds.shift(), cwd, (err) -> return cb(err) if err if cmds.length then execNext() else cb(null) heroku = (prod) -> app = "#{env.HEROKU.toLowerCase()}#{unless prod then '-qa' else ''}" -> CMDS = [ "rm -rf .git" "git init" "git add -A" "git commit -m '.'" "git remote add heroku git@heroku.com:#{app}.git" "git push -fu heroku master" ] series CMDS, DIR.build.root, (err) -> if err console.log err console.log(chalk.red('[Error] Deploy to Heroku failed!')) else console.log(chalk.green('[Success] Deploy to Heroku successful!')) deploy = (prod) -> -> CMDS = [ "gulp clean" "gulp build:prod" "gulp heroku:#{if prod then 'prod' else 'qa'}" ] series CMDS, null, (err) -> if err console.log(chalk.red('[Error] Deploy failed!')) else console.log(chalk.green('[Success] Deploy successful!')) gulp.task 'heroku:qa', heroku(false) gulp.task 'heroku:prod', heroku(true) gulp.task 'deploy:qa', deploy(false) gulp.task 'deploy:prod', deploy(true) ### Default Tasks ### gulp.task 'init', ['vendor', 'watch'] gulp.task 'default', ['watch']
86998
### Modules ### _ = require('lodash') chalk = require('chalk') gulp = require('gulp') clean = require('gulp-rimraf') cjsx = require('gulp-cjsx') filter = require('gulp-filter') iif = require('gulp-if') imagemin = require('gulp-imagemin') jade = require('gulp-jade') plumber = require('gulp-plumber') rename = require('gulp-rename') sass = require('gulp-ruby-sass') nodemon = require('gulp-nodemon') uglify = require('gulp-uglify') sync = require('browser-sync') { spawn } = require('child_process') ### Variables ### env = require('./env.json') data = _.extend({}, env) ### Directory Paths ### _src = './src' _build = './_build' DIR = modules: './node_modules' src: root: _src html: "#{_src}/frontend/html" js: "#{_src}/frontend/js" css: "#{_src}/frontend/css" img: "#{_src}/frontend/img" misc: "#{_src}/frontend/misc" vendor: "#{_src}/frontend/vendor" backend: "#{_src}/backend" shared: "#{_src}/shared" build: root: _build public: "#{_build}/public" js: "#{_build}/public/js" css: "#{_build}/public/css" img: "#{_build}/public/img" vendor: js: "#{_build}/public/js/vendor" css: "#{_build}/public/css/vendor" ### Task Manager ### _do = (src='', dest='', task='', filename='') -> _copy = task is '' _sass = /sass/.test task _jade = /jade/.test task _coffee = /coffee|cjsx/.test task _uglify = /uglify/.test task _imagemin = /imagemin/.test task _rename = /rename/.test task _dev = /dev/.test task if _sass sass(src, {compass: true, style: 'compressed', sourcemap: false}) # Sass .pipe(do plumber) # Plumber .pipe(gulp.dest(dest)) # Destination .pipe(filter('**/*.css')) # Filter CSS .pipe(sync.reload(stream: true)) # BrowserSync else gulp.src(src) .pipe(do plumber) # Plumber .pipe(iif(_jade, jade({data, pretty: true}))) # Jade .pipe(iif(_coffee, cjsx(bare: true))) # Coffee/React .pipe(iif(_uglify and not _dev, uglify(compress: drop_debugger: false))) # Uglify .pipe(iif(_imagemin and not _dev, imagemin(progressive: true))) # Imagemin .pipe(iif(_rename and !!filename, rename(basename: filename))) # Rename .pipe(gulp.dest(dest)) # Destination ### Clean ### gulp.task 'clean', -> gulp.src(DIR.build.root, {read: false}).pipe(clean()) gulp.task 'clean:modules', -> gulp.src([DIR.modules, DIR.src.vendor], {read: false}).pipe(clean()) gulp.task 'clean:all', ['clean', 'clean:modules'] ### Vendor Files ### gulp.task 'vendor', -> _do("#{DIR.src.vendor}/requirejs/require.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/zepto/zepto.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/lodash/lodash.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/react/react-with-addons.js", DIR.build.vendor.js, 'uglify rename', 'react') _do("#{DIR.src.vendor}/flux/dist/Flux.js", DIR.build.vendor.js, 'uglify rename', 'flux') _do("#{DIR.src.vendor}/eventEmitter/eventEmitter.js", DIR.build.vendor.js, 'uglify rename', 'event') _do("#{DIR.src.vendor}/backbone/backbone.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/bluebird/js/browser/bluebird.js", DIR.build.vendor.js, 'uglify rename', 'bluebird') _do("#{DIR.src.vendor}/prism/prism.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/prism/themes/prism.css", DIR.build.vendor.css) ### Tasks ### gulp.task 'misc', -> _do("#{DIR.src.misc}/**/*", DIR.build.public) gulp.task 'html', -> _do(["#{DIR.src.html}/**/*.jade", "!#{DIR.src.html}/**/_*.jade"], DIR.build.public, 'jade') gulp.task 'css', -> _do(DIR.src.css, DIR.build.css, 'sass') gulp.task 'js', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx uglify') gulp.task 'img', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin') gulp.task 'js:dev', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx dev') gulp.task 'img:dev', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin dev') gulp.task 'backend', -> _do(["!#{DIR.src.backend}/**/*.coffee", "#{DIR.src.backend}/**/*"], DIR.build.root) _do("#{DIR.src.backend}/**/*.coffee", DIR.build.root, 'cjsx uglify') gulp.task 'shared', -> _do("#{DIR.src.shared}/**/*.coffee", DIR.build.js, 'coffee') _do("#{DIR.src.shared}/**/*.coffee", DIR.build.root, 'coffee') ### Build ### gulp.task 'build:backend', ['shared', 'backend'] gulp.task 'build:static:dev', ['shared', 'misc', 'html', 'css', 'js:dev', 'img:dev'] gulp.task 'build:static:prod', ['vendor', 'shared', 'misc', 'html', 'js', 'css', 'img'] gulp.task 'build:dev', ['build:static:dev', 'build:backend'] gulp.task 'build:prod', ['build:static:prod', 'build:backend'] ### Watch/BrowserSync ### gulp.task 'watch', ['watch:backend', 'watch:static'] gulp.task 'watch:backend', ['nodemon'], -> gulp.watch ["!#{DIR.src.backend}/public", "#{DIR.src.backend}/**/*"], ['backend', sync.reload] gulp.task 'nodemon', ['build:backend'], -> nodemon script: "#{DIR.build.root}/server.js" ignore: ["#{DIR.build.public[2..]}/", "#{DIR.modules[2..]}/"] nodeArgs: ['--debug'] env: NODE_ENV: 'development' DEBUG: 'StahkPhotos' gulp.task 'watch:static', ['browser-sync'], -> gulp.watch "#{DIR.src.css}/**/*.sass", ['css'] gulp.watch "#{DIR.src.js}/**/*.{coffee,cjsx}", ['js:dev', sync.reload] gulp.watch "#{DIR.src.html}/**/*.jade", ['html', sync.reload] gulp.watch "#{DIR.src.shared}/**/*.coffee", ['shared', sync.reload] gulp.task 'browser-sync', ['build:static:dev'], -> sync proxy: "localhost:#{env.PORT}" port: env.BROWSERSYNC_PORT open: false notify: false ### Deploy Heroku ### write = (data) -> process.stdout.write(chalk.white(data.toString())) run = (cmd, cwd, cb) -> opts = if cwd then { cwd } else {} parts = cmd.split(/\s+/g) p = spawn(parts[0], parts[1..], opts) p.stdout.on('data', write) p.stderr.on('data', write) p.on 'exit', (code) -> if code err = new Error("command #{cmd} exited [code: #{code}]") err = _.extend {}, err, { code, cmd } cb?(err or null) series = (cmds, cwd, cb) -> do execNext = -> run cmds.shift(), cwd, (err) -> return cb(err) if err if cmds.length then execNext() else cb(null) heroku = (prod) -> app = "#{env.HEROKU.toLowerCase()}#{unless prod then '-qa' else ''}" -> CMDS = [ "rm -rf .git" "git init" "git add -A" "git commit -m '.'" "git remote add heroku <EMAIL>:#{app}.git" "git push -fu heroku master" ] series CMDS, DIR.build.root, (err) -> if err console.log err console.log(chalk.red('[Error] Deploy to Heroku failed!')) else console.log(chalk.green('[Success] Deploy to Heroku successful!')) deploy = (prod) -> -> CMDS = [ "gulp clean" "gulp build:prod" "gulp heroku:#{if prod then 'prod' else 'qa'}" ] series CMDS, null, (err) -> if err console.log(chalk.red('[Error] Deploy failed!')) else console.log(chalk.green('[Success] Deploy successful!')) gulp.task 'heroku:qa', heroku(false) gulp.task 'heroku:prod', heroku(true) gulp.task 'deploy:qa', deploy(false) gulp.task 'deploy:prod', deploy(true) ### Default Tasks ### gulp.task 'init', ['vendor', 'watch'] gulp.task 'default', ['watch']
true
### Modules ### _ = require('lodash') chalk = require('chalk') gulp = require('gulp') clean = require('gulp-rimraf') cjsx = require('gulp-cjsx') filter = require('gulp-filter') iif = require('gulp-if') imagemin = require('gulp-imagemin') jade = require('gulp-jade') plumber = require('gulp-plumber') rename = require('gulp-rename') sass = require('gulp-ruby-sass') nodemon = require('gulp-nodemon') uglify = require('gulp-uglify') sync = require('browser-sync') { spawn } = require('child_process') ### Variables ### env = require('./env.json') data = _.extend({}, env) ### Directory Paths ### _src = './src' _build = './_build' DIR = modules: './node_modules' src: root: _src html: "#{_src}/frontend/html" js: "#{_src}/frontend/js" css: "#{_src}/frontend/css" img: "#{_src}/frontend/img" misc: "#{_src}/frontend/misc" vendor: "#{_src}/frontend/vendor" backend: "#{_src}/backend" shared: "#{_src}/shared" build: root: _build public: "#{_build}/public" js: "#{_build}/public/js" css: "#{_build}/public/css" img: "#{_build}/public/img" vendor: js: "#{_build}/public/js/vendor" css: "#{_build}/public/css/vendor" ### Task Manager ### _do = (src='', dest='', task='', filename='') -> _copy = task is '' _sass = /sass/.test task _jade = /jade/.test task _coffee = /coffee|cjsx/.test task _uglify = /uglify/.test task _imagemin = /imagemin/.test task _rename = /rename/.test task _dev = /dev/.test task if _sass sass(src, {compass: true, style: 'compressed', sourcemap: false}) # Sass .pipe(do plumber) # Plumber .pipe(gulp.dest(dest)) # Destination .pipe(filter('**/*.css')) # Filter CSS .pipe(sync.reload(stream: true)) # BrowserSync else gulp.src(src) .pipe(do plumber) # Plumber .pipe(iif(_jade, jade({data, pretty: true}))) # Jade .pipe(iif(_coffee, cjsx(bare: true))) # Coffee/React .pipe(iif(_uglify and not _dev, uglify(compress: drop_debugger: false))) # Uglify .pipe(iif(_imagemin and not _dev, imagemin(progressive: true))) # Imagemin .pipe(iif(_rename and !!filename, rename(basename: filename))) # Rename .pipe(gulp.dest(dest)) # Destination ### Clean ### gulp.task 'clean', -> gulp.src(DIR.build.root, {read: false}).pipe(clean()) gulp.task 'clean:modules', -> gulp.src([DIR.modules, DIR.src.vendor], {read: false}).pipe(clean()) gulp.task 'clean:all', ['clean', 'clean:modules'] ### Vendor Files ### gulp.task 'vendor', -> _do("#{DIR.src.vendor}/requirejs/require.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/zepto/zepto.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/lodash/lodash.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/react/react-with-addons.js", DIR.build.vendor.js, 'uglify rename', 'react') _do("#{DIR.src.vendor}/flux/dist/Flux.js", DIR.build.vendor.js, 'uglify rename', 'flux') _do("#{DIR.src.vendor}/eventEmitter/eventEmitter.js", DIR.build.vendor.js, 'uglify rename', 'event') _do("#{DIR.src.vendor}/backbone/backbone.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/bluebird/js/browser/bluebird.js", DIR.build.vendor.js, 'uglify rename', 'bluebird') _do("#{DIR.src.vendor}/prism/prism.js", DIR.build.vendor.js, 'uglify') _do("#{DIR.src.vendor}/prism/themes/prism.css", DIR.build.vendor.css) ### Tasks ### gulp.task 'misc', -> _do("#{DIR.src.misc}/**/*", DIR.build.public) gulp.task 'html', -> _do(["#{DIR.src.html}/**/*.jade", "!#{DIR.src.html}/**/_*.jade"], DIR.build.public, 'jade') gulp.task 'css', -> _do(DIR.src.css, DIR.build.css, 'sass') gulp.task 'js', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx uglify') gulp.task 'img', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin') gulp.task 'js:dev', -> _do("#{DIR.src.js}/**/*.{coffee,cjsx}", DIR.build.js, 'cjsx dev') gulp.task 'img:dev', -> _do("#{DIR.src.img}/**/*", DIR.build.img, 'imagemin dev') gulp.task 'backend', -> _do(["!#{DIR.src.backend}/**/*.coffee", "#{DIR.src.backend}/**/*"], DIR.build.root) _do("#{DIR.src.backend}/**/*.coffee", DIR.build.root, 'cjsx uglify') gulp.task 'shared', -> _do("#{DIR.src.shared}/**/*.coffee", DIR.build.js, 'coffee') _do("#{DIR.src.shared}/**/*.coffee", DIR.build.root, 'coffee') ### Build ### gulp.task 'build:backend', ['shared', 'backend'] gulp.task 'build:static:dev', ['shared', 'misc', 'html', 'css', 'js:dev', 'img:dev'] gulp.task 'build:static:prod', ['vendor', 'shared', 'misc', 'html', 'js', 'css', 'img'] gulp.task 'build:dev', ['build:static:dev', 'build:backend'] gulp.task 'build:prod', ['build:static:prod', 'build:backend'] ### Watch/BrowserSync ### gulp.task 'watch', ['watch:backend', 'watch:static'] gulp.task 'watch:backend', ['nodemon'], -> gulp.watch ["!#{DIR.src.backend}/public", "#{DIR.src.backend}/**/*"], ['backend', sync.reload] gulp.task 'nodemon', ['build:backend'], -> nodemon script: "#{DIR.build.root}/server.js" ignore: ["#{DIR.build.public[2..]}/", "#{DIR.modules[2..]}/"] nodeArgs: ['--debug'] env: NODE_ENV: 'development' DEBUG: 'StahkPhotos' gulp.task 'watch:static', ['browser-sync'], -> gulp.watch "#{DIR.src.css}/**/*.sass", ['css'] gulp.watch "#{DIR.src.js}/**/*.{coffee,cjsx}", ['js:dev', sync.reload] gulp.watch "#{DIR.src.html}/**/*.jade", ['html', sync.reload] gulp.watch "#{DIR.src.shared}/**/*.coffee", ['shared', sync.reload] gulp.task 'browser-sync', ['build:static:dev'], -> sync proxy: "localhost:#{env.PORT}" port: env.BROWSERSYNC_PORT open: false notify: false ### Deploy Heroku ### write = (data) -> process.stdout.write(chalk.white(data.toString())) run = (cmd, cwd, cb) -> opts = if cwd then { cwd } else {} parts = cmd.split(/\s+/g) p = spawn(parts[0], parts[1..], opts) p.stdout.on('data', write) p.stderr.on('data', write) p.on 'exit', (code) -> if code err = new Error("command #{cmd} exited [code: #{code}]") err = _.extend {}, err, { code, cmd } cb?(err or null) series = (cmds, cwd, cb) -> do execNext = -> run cmds.shift(), cwd, (err) -> return cb(err) if err if cmds.length then execNext() else cb(null) heroku = (prod) -> app = "#{env.HEROKU.toLowerCase()}#{unless prod then '-qa' else ''}" -> CMDS = [ "rm -rf .git" "git init" "git add -A" "git commit -m '.'" "git remote add heroku PI:EMAIL:<EMAIL>END_PI:#{app}.git" "git push -fu heroku master" ] series CMDS, DIR.build.root, (err) -> if err console.log err console.log(chalk.red('[Error] Deploy to Heroku failed!')) else console.log(chalk.green('[Success] Deploy to Heroku successful!')) deploy = (prod) -> -> CMDS = [ "gulp clean" "gulp build:prod" "gulp heroku:#{if prod then 'prod' else 'qa'}" ] series CMDS, null, (err) -> if err console.log(chalk.red('[Error] Deploy failed!')) else console.log(chalk.green('[Success] Deploy successful!')) gulp.task 'heroku:qa', heroku(false) gulp.task 'heroku:prod', heroku(true) gulp.task 'deploy:qa', deploy(false) gulp.task 'deploy:prod', deploy(true) ### Default Tasks ### gulp.task 'init', ['vendor', 'watch'] gulp.task 'default', ['watch']
[ { "context": "type: \"POST\",\n data: {\n new_password1: pass1,\n new_password2: pass2\n },\n data", "end": 2673, "score": 0.9992865324020386, "start": 2668, "tag": "PASSWORD", "value": "pass1" }, { "context": " new_password1: pass1,\n new_pas...
jotleaf/static/js/views_auth.coffee
reverie/jotleaf.com
1
# views_auth.coffee is for TopViews related to authentication and accounts class PasswordResetView extends TopView @bodyClass: 'password_reset' documentTitle: 'Reset Your Password' events: { 'submit form.password-reset-form': '_password_reset' } initialize: -> @makeMainWebsiteView('tpl_password_reset') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.email').focus() , 0) _password_reset: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') email = form.findOne('input.email').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Processing...') password_reset = $.ajax( { url: '/xhr/account/password/reset/', type: "POST", data: { email: email }, dataType: "json" cache: false, }) password_reset.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset.fail((err)=> # TODO: show an error message button.val(origVal) form.find('input').attr('disabled', false) ) class PasswordResetConfirmView extends TopView @bodyClass: 'password_reset_confirm' documentTitle: 'Confirm Resetting Your Password' events: { 'submit form.password-reset-confirm-form': '_password_reset_confirm' } initialize: -> @makeMainWebsiteView('tpl_password_reset_confirm') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-confirm-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.new_password1').focus() , 0) _password_reset_confirm: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') pass1 = form.findOne('input.new_password1').val() pass2 = form.findOne('input.new_password2').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Setting password...') urlWithParams = "/xhr/account/password/reset/confirm/#{@options.tokens}/" password_reset_confirm = $.ajax( { url: urlWithParams, type: "POST", data: { new_password1: pass1, new_password2: pass2 }, dataType: "json" cache: false, }) password_reset_confirm.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_confirm_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset_confirm.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoginView extends TopView @bodyClass: 'login' documentTitle: 'Sign in to Jotleaf' events: { 'submit form.login-form': '_login' } initialize: -> @makeMainWebsiteView('tpl_login') errorContainer = @$findOne('.error-container') form = @$findOne('form.login-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.username').focus() , 0) _login: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') username = form.findOne('input.username').val() password = form.findOne('input.password').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Authenticating...') login = $.ajax( { url: '/xhr/account/login/', type: "POST", data: { username: username, password: password }, dataType: "json" cache: false, }) login.done((response) => if response.authenticated JL.AuthState.setUser(response.user) # ugh followDB = Database2.modelDB(Follow) for f in response.follows followDB.addInstance(new Follow(f)) Backbone.history.navigate('/home/', {trigger: true}) else @errorsView.showErrors(response.errors) button.val(origVal) form.find('input').attr('disabled', false) ) login.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoggedOutView extends TopView @bodyClass: 'logout' documentTitle: 'Signed out of Jotleaf' initialize: -> @makeMainWebsiteView('tpl_logout') class RegistrationView extends BaseRegistration @bodyClass: 'register' documentTitle: 'Register a Jotleaf Account' render: => @makeMainWebsiteView('tpl_registration') class SettingsView extends TopView documentTitle: 'Jotleaf Account Settings' initialize: -> @makeMainWebsiteView('tpl_settings') @_tendon = new Tendon.Tendon(@$el, { user: JL.AuthState.getUser() }) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_follower', 'input.email_on_new_follower', @$el]) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_membership', 'input.email_on_new_membership', @$el]) @_tendon.useBundle(Tendon.twoWay, ['user', 'bio', 'textarea.bio', @$el]) submitBtn = @$findOne('input[type=submit]') @listenTo(submitBtn, 'click', => router._redirect('') ) unbind: => @_tendon.unbind()
71852
# views_auth.coffee is for TopViews related to authentication and accounts class PasswordResetView extends TopView @bodyClass: 'password_reset' documentTitle: 'Reset Your Password' events: { 'submit form.password-reset-form': '_password_reset' } initialize: -> @makeMainWebsiteView('tpl_password_reset') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.email').focus() , 0) _password_reset: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') email = form.findOne('input.email').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Processing...') password_reset = $.ajax( { url: '/xhr/account/password/reset/', type: "POST", data: { email: email }, dataType: "json" cache: false, }) password_reset.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset.fail((err)=> # TODO: show an error message button.val(origVal) form.find('input').attr('disabled', false) ) class PasswordResetConfirmView extends TopView @bodyClass: 'password_reset_confirm' documentTitle: 'Confirm Resetting Your Password' events: { 'submit form.password-reset-confirm-form': '_password_reset_confirm' } initialize: -> @makeMainWebsiteView('tpl_password_reset_confirm') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-confirm-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.new_password1').focus() , 0) _password_reset_confirm: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') pass1 = form.findOne('input.new_password1').val() pass2 = form.findOne('input.new_password2').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Setting password...') urlWithParams = "/xhr/account/password/reset/confirm/#{@options.tokens}/" password_reset_confirm = $.ajax( { url: urlWithParams, type: "POST", data: { new_password1: <PASSWORD>, new_password2: <PASSWORD> }, dataType: "json" cache: false, }) password_reset_confirm.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_confirm_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset_confirm.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoginView extends TopView @bodyClass: 'login' documentTitle: 'Sign in to Jotleaf' events: { 'submit form.login-form': '_login' } initialize: -> @makeMainWebsiteView('tpl_login') errorContainer = @$findOne('.error-container') form = @$findOne('form.login-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.username').focus() , 0) _login: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') username = form.findOne('input.username').val() password = form.findOne('input.password').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Authenticating...') login = $.ajax( { url: '/xhr/account/login/', type: "POST", data: { username: username, password: <PASSWORD> }, dataType: "json" cache: false, }) login.done((response) => if response.authenticated JL.AuthState.setUser(response.user) # ugh followDB = Database2.modelDB(Follow) for f in response.follows followDB.addInstance(new Follow(f)) Backbone.history.navigate('/home/', {trigger: true}) else @errorsView.showErrors(response.errors) button.val(origVal) form.find('input').attr('disabled', false) ) login.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoggedOutView extends TopView @bodyClass: 'logout' documentTitle: 'Signed out of Jotleaf' initialize: -> @makeMainWebsiteView('tpl_logout') class RegistrationView extends BaseRegistration @bodyClass: 'register' documentTitle: 'Register a Jotleaf Account' render: => @makeMainWebsiteView('tpl_registration') class SettingsView extends TopView documentTitle: 'Jotleaf Account Settings' initialize: -> @makeMainWebsiteView('tpl_settings') @_tendon = new Tendon.Tendon(@$el, { user: JL.AuthState.getUser() }) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_follower', 'input.email_on_new_follower', @$el]) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_membership', 'input.email_on_new_membership', @$el]) @_tendon.useBundle(Tendon.twoWay, ['user', 'bio', 'textarea.bio', @$el]) submitBtn = @$findOne('input[type=submit]') @listenTo(submitBtn, 'click', => router._redirect('') ) unbind: => @_tendon.unbind()
true
# views_auth.coffee is for TopViews related to authentication and accounts class PasswordResetView extends TopView @bodyClass: 'password_reset' documentTitle: 'Reset Your Password' events: { 'submit form.password-reset-form': '_password_reset' } initialize: -> @makeMainWebsiteView('tpl_password_reset') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.email').focus() , 0) _password_reset: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') email = form.findOne('input.email').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Processing...') password_reset = $.ajax( { url: '/xhr/account/password/reset/', type: "POST", data: { email: email }, dataType: "json" cache: false, }) password_reset.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset.fail((err)=> # TODO: show an error message button.val(origVal) form.find('input').attr('disabled', false) ) class PasswordResetConfirmView extends TopView @bodyClass: 'password_reset_confirm' documentTitle: 'Confirm Resetting Your Password' events: { 'submit form.password-reset-confirm-form': '_password_reset_confirm' } initialize: -> @makeMainWebsiteView('tpl_password_reset_confirm') errorContainer = @$findOne('.error-container') form = @$findOne('form.password-reset-confirm-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.new_password1').focus() , 0) _password_reset_confirm: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') pass1 = form.findOne('input.new_password1').val() pass2 = form.findOne('input.new_password2').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Setting password...') urlWithParams = "/xhr/account/password/reset/confirm/#{@options.tokens}/" password_reset_confirm = $.ajax( { url: urlWithParams, type: "POST", data: { new_password1: PI:PASSWORD:<PASSWORD>END_PI, new_password2: PI:PASSWORD:<PASSWORD>END_PI }, dataType: "json" cache: false, }) password_reset_confirm.done((response) => button.val(origVal) form.find('input').attr('disabled', false) if response.success @queueSuccessMessage(makeMessage('password_reset_confirm_success')) Backbone.history.navigate('/', {trigger: true}) else @errorsView.showErrors(response.data) ) password_reset_confirm.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoginView extends TopView @bodyClass: 'login' documentTitle: 'Sign in to Jotleaf' events: { 'submit form.login-form': '_login' } initialize: -> @makeMainWebsiteView('tpl_login') errorContainer = @$findOne('.error-container') form = @$findOne('form.login-form') @errorsView = new ErrorsView(form, errorContainer) setTimeout(=> form.findOne('input.username').focus() , 0) _login: (e) => e.preventDefault() form = $(e.target) form.find('input').attr('disabled', 'disabled') username = form.findOne('input.username').val() password = form.findOne('input.password').val() button = form.findOne('input[type=submit]') origVal = button.val() @errorsView.clearErrors() button.val('Authenticating...') login = $.ajax( { url: '/xhr/account/login/', type: "POST", data: { username: username, password: PI:PASSWORD:<PASSWORD>END_PI }, dataType: "json" cache: false, }) login.done((response) => if response.authenticated JL.AuthState.setUser(response.user) # ugh followDB = Database2.modelDB(Follow) for f in response.follows followDB.addInstance(new Follow(f)) Backbone.history.navigate('/home/', {trigger: true}) else @errorsView.showErrors(response.errors) button.val(origVal) form.find('input').attr('disabled', false) ) login.fail((err)=> button.val(origVal) form.find('input').attr('disabled', false) ) class LoggedOutView extends TopView @bodyClass: 'logout' documentTitle: 'Signed out of Jotleaf' initialize: -> @makeMainWebsiteView('tpl_logout') class RegistrationView extends BaseRegistration @bodyClass: 'register' documentTitle: 'Register a Jotleaf Account' render: => @makeMainWebsiteView('tpl_registration') class SettingsView extends TopView documentTitle: 'Jotleaf Account Settings' initialize: -> @makeMainWebsiteView('tpl_settings') @_tendon = new Tendon.Tendon(@$el, { user: JL.AuthState.getUser() }) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_follower', 'input.email_on_new_follower', @$el]) @_tendon.useBundle(Tendon.twoWayCheckbox, ['user', 'email_on_new_membership', 'input.email_on_new_membership', @$el]) @_tendon.useBundle(Tendon.twoWay, ['user', 'bio', 'textarea.bio', @$el]) submitBtn = @$findOne('input[type=submit]') @listenTo(submitBtn, 'click', => router._redirect('') ) unbind: => @_tendon.unbind()
[ { "context": "timestamps\", ->\n logView.textEditor.setText(\"64.242.88.10 - - [07/Mar/2004:16:45:56 -0800] details\")\n ", "end": 12334, "score": 0.9997387528419495, "start": 12322, "tag": "IP_ADDRESS", "value": "64.242.88.10" } ]
spec/log-view-spec.coffee
MRodalgaard/language-log
47
path = require 'path' {TextBuffer} = require 'atom' moment = require 'moment' LogView = require '../lib/log-view' describe "LogView", -> {logView, logFilter, text} = [] # Atom marks the line over a fold and folded # and the first line doesn't really fold getFoldedLines = -> count = logView.textEditor.getLineCount() - 1 i for i in [0..count] when logView.textEditor.isFoldedAtBufferRow(i) getFilteredLines = -> logFilter.results.text.join('') beforeEach -> text = "12:34 INFO: 1\n12:34 INFO: 2\n12:34 DEBUG: 3" buffer = new TextBuffer(text) editor = atom.workspace.buildTextEditor({buffer}) logView = new LogView(editor) logFilter = logView.logFilter atom.project.setPaths [path.join(__dirname, 'fixtures')] describe "view", -> it "has basic elements in view", -> expect(logView.settings).toBeDefined() expect(logView.find('.input-block')).toBeDefined() expect(logView.find('.btn-group-level')).toBeDefined() expect(logView.find('.descriptionLabel')).toBeDefined() describe "filter log text", -> it "filters simple text", -> expect(logView.textEditor.getText()).toEqual text expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter 'INFO' # TODO: Fails because it marks the line above folded as folded also!!! #expect(getFoldedLines()).toEqual [2] expect(logFilter.getFilteredLines()).toEqual [2] it "can filter out no lines", -> expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter '12:34' expect(logFilter.getFilteredLines()).toHaveLength 0 it "can filter out all lines", -> logFilter.performTextFilter 'XXX' expect(logFilter.getFilteredLines()).toEqual [0,1,2] it "accepts advanced regex expressions", -> logFilter.performTextFilter "\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [0,1] it "fetches the currently set filter", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "works with advanced regex filters", -> logView.filterBuffer.setText 'INFO{1}.*' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "shows error message on invalid regex", -> logView.filterBuffer.setText '*INFO' expect(atom.notifications.getNotifications()).toHaveLength 0 logView.filterButton.click() expect(atom.notifications.getNotifications()).toHaveLength 1 it "removes filter when no input", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logView.filterBuffer.setText '' logView.filterBuffer.emitter.emit('did-stop-changing') expect(logFilter.getFilteredLines()).toEqual [] it "can can invert the filter", -> logFilter.performTextFilter '!INFO' expect(logFilter.getFilteredLines()).toEqual [0,1] it "inverts with advanced regex filters", -> logFilter.performTextFilter "!\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [2] describe "filter log levels", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "filters and folds log level lines", -> logView.levelVerboseButton.click() expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [0,1] expect(logFilter.getFilteredLines()).toHaveLength 2 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [0,1,2] expect(logFilter.getFilteredLines()).toHaveLength 3 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [1,2] expect(logFilter.getFilteredLines()).toHaveLength 1 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [] expect(logFilter.getFilteredLines()).toHaveLength 0 it "gets list of scopes from button state", -> logView.updateButtons() expect(logView.getFilterScopes()).toHaveLength 0 logView.levelVerboseButton.click() expect(logView.getFilterScopes()).toHaveLength 1 logView.levelInfoButton.click() logView.levelDebugButton.click() logView.levelErrorButton.click() logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 5 logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 4 describe "all filters", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "can handle both level and text filters", -> logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logFilter.performTextFilter "INFO: 2" expect(logFilter.getFilteredLines()).toEqual [0,2] logFilter.performTextFilter "" expect(logFilter.getFilteredLines()).toEqual [2] logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [] describe "show description label", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "shows total lines and filtered lines", -> expect(logView.find('.description')[0].innerHTML).toBe "Showing 3 log lines" logView.levelDebugButton.click() expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 of 3 log lines" it "updates on file changes", -> logView.textEditor.deleteLine(0) advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 log lines" logView.textEditor.deleteLine(0) logView.levelDebugButton.click() advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 0 of 1 log lines" describe "log tailing", -> it "does not tail by default", -> pos = logView.textEditor.getCursorBufferPosition() logView.textEditor.buffer.append('\nNew log line') expect(logView.tailing).toBe false advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe false newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).toEqual pos it "can tail on log changes", -> atom.config.set('language-log.tail', true) pos = logView.textEditor.getCursorBufferPosition() expect(logView.tailing).toBe false logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).not.toEqual pos logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true expect(logView.textEditor.getCursorBufferPosition()).not.toEqual pos expect(logView.textEditor.getCursorBufferPosition()).not.toEqual newPos it "handles tailing destroyed tabs", -> atom.config.set('language-log.tail', true) logView.textEditor.destroy() logView.tail() expect(logView.textEditor.isDestroyed()).toBe true describe "adjacentLines", -> beforeEach -> logView.textEditor.setText "a\nb\nc\nd\ne\nf\ng" it "shows adjacent lines", -> logView.filterBuffer.setText 'd' atom.config.set('language-log.adjacentLines', 0) expect(logFilter.getFilteredLines()).toHaveLength 6 expect(getFilteredLines()).toBe "012456" atom.config.set('language-log.adjacentLines', 1) expect(logFilter.getFilteredLines()).toHaveLength 4 expect(getFilteredLines()).toBe "0156" it "handles out of bounds adjacent lines", -> logView.filterBuffer.setText 'a' atom.config.set('language-log.adjacentLines', 0) expect(getFilteredLines()).toBe "123456" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "3456" atom.config.set('language-log.adjacentLines', 10) expect(getFilteredLines()).toBe "" logView.filterBuffer.setText 'f' atom.config.set('language-log.adjacentLines', 1) expect(getFilteredLines()).toBe "0123" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "012" describe "show timestamps", -> it "shows timestamp start and timestamp end", -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setText """ 11-13-15 05:51:46.949: D/dalvikvm(159): GC_FOR_ALLOC freed 104K, 6% free 11-13-15 05:51:52.279: D/NDK_DEBUG(1359): RUN APPLICATION 11-13-15 05:51:52.379: I/DEBUG(5441): fingerprint: 'generic/sdk/generic' """ logView.textEditor.setGrammar(grammar) waitsFor -> logView.timestampEnd.text() != '' runs -> expect(logView.timestampStart.text()).toBe '13-11-2015 05:51:46' expect(logView.timestampEnd.text()).toBe '13-11-2015 05:51:52' describe "timestamp extraction", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "ignores invalid timestamps", -> logView.textEditor.setText("WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("1234 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("123.456 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 it "parses small timestamps", -> logView.textEditor.setText("12-13 1:01 WARNING: this") time = moment("12/13 01:01:00.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses android timestamps", -> logView.textEditor.setText("11-13 05:51:52.279: I/NDK_DEBUG(1359): C") time = moment("11/13 05:51:52.279").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText('02-12 17:25:47.614 2335 26149 D WebSocketC') time = moment("02/12 17:25:47.614").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses iOS timestamps", -> logView.textEditor.setText("[2015-09-17 16:37:57 CEST] <main> INFO") time = moment("2015/09/17 16:37:57.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses idea timestamps", -> logView.textEditor.setText("2014-12-11 14:00:36,047 [ 200232]") time = moment("2014/12/11 14:00:36.047") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apache timestamps", -> logView.textEditor.setText("64.242.88.10 - - [07/Mar/2004:16:45:56 -0800] details") time = moment("2004/03/07 16:45:56.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("[11/Dec/2004:16:24:16] GET /twiki/bin/view/M") time = moment("2004/12/11 16:24:16.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses nabto timestamps", -> logView.textEditor.setText("141121-14:00:26.160 {00007fff7463f300} [AUTOMATLST,debug]") time = moment("2014/11/21 14:00:26.160") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses adobe timestamps", -> logView.textEditor.setText("04/25/15 14:51:34:414 | [INFO] | | OOBE | D") time = moment("2015/04/25 14:51:34.414") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses facetime timestamps", -> logView.textEditor.setText("2015-04-16 14:44:00 +0200 [FaceTimeServiceSe") time = moment("2015/04/16 14:44:00.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses google timestamps", -> logView.textEditor.setText("2015-03-11 21:07:03.094 GoogleSoftwareUpdate") time = moment("2015/03/11 21:07:03.094") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses vmware timestamps", -> logView.textEditor.setText("2015-04-23T13:58:41.657+01:00| VMware Fusio") time = moment("2015/04/23 13:58:41.657") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses auth timestamps", -> logView.textEditor.setText("Apr 28 08:46:03 (72.84) AuthenticationAllowe") time = moment("04/28 08:46:03.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apple timestamps", -> logView.textEditor.setText("Oct 21 09:12:33 Random-MacBook-Pro.local sto") time = moment("10/21 09:12:33.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("Mon Dec 30 15:19:10.047 <airportd[78]> _doAu") time = moment("12/30 15:19:10.047").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses ppp timestamps", -> logView.textEditor.setText("Thu Oct 9 11:52:14 2014 : IPSec connection ") time = moment("2014/10/09 11:52:14.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses windows cbs timestamps", -> logView.textEditor.setText("2015-08-14 05:50:12, Info CBS") time = moment("2015/08/14 05:50:12.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses mail server timestamps", -> logView.textEditor.setText("2008-11-08 06:35:41.724563500 26375 logging:") time = moment("2008/11/08 06:35:41.724") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time
63141
path = require 'path' {TextBuffer} = require 'atom' moment = require 'moment' LogView = require '../lib/log-view' describe "LogView", -> {logView, logFilter, text} = [] # Atom marks the line over a fold and folded # and the first line doesn't really fold getFoldedLines = -> count = logView.textEditor.getLineCount() - 1 i for i in [0..count] when logView.textEditor.isFoldedAtBufferRow(i) getFilteredLines = -> logFilter.results.text.join('') beforeEach -> text = "12:34 INFO: 1\n12:34 INFO: 2\n12:34 DEBUG: 3" buffer = new TextBuffer(text) editor = atom.workspace.buildTextEditor({buffer}) logView = new LogView(editor) logFilter = logView.logFilter atom.project.setPaths [path.join(__dirname, 'fixtures')] describe "view", -> it "has basic elements in view", -> expect(logView.settings).toBeDefined() expect(logView.find('.input-block')).toBeDefined() expect(logView.find('.btn-group-level')).toBeDefined() expect(logView.find('.descriptionLabel')).toBeDefined() describe "filter log text", -> it "filters simple text", -> expect(logView.textEditor.getText()).toEqual text expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter 'INFO' # TODO: Fails because it marks the line above folded as folded also!!! #expect(getFoldedLines()).toEqual [2] expect(logFilter.getFilteredLines()).toEqual [2] it "can filter out no lines", -> expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter '12:34' expect(logFilter.getFilteredLines()).toHaveLength 0 it "can filter out all lines", -> logFilter.performTextFilter 'XXX' expect(logFilter.getFilteredLines()).toEqual [0,1,2] it "accepts advanced regex expressions", -> logFilter.performTextFilter "\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [0,1] it "fetches the currently set filter", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "works with advanced regex filters", -> logView.filterBuffer.setText 'INFO{1}.*' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "shows error message on invalid regex", -> logView.filterBuffer.setText '*INFO' expect(atom.notifications.getNotifications()).toHaveLength 0 logView.filterButton.click() expect(atom.notifications.getNotifications()).toHaveLength 1 it "removes filter when no input", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logView.filterBuffer.setText '' logView.filterBuffer.emitter.emit('did-stop-changing') expect(logFilter.getFilteredLines()).toEqual [] it "can can invert the filter", -> logFilter.performTextFilter '!INFO' expect(logFilter.getFilteredLines()).toEqual [0,1] it "inverts with advanced regex filters", -> logFilter.performTextFilter "!\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [2] describe "filter log levels", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "filters and folds log level lines", -> logView.levelVerboseButton.click() expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [0,1] expect(logFilter.getFilteredLines()).toHaveLength 2 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [0,1,2] expect(logFilter.getFilteredLines()).toHaveLength 3 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [1,2] expect(logFilter.getFilteredLines()).toHaveLength 1 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [] expect(logFilter.getFilteredLines()).toHaveLength 0 it "gets list of scopes from button state", -> logView.updateButtons() expect(logView.getFilterScopes()).toHaveLength 0 logView.levelVerboseButton.click() expect(logView.getFilterScopes()).toHaveLength 1 logView.levelInfoButton.click() logView.levelDebugButton.click() logView.levelErrorButton.click() logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 5 logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 4 describe "all filters", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "can handle both level and text filters", -> logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logFilter.performTextFilter "INFO: 2" expect(logFilter.getFilteredLines()).toEqual [0,2] logFilter.performTextFilter "" expect(logFilter.getFilteredLines()).toEqual [2] logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [] describe "show description label", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "shows total lines and filtered lines", -> expect(logView.find('.description')[0].innerHTML).toBe "Showing 3 log lines" logView.levelDebugButton.click() expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 of 3 log lines" it "updates on file changes", -> logView.textEditor.deleteLine(0) advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 log lines" logView.textEditor.deleteLine(0) logView.levelDebugButton.click() advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 0 of 1 log lines" describe "log tailing", -> it "does not tail by default", -> pos = logView.textEditor.getCursorBufferPosition() logView.textEditor.buffer.append('\nNew log line') expect(logView.tailing).toBe false advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe false newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).toEqual pos it "can tail on log changes", -> atom.config.set('language-log.tail', true) pos = logView.textEditor.getCursorBufferPosition() expect(logView.tailing).toBe false logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).not.toEqual pos logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true expect(logView.textEditor.getCursorBufferPosition()).not.toEqual pos expect(logView.textEditor.getCursorBufferPosition()).not.toEqual newPos it "handles tailing destroyed tabs", -> atom.config.set('language-log.tail', true) logView.textEditor.destroy() logView.tail() expect(logView.textEditor.isDestroyed()).toBe true describe "adjacentLines", -> beforeEach -> logView.textEditor.setText "a\nb\nc\nd\ne\nf\ng" it "shows adjacent lines", -> logView.filterBuffer.setText 'd' atom.config.set('language-log.adjacentLines', 0) expect(logFilter.getFilteredLines()).toHaveLength 6 expect(getFilteredLines()).toBe "012456" atom.config.set('language-log.adjacentLines', 1) expect(logFilter.getFilteredLines()).toHaveLength 4 expect(getFilteredLines()).toBe "0156" it "handles out of bounds adjacent lines", -> logView.filterBuffer.setText 'a' atom.config.set('language-log.adjacentLines', 0) expect(getFilteredLines()).toBe "123456" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "3456" atom.config.set('language-log.adjacentLines', 10) expect(getFilteredLines()).toBe "" logView.filterBuffer.setText 'f' atom.config.set('language-log.adjacentLines', 1) expect(getFilteredLines()).toBe "0123" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "012" describe "show timestamps", -> it "shows timestamp start and timestamp end", -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setText """ 11-13-15 05:51:46.949: D/dalvikvm(159): GC_FOR_ALLOC freed 104K, 6% free 11-13-15 05:51:52.279: D/NDK_DEBUG(1359): RUN APPLICATION 11-13-15 05:51:52.379: I/DEBUG(5441): fingerprint: 'generic/sdk/generic' """ logView.textEditor.setGrammar(grammar) waitsFor -> logView.timestampEnd.text() != '' runs -> expect(logView.timestampStart.text()).toBe '13-11-2015 05:51:46' expect(logView.timestampEnd.text()).toBe '13-11-2015 05:51:52' describe "timestamp extraction", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "ignores invalid timestamps", -> logView.textEditor.setText("WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("1234 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("123.456 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 it "parses small timestamps", -> logView.textEditor.setText("12-13 1:01 WARNING: this") time = moment("12/13 01:01:00.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses android timestamps", -> logView.textEditor.setText("11-13 05:51:52.279: I/NDK_DEBUG(1359): C") time = moment("11/13 05:51:52.279").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText('02-12 17:25:47.614 2335 26149 D WebSocketC') time = moment("02/12 17:25:47.614").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses iOS timestamps", -> logView.textEditor.setText("[2015-09-17 16:37:57 CEST] <main> INFO") time = moment("2015/09/17 16:37:57.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses idea timestamps", -> logView.textEditor.setText("2014-12-11 14:00:36,047 [ 200232]") time = moment("2014/12/11 14:00:36.047") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apache timestamps", -> logView.textEditor.setText("172.16.17.32 - - [07/Mar/2004:16:45:56 -0800] details") time = moment("2004/03/07 16:45:56.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("[11/Dec/2004:16:24:16] GET /twiki/bin/view/M") time = moment("2004/12/11 16:24:16.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses nabto timestamps", -> logView.textEditor.setText("141121-14:00:26.160 {00007fff7463f300} [AUTOMATLST,debug]") time = moment("2014/11/21 14:00:26.160") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses adobe timestamps", -> logView.textEditor.setText("04/25/15 14:51:34:414 | [INFO] | | OOBE | D") time = moment("2015/04/25 14:51:34.414") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses facetime timestamps", -> logView.textEditor.setText("2015-04-16 14:44:00 +0200 [FaceTimeServiceSe") time = moment("2015/04/16 14:44:00.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses google timestamps", -> logView.textEditor.setText("2015-03-11 21:07:03.094 GoogleSoftwareUpdate") time = moment("2015/03/11 21:07:03.094") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses vmware timestamps", -> logView.textEditor.setText("2015-04-23T13:58:41.657+01:00| VMware Fusio") time = moment("2015/04/23 13:58:41.657") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses auth timestamps", -> logView.textEditor.setText("Apr 28 08:46:03 (72.84) AuthenticationAllowe") time = moment("04/28 08:46:03.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apple timestamps", -> logView.textEditor.setText("Oct 21 09:12:33 Random-MacBook-Pro.local sto") time = moment("10/21 09:12:33.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("Mon Dec 30 15:19:10.047 <airportd[78]> _doAu") time = moment("12/30 15:19:10.047").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses ppp timestamps", -> logView.textEditor.setText("Thu Oct 9 11:52:14 2014 : IPSec connection ") time = moment("2014/10/09 11:52:14.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses windows cbs timestamps", -> logView.textEditor.setText("2015-08-14 05:50:12, Info CBS") time = moment("2015/08/14 05:50:12.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses mail server timestamps", -> logView.textEditor.setText("2008-11-08 06:35:41.724563500 26375 logging:") time = moment("2008/11/08 06:35:41.724") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time
true
path = require 'path' {TextBuffer} = require 'atom' moment = require 'moment' LogView = require '../lib/log-view' describe "LogView", -> {logView, logFilter, text} = [] # Atom marks the line over a fold and folded # and the first line doesn't really fold getFoldedLines = -> count = logView.textEditor.getLineCount() - 1 i for i in [0..count] when logView.textEditor.isFoldedAtBufferRow(i) getFilteredLines = -> logFilter.results.text.join('') beforeEach -> text = "12:34 INFO: 1\n12:34 INFO: 2\n12:34 DEBUG: 3" buffer = new TextBuffer(text) editor = atom.workspace.buildTextEditor({buffer}) logView = new LogView(editor) logFilter = logView.logFilter atom.project.setPaths [path.join(__dirname, 'fixtures')] describe "view", -> it "has basic elements in view", -> expect(logView.settings).toBeDefined() expect(logView.find('.input-block')).toBeDefined() expect(logView.find('.btn-group-level')).toBeDefined() expect(logView.find('.descriptionLabel')).toBeDefined() describe "filter log text", -> it "filters simple text", -> expect(logView.textEditor.getText()).toEqual text expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter 'INFO' # TODO: Fails because it marks the line above folded as folded also!!! #expect(getFoldedLines()).toEqual [2] expect(logFilter.getFilteredLines()).toEqual [2] it "can filter out no lines", -> expect(logFilter.getFilteredLines()).toHaveLength 0 logFilter.performTextFilter '12:34' expect(logFilter.getFilteredLines()).toHaveLength 0 it "can filter out all lines", -> logFilter.performTextFilter 'XXX' expect(logFilter.getFilteredLines()).toEqual [0,1,2] it "accepts advanced regex expressions", -> logFilter.performTextFilter "\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [0,1] it "fetches the currently set filter", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "works with advanced regex filters", -> logView.filterBuffer.setText 'INFO{1}.*' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] it "shows error message on invalid regex", -> logView.filterBuffer.setText '*INFO' expect(atom.notifications.getNotifications()).toHaveLength 0 logView.filterButton.click() expect(atom.notifications.getNotifications()).toHaveLength 1 it "removes filter when no input", -> logView.filterBuffer.setText 'INFO' logView.filterButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logView.filterBuffer.setText '' logView.filterBuffer.emitter.emit('did-stop-changing') expect(logFilter.getFilteredLines()).toEqual [] it "can can invert the filter", -> logFilter.performTextFilter '!INFO' expect(logFilter.getFilteredLines()).toEqual [0,1] it "inverts with advanced regex filters", -> logFilter.performTextFilter "!\\d{2}:[0-9]{2}\\sD" expect(logFilter.getFilteredLines()).toEqual [2] describe "filter log levels", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "filters and folds log level lines", -> logView.levelVerboseButton.click() expect(logView.textEditor.getMarkers()).toHaveLength 0 expect(getFoldedLines()).toHaveLength 0 expect(logFilter.getFilteredLines()).toHaveLength 0 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [0,1] expect(logFilter.getFilteredLines()).toHaveLength 2 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [0,1,2] expect(logFilter.getFilteredLines()).toHaveLength 3 logView.levelInfoButton.click() expect(getFoldedLines()).toEqual [1,2] expect(logFilter.getFilteredLines()).toHaveLength 1 logView.levelDebugButton.click() expect(getFoldedLines()).toEqual [] expect(logFilter.getFilteredLines()).toHaveLength 0 it "gets list of scopes from button state", -> logView.updateButtons() expect(logView.getFilterScopes()).toHaveLength 0 logView.levelVerboseButton.click() expect(logView.getFilterScopes()).toHaveLength 1 logView.levelInfoButton.click() logView.levelDebugButton.click() logView.levelErrorButton.click() logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 5 logView.levelWarningButton.click() expect(logView.getFilterScopes()).toHaveLength 4 describe "all filters", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "can handle both level and text filters", -> logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [2] logFilter.performTextFilter "INFO: 2" expect(logFilter.getFilteredLines()).toEqual [0,2] logFilter.performTextFilter "" expect(logFilter.getFilteredLines()).toEqual [2] logView.levelDebugButton.click() expect(logFilter.getFilteredLines()).toEqual [] describe "show description label", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "shows total lines and filtered lines", -> expect(logView.find('.description')[0].innerHTML).toBe "Showing 3 log lines" logView.levelDebugButton.click() expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 of 3 log lines" it "updates on file changes", -> logView.textEditor.deleteLine(0) advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 2 log lines" logView.textEditor.deleteLine(0) logView.levelDebugButton.click() advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.find('.description')[0].innerHTML).toBe "Showing 0 of 1 log lines" describe "log tailing", -> it "does not tail by default", -> pos = logView.textEditor.getCursorBufferPosition() logView.textEditor.buffer.append('\nNew log line') expect(logView.tailing).toBe false advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe false newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).toEqual pos it "can tail on log changes", -> atom.config.set('language-log.tail', true) pos = logView.textEditor.getCursorBufferPosition() expect(logView.tailing).toBe false logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true newPos = logView.textEditor.getCursorBufferPosition() expect(newPos).not.toEqual pos logView.textEditor.buffer.append('\nNew log line') advanceClock(logView.textEditor.buffer.stoppedChangingDelay) expect(logView.tailing).toBe true expect(logView.textEditor.getCursorBufferPosition()).not.toEqual pos expect(logView.textEditor.getCursorBufferPosition()).not.toEqual newPos it "handles tailing destroyed tabs", -> atom.config.set('language-log.tail', true) logView.textEditor.destroy() logView.tail() expect(logView.textEditor.isDestroyed()).toBe true describe "adjacentLines", -> beforeEach -> logView.textEditor.setText "a\nb\nc\nd\ne\nf\ng" it "shows adjacent lines", -> logView.filterBuffer.setText 'd' atom.config.set('language-log.adjacentLines', 0) expect(logFilter.getFilteredLines()).toHaveLength 6 expect(getFilteredLines()).toBe "012456" atom.config.set('language-log.adjacentLines', 1) expect(logFilter.getFilteredLines()).toHaveLength 4 expect(getFilteredLines()).toBe "0156" it "handles out of bounds adjacent lines", -> logView.filterBuffer.setText 'a' atom.config.set('language-log.adjacentLines', 0) expect(getFilteredLines()).toBe "123456" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "3456" atom.config.set('language-log.adjacentLines', 10) expect(getFilteredLines()).toBe "" logView.filterBuffer.setText 'f' atom.config.set('language-log.adjacentLines', 1) expect(getFilteredLines()).toBe "0123" atom.config.set('language-log.adjacentLines', 2) expect(getFilteredLines()).toBe "012" describe "show timestamps", -> it "shows timestamp start and timestamp end", -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setText """ 11-13-15 05:51:46.949: D/dalvikvm(159): GC_FOR_ALLOC freed 104K, 6% free 11-13-15 05:51:52.279: D/NDK_DEBUG(1359): RUN APPLICATION 11-13-15 05:51:52.379: I/DEBUG(5441): fingerprint: 'generic/sdk/generic' """ logView.textEditor.setGrammar(grammar) waitsFor -> logView.timestampEnd.text() != '' runs -> expect(logView.timestampStart.text()).toBe '13-11-2015 05:51:46' expect(logView.timestampEnd.text()).toBe '13-11-2015 05:51:52' describe "timestamp extraction", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-log') runs -> grammar = atom.grammars.grammarForScopeName('source.log') logView.textEditor.setGrammar(grammar) it "ignores invalid timestamps", -> logView.textEditor.setText("WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("1234 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 logView.textEditor.setText("123.456 WARNING: this") logFilter.performTimestampFilter() expect(logFilter.getFilteredLines()).toHaveLength 0 it "parses small timestamps", -> logView.textEditor.setText("12-13 1:01 WARNING: this") time = moment("12/13 01:01:00.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses android timestamps", -> logView.textEditor.setText("11-13 05:51:52.279: I/NDK_DEBUG(1359): C") time = moment("11/13 05:51:52.279").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText('02-12 17:25:47.614 2335 26149 D WebSocketC') time = moment("02/12 17:25:47.614").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses iOS timestamps", -> logView.textEditor.setText("[2015-09-17 16:37:57 CEST] <main> INFO") time = moment("2015/09/17 16:37:57.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses idea timestamps", -> logView.textEditor.setText("2014-12-11 14:00:36,047 [ 200232]") time = moment("2014/12/11 14:00:36.047") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apache timestamps", -> logView.textEditor.setText("PI:IP_ADDRESS:172.16.17.32END_PI - - [07/Mar/2004:16:45:56 -0800] details") time = moment("2004/03/07 16:45:56.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("[11/Dec/2004:16:24:16] GET /twiki/bin/view/M") time = moment("2004/12/11 16:24:16.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses nabto timestamps", -> logView.textEditor.setText("141121-14:00:26.160 {00007fff7463f300} [AUTOMATLST,debug]") time = moment("2014/11/21 14:00:26.160") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses adobe timestamps", -> logView.textEditor.setText("04/25/15 14:51:34:414 | [INFO] | | OOBE | D") time = moment("2015/04/25 14:51:34.414") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses facetime timestamps", -> logView.textEditor.setText("2015-04-16 14:44:00 +0200 [FaceTimeServiceSe") time = moment("2015/04/16 14:44:00.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses google timestamps", -> logView.textEditor.setText("2015-03-11 21:07:03.094 GoogleSoftwareUpdate") time = moment("2015/03/11 21:07:03.094") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses vmware timestamps", -> logView.textEditor.setText("2015-04-23T13:58:41.657+01:00| VMware Fusio") time = moment("2015/04/23 13:58:41.657") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses auth timestamps", -> logView.textEditor.setText("Apr 28 08:46:03 (72.84) AuthenticationAllowe") time = moment("04/28 08:46:03.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses apple timestamps", -> logView.textEditor.setText("Oct 21 09:12:33 Random-MacBook-Pro.local sto") time = moment("10/21 09:12:33.000").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time logView.textEditor.setText("Mon Dec 30 15:19:10.047 <airportd[78]> _doAu") time = moment("12/30 15:19:10.047").year(moment().year()) logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses ppp timestamps", -> logView.textEditor.setText("Thu Oct 9 11:52:14 2014 : IPSec connection ") time = moment("2014/10/09 11:52:14.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses windows cbs timestamps", -> logView.textEditor.setText("2015-08-14 05:50:12, Info CBS") time = moment("2015/08/14 05:50:12.000") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time it "parses mail server timestamps", -> logView.textEditor.setText("2008-11-08 06:35:41.724563500 26375 logging:") time = moment("2008/11/08 06:35:41.724") logFilter.performTimestampFilter() expect(logFilter.results.times).toHaveLength 1 expect(+logFilter.results.times[0]).toBe +time
[ { "context": "ow, {foo: {bar: {baz: 1}}}\nlogger {user: {first: 'Bill', last: 'Nye'}}\n\nlogger.toggleElapsed()\n\nsecond =", "end": 118, "score": 0.999747633934021, "start": 114, "tag": "NAME", "value": "Bill" }, { "context": ": {baz: 1}}}\nlogger {user: {first: 'Bill', last: 'Nye'}...
sample/test.coffee
TorchlightSoftware/torch
0
logger = require '..' logger.red 'hi' logger.gray 'stuff:'.yellow, {foo: {bar: {baz: 1}}} logger {user: {first: 'Bill', last: 'Nye'}} logger.toggleElapsed() second = -> logger.yellow 'initiate launch sequence' third = -> logger.white 'begin countdown' logger.blue 'clear the area' setTimeout second, 30 setTimeout third, 70
188860
logger = require '..' logger.red 'hi' logger.gray 'stuff:'.yellow, {foo: {bar: {baz: 1}}} logger {user: {first: '<NAME>', last: '<NAME>'}} logger.toggleElapsed() second = -> logger.yellow 'initiate launch sequence' third = -> logger.white 'begin countdown' logger.blue 'clear the area' setTimeout second, 30 setTimeout third, 70
true
logger = require '..' logger.red 'hi' logger.gray 'stuff:'.yellow, {foo: {bar: {baz: 1}}} logger {user: {first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'}} logger.toggleElapsed() second = -> logger.yellow 'initiate launch sequence' third = -> logger.white 'begin countdown' logger.blue 'clear the area' setTimeout second, 30 setTimeout third, 70
[ { "context": "goods = [\n {\n name: \"I Heart Denver\"\n address: \"500 16th Street\"\n coordinates:\n", "end": 39, "score": 0.9974753856658936, "start": 25, "tag": "NAME", "value": "I Heart Denver" }, { "context": "en: \"1000\"\n close: \"2000\"\n }\n {\n name: \...
source/assets/javascripts/picks/goods.coffee
isabella232/summit-guide-2015
1
goods = [ { name: "I Heart Denver" address: "500 16th Street" coordinates: lat: 39.742870 long: -104.990508 hours: open: "1000" close: "2000" } { name: "Little Man Ice Cream" address: "2620 16th St" coordinates: lat: 39.7594564 long: -105.011112 hours: open: "1100" close: "2400" recommendation: who: "rachel" why: "Best ice cream in town. Expect a long line." } { name: "Cigars on 6th" address: "707 E 6th Ave" coordinates: lat: 39.725802 long: -104.978427 hours: open: "1000" close: "1700" recommendation: who: "sean" why: "Good selection and a really good barber too." } { name: "Topo" address: "2500 Larimer St" coordinates: lat: 39.7577094 long: -104.9861642 hours: open: "1100" close: "1800" recommendation: who: "rachel" why: "This place will make you want to go camping! Hip, Colorado-style clothing, bags, and accessories. (Plus it’s a shipping container!)" } ] localStorage.setItem("goods", JSON.stringify(goods))
78297
goods = [ { name: "<NAME>" address: "500 16th Street" coordinates: lat: 39.742870 long: -104.990508 hours: open: "1000" close: "2000" } { name: "<NAME>" address: "2620 16th St" coordinates: lat: 39.7594564 long: -105.011112 hours: open: "1100" close: "2400" recommendation: who: "<NAME>" why: "Best ice cream in town. Expect a long line." } { name: "<NAME>" address: "707 E 6th Ave" coordinates: lat: 39.725802 long: -104.978427 hours: open: "1000" close: "1700" recommendation: who: "<NAME>" why: "Good selection and a really good barber too." } { name: "<NAME>" address: "2500 Larimer St" coordinates: lat: 39.7577094 long: -104.9861642 hours: open: "1100" close: "1800" recommendation: who: "<NAME>" why: "This place will make you want to go camping! Hip, Colorado-style clothing, bags, and accessories. (Plus it’s a shipping container!)" } ] localStorage.setItem("goods", JSON.stringify(goods))
true
goods = [ { name: "PI:NAME:<NAME>END_PI" address: "500 16th Street" coordinates: lat: 39.742870 long: -104.990508 hours: open: "1000" close: "2000" } { name: "PI:NAME:<NAME>END_PI" address: "2620 16th St" coordinates: lat: 39.7594564 long: -105.011112 hours: open: "1100" close: "2400" recommendation: who: "PI:NAME:<NAME>END_PI" why: "Best ice cream in town. Expect a long line." } { name: "PI:NAME:<NAME>END_PI" address: "707 E 6th Ave" coordinates: lat: 39.725802 long: -104.978427 hours: open: "1000" close: "1700" recommendation: who: "PI:NAME:<NAME>END_PI" why: "Good selection and a really good barber too." } { name: "PI:NAME:<NAME>END_PI" address: "2500 Larimer St" coordinates: lat: 39.7577094 long: -104.9861642 hours: open: "1100" close: "1800" recommendation: who: "PI:NAME:<NAME>END_PI" why: "This place will make you want to go camping! Hip, Colorado-style clothing, bags, and accessories. (Plus it’s a shipping container!)" } ] localStorage.setItem("goods", JSON.stringify(goods))
[ { "context": "\nP.svc.oaworks.templates = _key: 'name', _sheet: '16Qm8n3Rmx3QyttFpSGj81_7T6ehfLAtYRSvmDf3pAzg/1', _hide: true\n\nP.svc.oaworks.bug = () ->\n if @pa", "end": 664, "score": 0.8079260587692261, "start": 618, "tag": "KEY", "value": "16Qm8n3Rmx3QyttFpSGj81_7T6ehfLAtYRSvmDf3pAzg/1...
worker/src/svc/oaworks/api.coffee
oaworks/paradigm
1
try S.svc.oaworks = JSON.parse SECRETS_OAWORKS catch S.svc.oaworks = {} P.svc.oaworks = () -> if JSON.stringify(@params) isnt '{}' return status: 404 else rts = await @subroutes 'svc.oaworks' rts.splice(rts.indexOf(hd), 1) for hd in ['bug', 'blacklist', 'deposits', 'journal', 'journal/load'] return name: 'OA.Works Paradigm API' version: @S.version base: if @S.dev then @base else undefined built: if @S.dev then @S.built else undefined user: if @user?.email then @user.email else undefined routes: rts P.svc.oaworks.templates = _key: 'name', _sheet: '16Qm8n3Rmx3QyttFpSGj81_7T6ehfLAtYRSvmDf3pAzg/1', _hide: true P.svc.oaworks.bug = () -> if @params.contact # verify humanity return '' else whoto = ['help@oa.works'] text = '' for k of @params text += k + ': ' + JSON.stringify(@params[k], undefined, 2) + '\n\n' text = await @tdm.clean text subject = '[OAB forms]' if @params?.form is 'uninstall' # wrong bug general other subject += ' Uninstall notice' else if @params?.form is 'wrong' subject += ' Wrong article' else if @params?.form is 'bug' subject += ' Bug' else if @params?.form is 'general' subject += ' General' else subject += ' Other' subject += ' ' + Date.now() if @params?.form in ['wrong','uninstall'] whoto.push 'help@openaccessbutton.org' @waitUntil @mail service: 'openaccessbutton' from: 'help@openaccessbutton.org' to: whoto subject: subject text: text lc = (if @S.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks' return status: 302 headers: 'Content-Type': 'text/plain', 'Location': lc body: lc P.svc.oaworks.blacklist = (url) -> url ?= @params.url url = url.toString() if typeof url is 'number' return false if url? and (url.length < 4 or url.indexOf('.') is -1) blacklist = [] blacklist.push(i.url.toLowerCase()) for i in await @src.google.sheets @S.svc.oaworks?.google?.sheets?.blacklist if url if not url.startsWith('http') and url.includes ' ' return false # sometimes things like article titles get sent here, no point checking them on the blacklist else for b in blacklist return true if url.includes b.toLowerCase() return false else return blacklist
90618
try S.svc.oaworks = JSON.parse SECRETS_OAWORKS catch S.svc.oaworks = {} P.svc.oaworks = () -> if JSON.stringify(@params) isnt '{}' return status: 404 else rts = await @subroutes 'svc.oaworks' rts.splice(rts.indexOf(hd), 1) for hd in ['bug', 'blacklist', 'deposits', 'journal', 'journal/load'] return name: 'OA.Works Paradigm API' version: @S.version base: if @S.dev then @base else undefined built: if @S.dev then @S.built else undefined user: if @user?.email then @user.email else undefined routes: rts P.svc.oaworks.templates = _key: 'name', _sheet: '<KEY>', _hide: true P.svc.oaworks.bug = () -> if @params.contact # verify humanity return '' else whoto = ['<EMAIL>'] text = '' for k of @params text += k + ': ' + JSON.stringify(@params[k], undefined, 2) + '\n\n' text = await @tdm.clean text subject = '[OAB forms]' if @params?.form is 'uninstall' # wrong bug general other subject += ' Uninstall notice' else if @params?.form is 'wrong' subject += ' Wrong article' else if @params?.form is 'bug' subject += ' Bug' else if @params?.form is 'general' subject += ' General' else subject += ' Other' subject += ' ' + Date.now() if @params?.form in ['wrong','uninstall'] whoto.push '<EMAIL>' @waitUntil @mail service: 'openaccessbutton' from: '<EMAIL>' to: whoto subject: subject text: text lc = (if @S.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks' return status: 302 headers: 'Content-Type': 'text/plain', 'Location': lc body: lc P.svc.oaworks.blacklist = (url) -> url ?= @params.url url = url.toString() if typeof url is 'number' return false if url? and (url.length < 4 or url.indexOf('.') is -1) blacklist = [] blacklist.push(i.url.toLowerCase()) for i in await @src.google.sheets @S.svc.oaworks?.google?.sheets?.blacklist if url if not url.startsWith('http') and url.includes ' ' return false # sometimes things like article titles get sent here, no point checking them on the blacklist else for b in blacklist return true if url.includes b.toLowerCase() return false else return blacklist
true
try S.svc.oaworks = JSON.parse SECRETS_OAWORKS catch S.svc.oaworks = {} P.svc.oaworks = () -> if JSON.stringify(@params) isnt '{}' return status: 404 else rts = await @subroutes 'svc.oaworks' rts.splice(rts.indexOf(hd), 1) for hd in ['bug', 'blacklist', 'deposits', 'journal', 'journal/load'] return name: 'OA.Works Paradigm API' version: @S.version base: if @S.dev then @base else undefined built: if @S.dev then @S.built else undefined user: if @user?.email then @user.email else undefined routes: rts P.svc.oaworks.templates = _key: 'name', _sheet: 'PI:KEY:<KEY>END_PI', _hide: true P.svc.oaworks.bug = () -> if @params.contact # verify humanity return '' else whoto = ['PI:EMAIL:<EMAIL>END_PI'] text = '' for k of @params text += k + ': ' + JSON.stringify(@params[k], undefined, 2) + '\n\n' text = await @tdm.clean text subject = '[OAB forms]' if @params?.form is 'uninstall' # wrong bug general other subject += ' Uninstall notice' else if @params?.form is 'wrong' subject += ' Wrong article' else if @params?.form is 'bug' subject += ' Bug' else if @params?.form is 'general' subject += ' General' else subject += ' Other' subject += ' ' + Date.now() if @params?.form in ['wrong','uninstall'] whoto.push 'PI:EMAIL:<EMAIL>END_PI' @waitUntil @mail service: 'openaccessbutton' from: 'PI:EMAIL:<EMAIL>END_PI' to: whoto subject: subject text: text lc = (if @S.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks' return status: 302 headers: 'Content-Type': 'text/plain', 'Location': lc body: lc P.svc.oaworks.blacklist = (url) -> url ?= @params.url url = url.toString() if typeof url is 'number' return false if url? and (url.length < 4 or url.indexOf('.') is -1) blacklist = [] blacklist.push(i.url.toLowerCase()) for i in await @src.google.sheets @S.svc.oaworks?.google?.sheets?.blacklist if url if not url.startsWith('http') and url.includes ' ' return false # sometimes things like article titles get sent here, no point checking them on the blacklist else for b in blacklist return true if url.includes b.toLowerCase() return false else return blacklist
[ { "context": "ningGambitRemoveRandomArtifact\"\n\n\t@modifierName: \"Opening Gambit\"\n\t@description: \"Destroy a random enemy artifact\"", "end": 421, "score": 0.8976187705993652, "start": 407, "tag": "NAME", "value": "Opening Gambit" } ]
app/sdk/modifiers/modifierOpeningGambitRemoveRandomArtifact.coffee
willroberts/duelyst
5
ModifierOpeningGambit = require './modifierOpeningGambit' RemoveRandomArtifactAction = require 'app/sdk/actions/removeRandomArtifactAction' UtilsGameSession = require 'app/common/utils/utils_game_session' class ModifierOpeningGambitRemoveRandomArtifact extends ModifierOpeningGambit type: "ModifierOpeningGambitRemoveRandomArtifact" @type: "ModifierOpeningGambitRemoveRandomArtifact" @modifierName: "Opening Gambit" @description: "Destroy a random enemy artifact" onOpeningGambit: () -> general = @getCard().getGameSession().getGeneralForOpponentOfPlayerId(@getCard().getOwnerId()) modifiersByArtifact = general.getArtifactModifiersGroupedByArtifactCard() # if enemy General has at least one artifact on, then remove 1 artifact at random if modifiersByArtifact.length > 0 removeArtifactAction = new RemoveRandomArtifactAction(@getGameSession()) removeArtifactAction.setTarget(general) @getGameSession().executeAction(removeArtifactAction) module.exports = ModifierOpeningGambitRemoveRandomArtifact
74040
ModifierOpeningGambit = require './modifierOpeningGambit' RemoveRandomArtifactAction = require 'app/sdk/actions/removeRandomArtifactAction' UtilsGameSession = require 'app/common/utils/utils_game_session' class ModifierOpeningGambitRemoveRandomArtifact extends ModifierOpeningGambit type: "ModifierOpeningGambitRemoveRandomArtifact" @type: "ModifierOpeningGambitRemoveRandomArtifact" @modifierName: "<NAME>" @description: "Destroy a random enemy artifact" onOpeningGambit: () -> general = @getCard().getGameSession().getGeneralForOpponentOfPlayerId(@getCard().getOwnerId()) modifiersByArtifact = general.getArtifactModifiersGroupedByArtifactCard() # if enemy General has at least one artifact on, then remove 1 artifact at random if modifiersByArtifact.length > 0 removeArtifactAction = new RemoveRandomArtifactAction(@getGameSession()) removeArtifactAction.setTarget(general) @getGameSession().executeAction(removeArtifactAction) module.exports = ModifierOpeningGambitRemoveRandomArtifact
true
ModifierOpeningGambit = require './modifierOpeningGambit' RemoveRandomArtifactAction = require 'app/sdk/actions/removeRandomArtifactAction' UtilsGameSession = require 'app/common/utils/utils_game_session' class ModifierOpeningGambitRemoveRandomArtifact extends ModifierOpeningGambit type: "ModifierOpeningGambitRemoveRandomArtifact" @type: "ModifierOpeningGambitRemoveRandomArtifact" @modifierName: "PI:NAME:<NAME>END_PI" @description: "Destroy a random enemy artifact" onOpeningGambit: () -> general = @getCard().getGameSession().getGeneralForOpponentOfPlayerId(@getCard().getOwnerId()) modifiersByArtifact = general.getArtifactModifiersGroupedByArtifactCard() # if enemy General has at least one artifact on, then remove 1 artifact at random if modifiersByArtifact.length > 0 removeArtifactAction = new RemoveRandomArtifactAction(@getGameSession()) removeArtifactAction.setTarget(general) @getGameSession().executeAction(removeArtifactAction) module.exports = ModifierOpeningGambitRemoveRandomArtifact
[ { "context": "rStore\n find: (email) ->\n return if email is 'info@grokbit.com' then @createInstance() else null\n\n findByKey: (", "end": 109, "score": 0.9999009966850281, "start": 93, "tag": "EMAIL", "value": "info@grokbit.com" }, { "context": "null\n\n findByKey: (key) ->\n ...
src/services/userStore.coffee
marinoscar/NodeExpressAuth
0
User = require('../models/user') class UserStore find: (email) -> return if email is 'info@grokbit.com' then @createInstance() else null findByKey: (key) -> return if key is 'info@grokbit.com' then @createInstance() else null createInstance: () -> validUser = new User() validUser.email = 'info@grokbit.com' validUser.providerKey = validUser.email validUser.password = 'mypassword' validUser.name = 'Grokbit' return validUser module.exports = UserStore
179861
User = require('../models/user') class UserStore find: (email) -> return if email is '<EMAIL>' then @createInstance() else null findByKey: (key) -> return if key is '<EMAIL>' then @createInstance() else null createInstance: () -> validUser = new User() validUser.email = '<EMAIL>' validUser.providerKey = validUser.email validUser.password = '<PASSWORD>' validUser.name = 'Grokbit' return validUser module.exports = UserStore
true
User = require('../models/user') class UserStore find: (email) -> return if email is 'PI:EMAIL:<EMAIL>END_PI' then @createInstance() else null findByKey: (key) -> return if key is 'PI:EMAIL:<EMAIL>END_PI' then @createInstance() else null createInstance: () -> validUser = new User() validUser.email = 'PI:EMAIL:<EMAIL>END_PI' validUser.providerKey = validUser.email validUser.password = 'PI:PASSWORD:<PASSWORD>END_PI' validUser.name = 'Grokbit' return validUser module.exports = UserStore
[ { "context": "**\n# JSTextField - One line text object\n# Coded by Hajime Oh-yake 2013.03.25\n#*************************************", "end": 105, "score": 0.999882161617279, "start": 91, "tag": "NAME", "value": "Hajime Oh-yake" } ]
JSKit/04_JSTextField.coffee
digitarhythm/codeJS
0
#***************************************** # JSTextField - One line text object # Coded by Hajime Oh-yake 2013.03.25 #***************************************** class JSTextField extends JSControl constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "" @_editable = true @_action = null @_focus = false @_placeholder = "" @_formtype = 'text' getText:-> if (@_editable == true) text = $(@_viewSelector+"_text").val() else text = @_text return text setText: (@_text) -> if ($(@_viewSelector+"_text").length) if (@_editable == true) $(@_viewSelector+"_text").val(@_text) else disp = JSEscape(@_text) $(@_viewSelector+"_text").html(disp) setTextSize: (@_textSize) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").css("font-size", @_textSize+"pt") setTextColor: (@_textColor) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> frame.size.width -= 5 frame.origin.x += 2 super(frame) $(@_viewSelector+"_text").width(frame.size.width) $(@_viewSelector+"_text").height(frame.size.height) setPlaceholder:(@_placeholder)-> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").attr("placeholder", @_placeholder) setEditable:(editable)-> if (!$(@_viewSelector).length) @_editable = editable return if (editable == true) # 編集可能モード if (@_editable == true) # モード変更前が編集可能モード if (!$(@_viewSelector+"_text").length) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else @_text = $(@_viewSelector+"_text").val() $(@_viewSelector+"_text").remove() tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else # モード変更前が編集不可モード disp = JSEscape(@_text) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+disp+"'>" x = -2 y = -2 else # 編集不可モード if (@_editable == true) # モード変更前が編集可能モード @_text = $(@_viewSelector+"_text").val() text = JSEscape(@_text) disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" else # モード変更前が編集不可モード if (@_text?) text = JSEscape(@_text) else text = "" disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" x = 0 y = 0 @_editable = editable if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").remove() $(@_viewSelector).append(tag) $(@_viewSelector+"_text").keypress (event)=> if (@action?) @action(event.which) if (@_editable == true) $(@_viewSelector+"_text").unbind("click").bind "click", (event) => event.stopPropagation() $(@_viewSelector+"_text").bind "change", => @_text = $(@_viewSelector+"_text").val() @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) $(@_viewSelector+"_text").css("left", x) $(@_viewSelector+"_text").css("top", y) $(@_viewSelector+"_text").width(@_frame.size.width) $(@_viewSelector+"_text").height(@_frame.size.height) setDidKeyPressEvent:(@action)-> setSecureTextEntry:(flag)-> @_formtype = if (flag) then 'password' else 'text' @setEditable(@_editable) getSecureTextEntry:-> return if (@_formtype == 'password') then true else false setFocus:(@_focus)-> if (!$(@_viewSelector+"_text").length) return if (@_focus == true) $(@_viewSelector+"_text").focus() else $(@_viewSelector+"_text").blur() viewDidAppear: -> super() @setEditable(@_editable) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector+"_text").width(@_frame.size.width) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) @setPlaceholder(@_placeholder) $(@_viewSelector).css("overflow", "")
154802
#***************************************** # JSTextField - One line text object # Coded by <NAME> 2013.03.25 #***************************************** class JSTextField extends JSControl constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "" @_editable = true @_action = null @_focus = false @_placeholder = "" @_formtype = 'text' getText:-> if (@_editable == true) text = $(@_viewSelector+"_text").val() else text = @_text return text setText: (@_text) -> if ($(@_viewSelector+"_text").length) if (@_editable == true) $(@_viewSelector+"_text").val(@_text) else disp = JSEscape(@_text) $(@_viewSelector+"_text").html(disp) setTextSize: (@_textSize) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").css("font-size", @_textSize+"pt") setTextColor: (@_textColor) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> frame.size.width -= 5 frame.origin.x += 2 super(frame) $(@_viewSelector+"_text").width(frame.size.width) $(@_viewSelector+"_text").height(frame.size.height) setPlaceholder:(@_placeholder)-> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").attr("placeholder", @_placeholder) setEditable:(editable)-> if (!$(@_viewSelector).length) @_editable = editable return if (editable == true) # 編集可能モード if (@_editable == true) # モード変更前が編集可能モード if (!$(@_viewSelector+"_text").length) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else @_text = $(@_viewSelector+"_text").val() $(@_viewSelector+"_text").remove() tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else # モード変更前が編集不可モード disp = JSEscape(@_text) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+disp+"'>" x = -2 y = -2 else # 編集不可モード if (@_editable == true) # モード変更前が編集可能モード @_text = $(@_viewSelector+"_text").val() text = JSEscape(@_text) disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" else # モード変更前が編集不可モード if (@_text?) text = JSEscape(@_text) else text = "" disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" x = 0 y = 0 @_editable = editable if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").remove() $(@_viewSelector).append(tag) $(@_viewSelector+"_text").keypress (event)=> if (@action?) @action(event.which) if (@_editable == true) $(@_viewSelector+"_text").unbind("click").bind "click", (event) => event.stopPropagation() $(@_viewSelector+"_text").bind "change", => @_text = $(@_viewSelector+"_text").val() @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) $(@_viewSelector+"_text").css("left", x) $(@_viewSelector+"_text").css("top", y) $(@_viewSelector+"_text").width(@_frame.size.width) $(@_viewSelector+"_text").height(@_frame.size.height) setDidKeyPressEvent:(@action)-> setSecureTextEntry:(flag)-> @_formtype = if (flag) then 'password' else 'text' @setEditable(@_editable) getSecureTextEntry:-> return if (@_formtype == 'password') then true else false setFocus:(@_focus)-> if (!$(@_viewSelector+"_text").length) return if (@_focus == true) $(@_viewSelector+"_text").focus() else $(@_viewSelector+"_text").blur() viewDidAppear: -> super() @setEditable(@_editable) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector+"_text").width(@_frame.size.width) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) @setPlaceholder(@_placeholder) $(@_viewSelector).css("overflow", "")
true
#***************************************** # JSTextField - One line text object # Coded by PI:NAME:<NAME>END_PI 2013.03.25 #***************************************** class JSTextField extends JSControl constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "" @_editable = true @_action = null @_focus = false @_placeholder = "" @_formtype = 'text' getText:-> if (@_editable == true) text = $(@_viewSelector+"_text").val() else text = @_text return text setText: (@_text) -> if ($(@_viewSelector+"_text").length) if (@_editable == true) $(@_viewSelector+"_text").val(@_text) else disp = JSEscape(@_text) $(@_viewSelector+"_text").html(disp) setTextSize: (@_textSize) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").css("font-size", @_textSize+"pt") setTextColor: (@_textColor) -> if ($(@_viewSelector+"_text").length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> frame.size.width -= 5 frame.origin.x += 2 super(frame) $(@_viewSelector+"_text").width(frame.size.width) $(@_viewSelector+"_text").height(frame.size.height) setPlaceholder:(@_placeholder)-> if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").attr("placeholder", @_placeholder) setEditable:(editable)-> if (!$(@_viewSelector).length) @_editable = editable return if (editable == true) # 編集可能モード if (@_editable == true) # モード変更前が編集可能モード if (!$(@_viewSelector+"_text").length) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else @_text = $(@_viewSelector+"_text").val() $(@_viewSelector+"_text").remove() tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+@_text+"'>" else # モード変更前が編集不可モード disp = JSEscape(@_text) tag = "<input type='"+@_formtype+"' id='"+@_objectID+"_text' style='position:absolute;z-index:1;height:"+@_frame.size.height+"px;' value='"+disp+"'>" x = -2 y = -2 else # 編集不可モード if (@_editable == true) # モード変更前が編集可能モード @_text = $(@_viewSelector+"_text").val() text = JSEscape(@_text) disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" else # モード変更前が編集不可モード if (@_text?) text = JSEscape(@_text) else text = "" disp = text.replace(/\n/g, "<br>") tag = "<div id='"+@_objectID+"_text' style='position:absolute;z-index:1;overflow:hidden;'>"+disp+"</div>" x = 0 y = 0 @_editable = editable if ($(@_viewSelector+"_text").length) $(@_viewSelector+"_text").remove() $(@_viewSelector).append(tag) $(@_viewSelector+"_text").keypress (event)=> if (@action?) @action(event.which) if (@_editable == true) $(@_viewSelector+"_text").unbind("click").bind "click", (event) => event.stopPropagation() $(@_viewSelector+"_text").bind "change", => @_text = $(@_viewSelector+"_text").val() @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) $(@_viewSelector+"_text").css("left", x) $(@_viewSelector+"_text").css("top", y) $(@_viewSelector+"_text").width(@_frame.size.width) $(@_viewSelector+"_text").height(@_frame.size.height) setDidKeyPressEvent:(@action)-> setSecureTextEntry:(flag)-> @_formtype = if (flag) then 'password' else 'text' @setEditable(@_editable) getSecureTextEntry:-> return if (@_formtype == 'password') then true else false setFocus:(@_focus)-> if (!$(@_viewSelector+"_text").length) return if (@_focus == true) $(@_viewSelector+"_text").focus() else $(@_viewSelector+"_text").blur() viewDidAppear: -> super() @setEditable(@_editable) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector+"_text").width(@_frame.size.width) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment) @setPlaceholder(@_placeholder) $(@_viewSelector).css("overflow", "")
[ { "context": "lass\n FIXTURES: [\n {\n id: 1\n name: 'Jungpflanzen'\n isYoung: yes\n }\n {\n id: 2\n ", "end": 340, "score": 0.9997730255126953, "start": 328, "tag": "NAME", "value": "Jungpflanzen" }, { "context": "isYoung: yes\n }\n {\n i...
app/models/quarter.coffee
koenig/moosi
0
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Quarter = DS.Model.extend name: attr 'string' isYoung: attr 'boolean', defaultValue: false positions: hasMany 'position' isPlant: Em.computed.not 'isYoung' Quarter.reopenClass FIXTURES: [ { id: 1 name: 'Jungpflanzen' isYoung: yes } { id: 2 name: 'Hauptlager' isYoung: no } ] `export default Quarter`
217881
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Quarter = DS.Model.extend name: attr 'string' isYoung: attr 'boolean', defaultValue: false positions: hasMany 'position' isPlant: Em.computed.not 'isYoung' Quarter.reopenClass FIXTURES: [ { id: 1 name: '<NAME>' isYoung: yes } { id: 2 name: '<NAME>' isYoung: no } ] `export default Quarter`
true
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Quarter = DS.Model.extend name: attr 'string' isYoung: attr 'boolean', defaultValue: false positions: hasMany 'position' isPlant: Em.computed.not 'isYoung' Quarter.reopenClass FIXTURES: [ { id: 1 name: 'PI:NAME:<NAME>END_PI' isYoung: yes } { id: 2 name: 'PI:NAME:<NAME>END_PI' isYoung: no } ] `export default Quarter`
[ { "context": "@app.component 'modalProfile',\n\n bindings:\n modalIn", "end": 4, "score": 0.5701888799667358, "start": 1, "tag": "EMAIL", "value": "app" } ]
app/assets/javascripts/components/modal_profile.coffee
mthorn/photo-store
0
@app.component 'modalProfile', bindings: modalInstance: '<' template: """ <div class='modal-header'> <h3 class='modal-title'>Profile</h3> </div> <div class='modal-body form form-horizontal'> <div class='form-group'> <label class='control-label col-sm-3' for='email'>Email</label> <div class='col-sm-9' errors='$ctrl.errors.email'> <input class='form-control' id='email' ng-model='$ctrl.view.email' type='email'> </div> </div> <div class='form-group'> <label class='control-label col-sm-3' for='name'>Name</label> <div class='col-sm-9' errors='$ctrl.errors.name'> <input class='form-control' id='name' ng-model='$ctrl.view.name' type='text'> </div> </div> <div class='form-group' ng-if='$ctrl.Library.mine.length &gt; 1'> <label class='control-label col-sm-3' for='default_library_id'>Default Library</label> <div class='col-sm-9' errors='$ctrl.errors.default_library_id'> <select class='form-control' id='default_library_id' ng-model='$ctrl.view.default_library_id' ng-options='lib.id as lib.name for lib in $ctrl.Library.mine' type='text'></select> </div> </div> <div class='form-group' uib-tooltip='The maximum amount of upload data that will be discarded if an upload is paused or a transient error occurs with the storage provider.'> <label class='control-label col-sm-3' for='upload_block_size_mib'>Upload Block Size (MiB)</label> <div class='col-sm-9' errors='$ctrl.errors.upload_block_size_mib'> <input class='form-control' id='upload_block_size_mib' ng-model='$ctrl.view.upload_block_size_mib' type='number'> </div> </div> </div> <div class='modal-footer'> <button busy-click='$ctrl.save()' class='btn btn-primary'>Save</button> <button class='btn btn-default' ng-click='$ctrl.modalInstance.dismiss()'>Cancel</button> </div> """ controller: class extends BaseCtrl @inject 'User' $onInit: -> @user = @User.me @view = new @User @user save: -> @errors = null @view.$update(). then(=> angular.copy(@view, @user)). then(=> @modalInstance.close()). catch((response) => @errors = response.data)
75907
@<EMAIL>.component 'modalProfile', bindings: modalInstance: '<' template: """ <div class='modal-header'> <h3 class='modal-title'>Profile</h3> </div> <div class='modal-body form form-horizontal'> <div class='form-group'> <label class='control-label col-sm-3' for='email'>Email</label> <div class='col-sm-9' errors='$ctrl.errors.email'> <input class='form-control' id='email' ng-model='$ctrl.view.email' type='email'> </div> </div> <div class='form-group'> <label class='control-label col-sm-3' for='name'>Name</label> <div class='col-sm-9' errors='$ctrl.errors.name'> <input class='form-control' id='name' ng-model='$ctrl.view.name' type='text'> </div> </div> <div class='form-group' ng-if='$ctrl.Library.mine.length &gt; 1'> <label class='control-label col-sm-3' for='default_library_id'>Default Library</label> <div class='col-sm-9' errors='$ctrl.errors.default_library_id'> <select class='form-control' id='default_library_id' ng-model='$ctrl.view.default_library_id' ng-options='lib.id as lib.name for lib in $ctrl.Library.mine' type='text'></select> </div> </div> <div class='form-group' uib-tooltip='The maximum amount of upload data that will be discarded if an upload is paused or a transient error occurs with the storage provider.'> <label class='control-label col-sm-3' for='upload_block_size_mib'>Upload Block Size (MiB)</label> <div class='col-sm-9' errors='$ctrl.errors.upload_block_size_mib'> <input class='form-control' id='upload_block_size_mib' ng-model='$ctrl.view.upload_block_size_mib' type='number'> </div> </div> </div> <div class='modal-footer'> <button busy-click='$ctrl.save()' class='btn btn-primary'>Save</button> <button class='btn btn-default' ng-click='$ctrl.modalInstance.dismiss()'>Cancel</button> </div> """ controller: class extends BaseCtrl @inject 'User' $onInit: -> @user = @User.me @view = new @User @user save: -> @errors = null @view.$update(). then(=> angular.copy(@view, @user)). then(=> @modalInstance.close()). catch((response) => @errors = response.data)
true
@PI:EMAIL:<EMAIL>END_PI.component 'modalProfile', bindings: modalInstance: '<' template: """ <div class='modal-header'> <h3 class='modal-title'>Profile</h3> </div> <div class='modal-body form form-horizontal'> <div class='form-group'> <label class='control-label col-sm-3' for='email'>Email</label> <div class='col-sm-9' errors='$ctrl.errors.email'> <input class='form-control' id='email' ng-model='$ctrl.view.email' type='email'> </div> </div> <div class='form-group'> <label class='control-label col-sm-3' for='name'>Name</label> <div class='col-sm-9' errors='$ctrl.errors.name'> <input class='form-control' id='name' ng-model='$ctrl.view.name' type='text'> </div> </div> <div class='form-group' ng-if='$ctrl.Library.mine.length &gt; 1'> <label class='control-label col-sm-3' for='default_library_id'>Default Library</label> <div class='col-sm-9' errors='$ctrl.errors.default_library_id'> <select class='form-control' id='default_library_id' ng-model='$ctrl.view.default_library_id' ng-options='lib.id as lib.name for lib in $ctrl.Library.mine' type='text'></select> </div> </div> <div class='form-group' uib-tooltip='The maximum amount of upload data that will be discarded if an upload is paused or a transient error occurs with the storage provider.'> <label class='control-label col-sm-3' for='upload_block_size_mib'>Upload Block Size (MiB)</label> <div class='col-sm-9' errors='$ctrl.errors.upload_block_size_mib'> <input class='form-control' id='upload_block_size_mib' ng-model='$ctrl.view.upload_block_size_mib' type='number'> </div> </div> </div> <div class='modal-footer'> <button busy-click='$ctrl.save()' class='btn btn-primary'>Save</button> <button class='btn btn-default' ng-click='$ctrl.modalInstance.dismiss()'>Cancel</button> </div> """ controller: class extends BaseCtrl @inject 'User' $onInit: -> @user = @User.me @view = new @User @user save: -> @errors = null @view.$update(). then(=> angular.copy(@view, @user)). then(=> @modalInstance.close()). catch((response) => @errors = response.data)
[ { "context": "s: (filterdSearchOptions, numberOfColumns=2, key='related_gene', namespace='artworks') ->\n href = @href()\n ", "end": 4915, "score": 0.8996798992156982, "start": 4903, "tag": "KEY", "value": "related_gene" } ]
src/desktop/models/fair.coffee
pepopowitz/force
0
sd = require('sharify').data _ = require 'underscore' _s = require 'underscore.string' Backbone = require 'backbone' { Image, Markdown } = require '@artsy/backbone-mixins' PartnerLocation = require './partner_location.coffee' OrderedSets = require '../collections/ordered_sets.coffee' Profiles = require '../collections/profiles.coffee' DateHelpers = require '../components/util/date_helpers.coffee' Clock = require './mixins/clock.coffee' moment = require 'moment' Profile = require './profile.coffee' FilterSuggest = require './filter_suggest.coffee' deslugify = require '../components/deslugify/index.coffee' Relations = require './mixins/relations/fair.coffee' MetaOverrides = require './mixins/meta_overrides.coffee' DEFAULT_CACHE_TIME = 60 module.exports = class Fair extends Backbone.Model _.extend @prototype, Relations _.extend @prototype, Image(sd.SECURE_IMAGES_URL) _.extend @prototype, Markdown _.extend @prototype, Clock _.extend @prototype, MetaOverrides urlRoot: "#{sd.API_URL}/api/v1/fair" href: -> "/#{@profileId()}" profileId: -> @get('default_profile_id') || @get('organizer')?.profile_id fairOrgHref: -> "/#{@get('organizer')?.profile_id}/#{@formatYear()}" hasImage: (version = 'wide') -> version in (@get('image_versions') || []) location: -> if @get('location') new PartnerLocation @get('location') profileImage: (version = 'square140')-> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image/#{version}" url = "#{url}?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url hasOpened: -> moment().isAfter @get('start_at') formatLocation: -> @location()?.get('city') formatYear: -> moment(@get('start_at')).year() formatDates: -> DateHelpers.timespanInWords @get('start_at'), @get('end_at') bannerSize: -> sizes = 'x-large' : 1 'large' : 2 'medium' : 3 'small' : 4 'x-small' : 5 sizes[@get('banner_size')] fetchExhibitors: (options) -> galleries = new @aToZCollection('show', 'partner') galleries.fetchUntilEnd url: "#{@url()}/partners" data: private_partner: false cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = galleries.groupByAlphaWithColumns 3 options?.success aToZGroup, galleries error: -> options?.error() fetchArtists: (options = {}) -> artists = new @aToZCollection('artist') artists.fetchUntilEnd url: "#{@url()}/artists" cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = artists.groupByAlphaWithColumns 3 options.success aToZGroup, artists error: options.error fetchSections: (options) -> sections = new Backbone.Collection sections.fetch _.extend options, cache: true cacheTime: DEFAULT_CACHE_TIME url: "#{@url()}/sections" fetchPrimarySets: (options) -> orderedSets = new OrderedSets orderedSets .fetchItemsByOwner('Fair', @get('id'), cache: options.cache, cacheTime: options.cacheTime) .done -> for set in orderedSets.models items = set.get('items').filter (item) -> item.get('display_on_desktop') set.get('items').reset items options.success orderedSets # Custom A-to-Z-collection for fair urls aToZCollection: (namespace) => href = @href() class FairSearchResult extends Backbone.Model href: -> if namespace is 'show' and @get('partner_show_ids')?[0] "/show/#{@get('partner_show_ids')[0]}" else "#{href}/browse/#{namespace}/#{@get('id')}" displayName: -> @get('name') imageUrl: -> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image" url = url + "?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url new class FairSearchResults extends Profiles model: FairSearchResult # comparator: (model) -> model.get('sortable_id') groupByColumns: (columnCount=3) -> itemsPerColumn = Math.ceil(@length/3) columns = [] for n in [0...columnCount] columns.push @models[n*itemsPerColumn..(n+1)*itemsPerColumn - 1] columns fetchShowForPartner: (partnerId, options) -> shows = new Backbone.Collection shows.url = "#{@url()}/shows" shows.fetch data: partner: partnerId success: (shows) -> if shows.models?[0]?.get('results')?[0] options.success shows.models[0].get('results')[0] else options.error() error: options.error itemsToColumns: (items, numberOfColumns=2) -> maxRows = Math.ceil(items.length / numberOfColumns) for i in [0...numberOfColumns] items[(i * maxRows)...((i + 1) * maxRows)] filteredSearchColumns: (filterdSearchOptions, numberOfColumns=2, key='related_gene', namespace='artworks') -> href = @href() items = for item in _.keys(filterdSearchOptions.get(key)) actualName = filterdSearchOptions.get(key)[item]['name'] name = actualName || deslugify(item) { name: name href: "#{href}/browse/#{namespace}?#{key}=#{item}" } @itemsToColumns items, numberOfColumns # Fetches all of the data necessary to render the initial fair page and returns a # giant hash full of those models/az-groups/etc. # # The hash looks like this: # { # fair: Fair, # profile: Profile # filterSuggest: new FilterSuggest().fetch # filteredSearchOptions: this.filterSuggest # filteredSearchColumns: fair.filteredSearchColumns # sections: fair.fetchSections # galleries: fair.fetchExhibitors # exhibitorsCount: this.galleries.length # exhibitorsAToZGroup: fair.fetchExhibitors # artistsAToZGroup: fair.fetchArtists # } # # @param {Object} options Backbone-like options that calls success with (data) fetchOverviewData: (options) -> @fetch error: options.error success: => # Initialize the data hash with the models/collections that can be fetched in parallel data = fair: this filterSuggest: new FilterSuggest id: "fair/#{@get 'id'}" sections: null exhibitorsAToZGroup: null artistsAToZGroup: null galleries: null # Setup parallel callback after = _.after 3, => options.success _.extend data, coverImage: @get('profile').coverImage() exhibitorsCount: data.galleries.length @fetchSections(error: options.error, success: (x) => data.sections = x; after()) @fetchExhibitors error: options.error, success: (x, y) => data.exhibitorsAToZGroup = x data.galleries = y after() @fetchArtists(error: options.error, success: (x) => data.artistsAToZGroup = x; after()) isEligible: -> @get('has_full_feature') and @get('published') and @related().profile.get('published') isEventuallyEligible: -> @get('has_full_feature') and @get('published') and not @related().profile.get('published') isNotOver: -> not @isOver() isOver: -> endOfFair = moment.utc(@get('end_at')).endOf("day") now = moment() now.isAfter(endOfFair) isCurrent: -> @isEligible() and @isNotOver() isUpcoming: -> @isEventuallyEligible() and @isNotOver() isPast: -> @isEligible() and @isOver() nameSansYear: -> _s.rtrim @get('name'), /\s[0-9]/
154950
sd = require('sharify').data _ = require 'underscore' _s = require 'underscore.string' Backbone = require 'backbone' { Image, Markdown } = require '@artsy/backbone-mixins' PartnerLocation = require './partner_location.coffee' OrderedSets = require '../collections/ordered_sets.coffee' Profiles = require '../collections/profiles.coffee' DateHelpers = require '../components/util/date_helpers.coffee' Clock = require './mixins/clock.coffee' moment = require 'moment' Profile = require './profile.coffee' FilterSuggest = require './filter_suggest.coffee' deslugify = require '../components/deslugify/index.coffee' Relations = require './mixins/relations/fair.coffee' MetaOverrides = require './mixins/meta_overrides.coffee' DEFAULT_CACHE_TIME = 60 module.exports = class Fair extends Backbone.Model _.extend @prototype, Relations _.extend @prototype, Image(sd.SECURE_IMAGES_URL) _.extend @prototype, Markdown _.extend @prototype, Clock _.extend @prototype, MetaOverrides urlRoot: "#{sd.API_URL}/api/v1/fair" href: -> "/#{@profileId()}" profileId: -> @get('default_profile_id') || @get('organizer')?.profile_id fairOrgHref: -> "/#{@get('organizer')?.profile_id}/#{@formatYear()}" hasImage: (version = 'wide') -> version in (@get('image_versions') || []) location: -> if @get('location') new PartnerLocation @get('location') profileImage: (version = 'square140')-> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image/#{version}" url = "#{url}?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url hasOpened: -> moment().isAfter @get('start_at') formatLocation: -> @location()?.get('city') formatYear: -> moment(@get('start_at')).year() formatDates: -> DateHelpers.timespanInWords @get('start_at'), @get('end_at') bannerSize: -> sizes = 'x-large' : 1 'large' : 2 'medium' : 3 'small' : 4 'x-small' : 5 sizes[@get('banner_size')] fetchExhibitors: (options) -> galleries = new @aToZCollection('show', 'partner') galleries.fetchUntilEnd url: "#{@url()}/partners" data: private_partner: false cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = galleries.groupByAlphaWithColumns 3 options?.success aToZGroup, galleries error: -> options?.error() fetchArtists: (options = {}) -> artists = new @aToZCollection('artist') artists.fetchUntilEnd url: "#{@url()}/artists" cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = artists.groupByAlphaWithColumns 3 options.success aToZGroup, artists error: options.error fetchSections: (options) -> sections = new Backbone.Collection sections.fetch _.extend options, cache: true cacheTime: DEFAULT_CACHE_TIME url: "#{@url()}/sections" fetchPrimarySets: (options) -> orderedSets = new OrderedSets orderedSets .fetchItemsByOwner('Fair', @get('id'), cache: options.cache, cacheTime: options.cacheTime) .done -> for set in orderedSets.models items = set.get('items').filter (item) -> item.get('display_on_desktop') set.get('items').reset items options.success orderedSets # Custom A-to-Z-collection for fair urls aToZCollection: (namespace) => href = @href() class FairSearchResult extends Backbone.Model href: -> if namespace is 'show' and @get('partner_show_ids')?[0] "/show/#{@get('partner_show_ids')[0]}" else "#{href}/browse/#{namespace}/#{@get('id')}" displayName: -> @get('name') imageUrl: -> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image" url = url + "?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url new class FairSearchResults extends Profiles model: FairSearchResult # comparator: (model) -> model.get('sortable_id') groupByColumns: (columnCount=3) -> itemsPerColumn = Math.ceil(@length/3) columns = [] for n in [0...columnCount] columns.push @models[n*itemsPerColumn..(n+1)*itemsPerColumn - 1] columns fetchShowForPartner: (partnerId, options) -> shows = new Backbone.Collection shows.url = "#{@url()}/shows" shows.fetch data: partner: partnerId success: (shows) -> if shows.models?[0]?.get('results')?[0] options.success shows.models[0].get('results')[0] else options.error() error: options.error itemsToColumns: (items, numberOfColumns=2) -> maxRows = Math.ceil(items.length / numberOfColumns) for i in [0...numberOfColumns] items[(i * maxRows)...((i + 1) * maxRows)] filteredSearchColumns: (filterdSearchOptions, numberOfColumns=2, key='<KEY>', namespace='artworks') -> href = @href() items = for item in _.keys(filterdSearchOptions.get(key)) actualName = filterdSearchOptions.get(key)[item]['name'] name = actualName || deslugify(item) { name: name href: "#{href}/browse/#{namespace}?#{key}=#{item}" } @itemsToColumns items, numberOfColumns # Fetches all of the data necessary to render the initial fair page and returns a # giant hash full of those models/az-groups/etc. # # The hash looks like this: # { # fair: Fair, # profile: Profile # filterSuggest: new FilterSuggest().fetch # filteredSearchOptions: this.filterSuggest # filteredSearchColumns: fair.filteredSearchColumns # sections: fair.fetchSections # galleries: fair.fetchExhibitors # exhibitorsCount: this.galleries.length # exhibitorsAToZGroup: fair.fetchExhibitors # artistsAToZGroup: fair.fetchArtists # } # # @param {Object} options Backbone-like options that calls success with (data) fetchOverviewData: (options) -> @fetch error: options.error success: => # Initialize the data hash with the models/collections that can be fetched in parallel data = fair: this filterSuggest: new FilterSuggest id: "fair/#{@get 'id'}" sections: null exhibitorsAToZGroup: null artistsAToZGroup: null galleries: null # Setup parallel callback after = _.after 3, => options.success _.extend data, coverImage: @get('profile').coverImage() exhibitorsCount: data.galleries.length @fetchSections(error: options.error, success: (x) => data.sections = x; after()) @fetchExhibitors error: options.error, success: (x, y) => data.exhibitorsAToZGroup = x data.galleries = y after() @fetchArtists(error: options.error, success: (x) => data.artistsAToZGroup = x; after()) isEligible: -> @get('has_full_feature') and @get('published') and @related().profile.get('published') isEventuallyEligible: -> @get('has_full_feature') and @get('published') and not @related().profile.get('published') isNotOver: -> not @isOver() isOver: -> endOfFair = moment.utc(@get('end_at')).endOf("day") now = moment() now.isAfter(endOfFair) isCurrent: -> @isEligible() and @isNotOver() isUpcoming: -> @isEventuallyEligible() and @isNotOver() isPast: -> @isEligible() and @isOver() nameSansYear: -> _s.rtrim @get('name'), /\s[0-9]/
true
sd = require('sharify').data _ = require 'underscore' _s = require 'underscore.string' Backbone = require 'backbone' { Image, Markdown } = require '@artsy/backbone-mixins' PartnerLocation = require './partner_location.coffee' OrderedSets = require '../collections/ordered_sets.coffee' Profiles = require '../collections/profiles.coffee' DateHelpers = require '../components/util/date_helpers.coffee' Clock = require './mixins/clock.coffee' moment = require 'moment' Profile = require './profile.coffee' FilterSuggest = require './filter_suggest.coffee' deslugify = require '../components/deslugify/index.coffee' Relations = require './mixins/relations/fair.coffee' MetaOverrides = require './mixins/meta_overrides.coffee' DEFAULT_CACHE_TIME = 60 module.exports = class Fair extends Backbone.Model _.extend @prototype, Relations _.extend @prototype, Image(sd.SECURE_IMAGES_URL) _.extend @prototype, Markdown _.extend @prototype, Clock _.extend @prototype, MetaOverrides urlRoot: "#{sd.API_URL}/api/v1/fair" href: -> "/#{@profileId()}" profileId: -> @get('default_profile_id') || @get('organizer')?.profile_id fairOrgHref: -> "/#{@get('organizer')?.profile_id}/#{@formatYear()}" hasImage: (version = 'wide') -> version in (@get('image_versions') || []) location: -> if @get('location') new PartnerLocation @get('location') profileImage: (version = 'square140')-> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image/#{version}" url = "#{url}?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url hasOpened: -> moment().isAfter @get('start_at') formatLocation: -> @location()?.get('city') formatYear: -> moment(@get('start_at')).year() formatDates: -> DateHelpers.timespanInWords @get('start_at'), @get('end_at') bannerSize: -> sizes = 'x-large' : 1 'large' : 2 'medium' : 3 'small' : 4 'x-small' : 5 sizes[@get('banner_size')] fetchExhibitors: (options) -> galleries = new @aToZCollection('show', 'partner') galleries.fetchUntilEnd url: "#{@url()}/partners" data: private_partner: false cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = galleries.groupByAlphaWithColumns 3 options?.success aToZGroup, galleries error: -> options?.error() fetchArtists: (options = {}) -> artists = new @aToZCollection('artist') artists.fetchUntilEnd url: "#{@url()}/artists" cache: true cacheTime: DEFAULT_CACHE_TIME success: -> aToZGroup = artists.groupByAlphaWithColumns 3 options.success aToZGroup, artists error: options.error fetchSections: (options) -> sections = new Backbone.Collection sections.fetch _.extend options, cache: true cacheTime: DEFAULT_CACHE_TIME url: "#{@url()}/sections" fetchPrimarySets: (options) -> orderedSets = new OrderedSets orderedSets .fetchItemsByOwner('Fair', @get('id'), cache: options.cache, cacheTime: options.cacheTime) .done -> for set in orderedSets.models items = set.get('items').filter (item) -> item.get('display_on_desktop') set.get('items').reset items options.success orderedSets # Custom A-to-Z-collection for fair urls aToZCollection: (namespace) => href = @href() class FairSearchResult extends Backbone.Model href: -> if namespace is 'show' and @get('partner_show_ids')?[0] "/show/#{@get('partner_show_ids')[0]}" else "#{href}/browse/#{namespace}/#{@get('id')}" displayName: -> @get('name') imageUrl: -> url = "#{sd.API_URL}/api/v1/profile/#{@get('default_profile_id')}/image" url = url + "?xapp_token=#{sd.ARTSY_XAPP_TOKEN}" if sd.ARTSY_XAPP_TOKEN? url new class FairSearchResults extends Profiles model: FairSearchResult # comparator: (model) -> model.get('sortable_id') groupByColumns: (columnCount=3) -> itemsPerColumn = Math.ceil(@length/3) columns = [] for n in [0...columnCount] columns.push @models[n*itemsPerColumn..(n+1)*itemsPerColumn - 1] columns fetchShowForPartner: (partnerId, options) -> shows = new Backbone.Collection shows.url = "#{@url()}/shows" shows.fetch data: partner: partnerId success: (shows) -> if shows.models?[0]?.get('results')?[0] options.success shows.models[0].get('results')[0] else options.error() error: options.error itemsToColumns: (items, numberOfColumns=2) -> maxRows = Math.ceil(items.length / numberOfColumns) for i in [0...numberOfColumns] items[(i * maxRows)...((i + 1) * maxRows)] filteredSearchColumns: (filterdSearchOptions, numberOfColumns=2, key='PI:KEY:<KEY>END_PI', namespace='artworks') -> href = @href() items = for item in _.keys(filterdSearchOptions.get(key)) actualName = filterdSearchOptions.get(key)[item]['name'] name = actualName || deslugify(item) { name: name href: "#{href}/browse/#{namespace}?#{key}=#{item}" } @itemsToColumns items, numberOfColumns # Fetches all of the data necessary to render the initial fair page and returns a # giant hash full of those models/az-groups/etc. # # The hash looks like this: # { # fair: Fair, # profile: Profile # filterSuggest: new FilterSuggest().fetch # filteredSearchOptions: this.filterSuggest # filteredSearchColumns: fair.filteredSearchColumns # sections: fair.fetchSections # galleries: fair.fetchExhibitors # exhibitorsCount: this.galleries.length # exhibitorsAToZGroup: fair.fetchExhibitors # artistsAToZGroup: fair.fetchArtists # } # # @param {Object} options Backbone-like options that calls success with (data) fetchOverviewData: (options) -> @fetch error: options.error success: => # Initialize the data hash with the models/collections that can be fetched in parallel data = fair: this filterSuggest: new FilterSuggest id: "fair/#{@get 'id'}" sections: null exhibitorsAToZGroup: null artistsAToZGroup: null galleries: null # Setup parallel callback after = _.after 3, => options.success _.extend data, coverImage: @get('profile').coverImage() exhibitorsCount: data.galleries.length @fetchSections(error: options.error, success: (x) => data.sections = x; after()) @fetchExhibitors error: options.error, success: (x, y) => data.exhibitorsAToZGroup = x data.galleries = y after() @fetchArtists(error: options.error, success: (x) => data.artistsAToZGroup = x; after()) isEligible: -> @get('has_full_feature') and @get('published') and @related().profile.get('published') isEventuallyEligible: -> @get('has_full_feature') and @get('published') and not @related().profile.get('published') isNotOver: -> not @isOver() isOver: -> endOfFair = moment.utc(@get('end_at')).endOf("day") now = moment() now.isAfter(endOfFair) isCurrent: -> @isEligible() and @isNotOver() isUpcoming: -> @isEventuallyEligible() and @isNotOver() isPast: -> @isEligible() and @isOver() nameSansYear: -> _s.rtrim @get('name'), /\s[0-9]/
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.9999228715896606, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/services/status.js.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> 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. ### window.ChaiBioTech.ngApp .service 'Status', [ '$http' '$q' 'host' '$interval' '$timeout' '$rootScope' ($http, $q, host, $interval, $timeout, $rootScope) -> data = null isUp = false isUpStart = false isUpdating = false fetchInterval = null fetchForUpdateInterval = null @listenersCount = 0 fetching = false fetchingForUpdate = false timeoutPromise = null ques = [] @getData = -> data @isUp = -> isUp @isUpdating = -> isUpdating @fetch = -> deferred = $q.defer() ques.push deferred if fetching return deferred.promise else fetching = true timeoutPromise = $timeout => timeoutPromise = null fetching = false , 10000 $http.get("http://" + window.location.hostname + ":8000/status") .success (resp) => #console .log isUp #isUp = true oldData = angular.copy data data = resp for def in ques by 1 def.resolve data if data?.experiment_controller?.machine?.state is 'idle' and oldData?.experiment_controller?.machine?.state isnt 'idle' $rootScope.$broadcast 'status:experiment:completed' $rootScope.$broadcast 'status:data:updated', data, oldData .error (resp) -> #isUp = if resp is null then false else true $rootScope.$broadcast 'status:data:error', resp for def in ques by 1 def.reject(resp) .finally => $timeout.cancel timeoutPromise timeoutPromise = null fetching = false ques = [] deferred.promise @fetchForUpdate = -> isUpdating = true $http.get("/experiments") .success (resp) => console .log isUp isUp = if isUpStart then true else false if isUp $interval.cancel fetchForUpdateInterval .error (resp, status) -> console.log status isUpStart = true isUp = if status == 401 then true else false if isUp $interval.cancel fetchForUpdateInterval true @startSync = -> if !fetching then @fetch() if !fetchInterval fetchInterval = $interval @fetch, 1000 @stopSync = -> if (fetchInterval) $interval.cancel(fetchInterval) @startUpdateSync = -> fetchForUpdateInterval = $interval @fetchForUpdate, 1000 return ]
153285
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> 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. ### window.ChaiBioTech.ngApp .service 'Status', [ '$http' '$q' 'host' '$interval' '$timeout' '$rootScope' ($http, $q, host, $interval, $timeout, $rootScope) -> data = null isUp = false isUpStart = false isUpdating = false fetchInterval = null fetchForUpdateInterval = null @listenersCount = 0 fetching = false fetchingForUpdate = false timeoutPromise = null ques = [] @getData = -> data @isUp = -> isUp @isUpdating = -> isUpdating @fetch = -> deferred = $q.defer() ques.push deferred if fetching return deferred.promise else fetching = true timeoutPromise = $timeout => timeoutPromise = null fetching = false , 10000 $http.get("http://" + window.location.hostname + ":8000/status") .success (resp) => #console .log isUp #isUp = true oldData = angular.copy data data = resp for def in ques by 1 def.resolve data if data?.experiment_controller?.machine?.state is 'idle' and oldData?.experiment_controller?.machine?.state isnt 'idle' $rootScope.$broadcast 'status:experiment:completed' $rootScope.$broadcast 'status:data:updated', data, oldData .error (resp) -> #isUp = if resp is null then false else true $rootScope.$broadcast 'status:data:error', resp for def in ques by 1 def.reject(resp) .finally => $timeout.cancel timeoutPromise timeoutPromise = null fetching = false ques = [] deferred.promise @fetchForUpdate = -> isUpdating = true $http.get("/experiments") .success (resp) => console .log isUp isUp = if isUpStart then true else false if isUp $interval.cancel fetchForUpdateInterval .error (resp, status) -> console.log status isUpStart = true isUp = if status == 401 then true else false if isUp $interval.cancel fetchForUpdateInterval true @startSync = -> if !fetching then @fetch() if !fetchInterval fetchInterval = $interval @fetch, 1000 @stopSync = -> if (fetchInterval) $interval.cancel(fetchInterval) @startUpdateSync = -> fetchForUpdateInterval = $interval @fetchForUpdate, 1000 return ]
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.ChaiBioTech.ngApp .service 'Status', [ '$http' '$q' 'host' '$interval' '$timeout' '$rootScope' ($http, $q, host, $interval, $timeout, $rootScope) -> data = null isUp = false isUpStart = false isUpdating = false fetchInterval = null fetchForUpdateInterval = null @listenersCount = 0 fetching = false fetchingForUpdate = false timeoutPromise = null ques = [] @getData = -> data @isUp = -> isUp @isUpdating = -> isUpdating @fetch = -> deferred = $q.defer() ques.push deferred if fetching return deferred.promise else fetching = true timeoutPromise = $timeout => timeoutPromise = null fetching = false , 10000 $http.get("http://" + window.location.hostname + ":8000/status") .success (resp) => #console .log isUp #isUp = true oldData = angular.copy data data = resp for def in ques by 1 def.resolve data if data?.experiment_controller?.machine?.state is 'idle' and oldData?.experiment_controller?.machine?.state isnt 'idle' $rootScope.$broadcast 'status:experiment:completed' $rootScope.$broadcast 'status:data:updated', data, oldData .error (resp) -> #isUp = if resp is null then false else true $rootScope.$broadcast 'status:data:error', resp for def in ques by 1 def.reject(resp) .finally => $timeout.cancel timeoutPromise timeoutPromise = null fetching = false ques = [] deferred.promise @fetchForUpdate = -> isUpdating = true $http.get("/experiments") .success (resp) => console .log isUp isUp = if isUpStart then true else false if isUp $interval.cancel fetchForUpdateInterval .error (resp, status) -> console.log status isUpStart = true isUp = if status == 401 then true else false if isUp $interval.cancel fetchForUpdateInterval true @startSync = -> if !fetching then @fetch() if !fetchInterval fetchInterval = $interval @fetch, 1000 @stopSync = -> if (fetchInterval) $interval.cancel(fetchInterval) @startUpdateSync = -> fetchForUpdateInterval = $interval @fetchForUpdate, 1000 return ]
[ { "context": "adeTemplate)\nhtmlOutput = fn(maintainer:\n name: 'Forbes Lindesay'\n twitter: '@ForbesLindesay'\n blog: 'forbeslind", "end": 121, "score": 0.9998737573623657, "start": 106, "tag": "NAME", "value": "Forbes Lindesay" }, { "context": "n(maintainer:\n name: 'Forbes Lin...
JadeFetcher.coffee
KuroiAme/ui-router.stateHelper.json
0
Jadefetcher = (jade,JSONfetcher) -> fn = jade.compile(jadeTemplate) htmlOutput = fn(maintainer: name: 'Forbes Lindesay' twitter: '@ForbesLindesay' blog: 'forbeslindesay.co.uk') return jade: htmlOutput fetcher .$inject = [ 'jade' 'd.json' ] angular .module('daniel.json') .factory('fetcher', fetcher)
83146
Jadefetcher = (jade,JSONfetcher) -> fn = jade.compile(jadeTemplate) htmlOutput = fn(maintainer: name: '<NAME>' twitter: '@ForbesLindesay' blog: 'forbeslindesay.co.uk') return jade: htmlOutput fetcher .$inject = [ 'jade' 'd.json' ] angular .module('daniel.json') .factory('fetcher', fetcher)
true
Jadefetcher = (jade,JSONfetcher) -> fn = jade.compile(jadeTemplate) htmlOutput = fn(maintainer: name: 'PI:NAME:<NAME>END_PI' twitter: '@ForbesLindesay' blog: 'forbeslindesay.co.uk') return jade: htmlOutput fetcher .$inject = [ 'jade' 'd.json' ] angular .module('daniel.json') .factory('fetcher', fetcher)
[ { "context": "ssage to the buyer\n smsOptions = \n From: 'MyPikins'\n phone: '233246424340'\n contents: cont", "end": 929, "score": 0.8953349590301514, "start": 921, "tag": "USERNAME", "value": "MyPikins" }, { "context": "ay.vodafonecash.com.gh', { params:\n user...
client/helpers/generic_helpers.coffee
Innarticles/mypikin
0
Template.saveToday.helpers amountToday: ()-> getAmountPayableToday() Template.paymentPlan.helpers pikin: () -> Pikins.findOne() Template.saveToday.events 'click #saveToVCash': (event, template) -> # console.log 'click is working' console.log (Meteor.call 'vodafoneApi') Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.confirmTransactionModal.events 'click #confirmationModal': (event, template) -> content = 'Transaction is completed successfully. Money has been saved from your Vodafone Cash!' #send a message to the buyer smsOptions = From: 'MyPikins' phone: '233246424340' contents: content Meteor.call 'sendMessage', smsOptions Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.saveToday.helpers pikin: () -> Pikins.findOne() Template.status.helpers progress: () -> if Payments.findOne() Math.ceil(getTheTotalAmountContributed()/getTotalPayable() * 100) totalSaved: () -> getTheTotalAmountContributed() saveXToday: () -> getAmountPayableToday() getAmountPayableToday = ()-> totalPayable = getTotalPayable(); console.log getNumberOfPeriods() amountToPayNow = Math.ceil (totalPayable/getNumberOfPeriods()) getTotalPayable = ()-> delivery = Pikins.findOne()?.choiceOfDelivery potentialAMount = if (delivery == "Normal") then 500 else 1000 getNumberOfPeriods = ()-> if Pikins.findOne() birthDate = moment(Pikins.findOne()?.conceptionDate) createdDate = moment(Pikins.findOne()?.createdAt) intervalType = Pikins.findOne()?.PaymentInterval if intervalType == 'Daily' numberOfPeriods = birthDate?.diff(createdDate, 'days') else if intervalType == 'Weekly' numberOfPeriods = birthDate?.diff(createdDate, 'weeks') else numberOfPeriods = birthDate?.diff(createdDate, 'monthly') getTheTotalAmountContributed = ()-> total = 0 Payments.find().map (payment) -> total += payment.amount total vodafoneAPi = ()-> console.log 'in the api' HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: 'hackathon2' token: 'abc1234' amount: '2' }, (error, result) -> if !error console.log result return
123211
Template.saveToday.helpers amountToday: ()-> getAmountPayableToday() Template.paymentPlan.helpers pikin: () -> Pikins.findOne() Template.saveToday.events 'click #saveToVCash': (event, template) -> # console.log 'click is working' console.log (Meteor.call 'vodafoneApi') Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.confirmTransactionModal.events 'click #confirmationModal': (event, template) -> content = 'Transaction is completed successfully. Money has been saved from your Vodafone Cash!' #send a message to the buyer smsOptions = From: 'MyPikins' phone: '233246424340' contents: content Meteor.call 'sendMessage', smsOptions Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.saveToday.helpers pikin: () -> Pikins.findOne() Template.status.helpers progress: () -> if Payments.findOne() Math.ceil(getTheTotalAmountContributed()/getTotalPayable() * 100) totalSaved: () -> getTheTotalAmountContributed() saveXToday: () -> getAmountPayableToday() getAmountPayableToday = ()-> totalPayable = getTotalPayable(); console.log getNumberOfPeriods() amountToPayNow = Math.ceil (totalPayable/getNumberOfPeriods()) getTotalPayable = ()-> delivery = Pikins.findOne()?.choiceOfDelivery potentialAMount = if (delivery == "Normal") then 500 else 1000 getNumberOfPeriods = ()-> if Pikins.findOne() birthDate = moment(Pikins.findOne()?.conceptionDate) createdDate = moment(Pikins.findOne()?.createdAt) intervalType = Pikins.findOne()?.PaymentInterval if intervalType == 'Daily' numberOfPeriods = birthDate?.diff(createdDate, 'days') else if intervalType == 'Weekly' numberOfPeriods = birthDate?.diff(createdDate, 'weeks') else numberOfPeriods = birthDate?.diff(createdDate, 'monthly') getTheTotalAmountContributed = ()-> total = 0 Payments.find().map (payment) -> total += payment.amount total vodafoneAPi = ()-> console.log 'in the api' HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: '<PASSWORD>' token: '<KEY> <PASSWORD>' amount: '2' }, (error, result) -> if !error console.log result return
true
Template.saveToday.helpers amountToday: ()-> getAmountPayableToday() Template.paymentPlan.helpers pikin: () -> Pikins.findOne() Template.saveToday.events 'click #saveToVCash': (event, template) -> # console.log 'click is working' console.log (Meteor.call 'vodafoneApi') Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.confirmTransactionModal.events 'click #confirmationModal': (event, template) -> content = 'Transaction is completed successfully. Money has been saved from your Vodafone Cash!' #send a message to the buyer smsOptions = From: 'MyPikins' phone: '233246424340' contents: content Meteor.call 'sendMessage', smsOptions Meteor.call 'vodafoneApi', (err, data) -> if err console.log err if data # console.log data Session.set 'q', data return wrapper= document.createElement('div') wrapper.innerHTML= Session.get 'q' div = template.find('#showStatus') # console.log div div= wrapper.firstChild # console.log div Template.saveToday.helpers pikin: () -> Pikins.findOne() Template.status.helpers progress: () -> if Payments.findOne() Math.ceil(getTheTotalAmountContributed()/getTotalPayable() * 100) totalSaved: () -> getTheTotalAmountContributed() saveXToday: () -> getAmountPayableToday() getAmountPayableToday = ()-> totalPayable = getTotalPayable(); console.log getNumberOfPeriods() amountToPayNow = Math.ceil (totalPayable/getNumberOfPeriods()) getTotalPayable = ()-> delivery = Pikins.findOne()?.choiceOfDelivery potentialAMount = if (delivery == "Normal") then 500 else 1000 getNumberOfPeriods = ()-> if Pikins.findOne() birthDate = moment(Pikins.findOne()?.conceptionDate) createdDate = moment(Pikins.findOne()?.createdAt) intervalType = Pikins.findOne()?.PaymentInterval if intervalType == 'Daily' numberOfPeriods = birthDate?.diff(createdDate, 'days') else if intervalType == 'Weekly' numberOfPeriods = birthDate?.diff(createdDate, 'weeks') else numberOfPeriods = birthDate?.diff(createdDate, 'monthly') getTheTotalAmountContributed = ()-> total = 0 Payments.find().map (payment) -> total += payment.amount total vodafoneAPi = ()-> console.log 'in the api' HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: 'PI:PASSWORD:<PASSWORD>END_PI' token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' amount: '2' }, (error, result) -> if !error console.log result return
[ { "context": " @database.devices.insert uuid: 'uuid1', token: 'token1', configureWhitelist: ['*'], done\n\n beforeEac", "end": 1157, "score": 0.5388278961181641, "start": 1152, "tag": "KEY", "value": "token" }, { "context": "tabase.devices.insert uuid: 'uuid1', token: 'token1', c...
test/lib/createSubscriptionIfAuthorized-spec.coffee
CESARBR/knot-cloud-source
4
_ = require 'lodash' TestDatabase = require '../test-database' describe 'createSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/createSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when called with an invalid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'invalid'}, storeError it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Type must be one of ["broadcast", "config", "received", "sent"]' describe 'when called with an valid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'broadcast'}, storeError it 'should yield not an error', -> expect(@error).not.to.be.an.instanceOf Error describe 'when we have one open device and one closed device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: 'token1', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: 'token2', configureWhitelist: [], done describe 'when the open device creates a subscription from itself to the closed device', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should create exactly one subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() it 'should create a new subscription for uuid1', (done) -> @database.subscriptions.findOne {}, (error, subscription) => return done error if error? subscription = _.omit subscription, '_id' expect(subscription).to.deep.equal subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'broadcast' done() describe 'if we call it again', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should not create a new subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else creates a subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { subscriberUuid: @closed_device.uuid emitterUuid: @open_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should create exactly no subscriptions in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 0 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to subscribe on behalf of that device'
125506
_ = require 'lodash' TestDatabase = require '../test-database' describe 'createSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/createSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when called with an invalid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'invalid'}, storeError it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Type must be one of ["broadcast", "config", "received", "sent"]' describe 'when called with an valid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'broadcast'}, storeError it 'should yield not an error', -> expect(@error).not.to.be.an.instanceOf Error describe 'when we have one open device and one closed device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: '<KEY> <PASSWORD>', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: '<PASSWORD>', configureWhitelist: [], done describe 'when the open device creates a subscription from itself to the closed device', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should create exactly one subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() it 'should create a new subscription for uuid1', (done) -> @database.subscriptions.findOne {}, (error, subscription) => return done error if error? subscription = _.omit subscription, '_id' expect(subscription).to.deep.equal subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'broadcast' done() describe 'if we call it again', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should not create a new subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else creates a subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { subscriberUuid: @closed_device.uuid emitterUuid: @open_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should create exactly no subscriptions in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 0 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to subscribe on behalf of that device'
true
_ = require 'lodash' TestDatabase = require '../test-database' describe 'createSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/createSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when called with an invalid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'invalid'}, storeError it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Type must be one of ["broadcast", "config", "received", "sent"]' describe 'when called with an valid type', -> beforeEach (done) -> storeError = (@error) => done() @sut {}, {type: 'broadcast'}, storeError it 'should yield not an error', -> expect(@error).not.to.be.an.instanceOf Error describe 'when we have one open device and one closed device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: 'PI:PASSWORD:<PASSWORD>END_PI', configureWhitelist: [], done describe 'when the open device creates a subscription from itself to the closed device', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should create exactly one subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() it 'should create a new subscription for uuid1', (done) -> @database.subscriptions.findOne {}, (error, subscription) => return done error if error? subscription = _.omit subscription, '_id' expect(subscription).to.deep.equal subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'broadcast' done() describe 'if we call it again', -> beforeEach (done) -> params = { subscriberUuid: @open_device.uuid emitterUuid: @closed_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should not create a new subscription in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else creates a subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { subscriberUuid: @closed_device.uuid emitterUuid: @open_device.uuid type: 'broadcast' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should create exactly no subscriptions in the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 0 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to subscribe on behalf of that device'
[ { "context": " Tests for no-useless-computed-key rule.\n# @author Burak Yigit Kaya\n###\n\n'use strict'\n\n#-----------------------------", "end": 87, "score": 0.9998484253883362, "start": 71, "tag": "NAME", "value": "Burak Yigit Kaya" } ]
src/tests/rules/no-useless-computed-key.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-useless-computed-key rule. # @author Burak Yigit Kaya ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-useless-computed-key' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-useless-computed-key', rule, valid: [ "({ 'a': 0, b: -> })" '({ [x]: 0 });' '({ a: 0, [b]: -> })' "({ ['__proto__']: [] })" '{[5]}' '{[a]}' '{["a"]}' ] invalid: [ code: "({ ['0']: 0 })" output: "({ '0': 0 })" errors: [ message: "Unnecessarily computed property ['0'] found." type: 'Property' ] , code: "({ ['0+1,234']: 0 })" output: "({ '0+1,234': 0 })" errors: [ message: "Unnecessarily computed property ['0+1,234'] found." type: 'Property' ] , code: '({ [0]: 0 })' output: '({ 0: 0 })' errors: [ message: 'Unnecessarily computed property [0] found.' type: 'Property' ] , code: "({ ['x']: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x']: -> })" output: "({ 'x': -> })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [### this comment prevents a fix ### 'x']: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x' ### this comment also prevents a fix ###]: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [('x')]: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] ]
211396
###* # @fileoverview Tests for no-useless-computed-key rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-useless-computed-key' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-useless-computed-key', rule, valid: [ "({ 'a': 0, b: -> })" '({ [x]: 0 });' '({ a: 0, [b]: -> })' "({ ['__proto__']: [] })" '{[5]}' '{[a]}' '{["a"]}' ] invalid: [ code: "({ ['0']: 0 })" output: "({ '0': 0 })" errors: [ message: "Unnecessarily computed property ['0'] found." type: 'Property' ] , code: "({ ['0+1,234']: 0 })" output: "({ '0+1,234': 0 })" errors: [ message: "Unnecessarily computed property ['0+1,234'] found." type: 'Property' ] , code: '({ [0]: 0 })' output: '({ 0: 0 })' errors: [ message: 'Unnecessarily computed property [0] found.' type: 'Property' ] , code: "({ ['x']: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x']: -> })" output: "({ 'x': -> })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [### this comment prevents a fix ### 'x']: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x' ### this comment also prevents a fix ###]: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [('x')]: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] ]
true
###* # @fileoverview Tests for no-useless-computed-key rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-useless-computed-key' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-useless-computed-key', rule, valid: [ "({ 'a': 0, b: -> })" '({ [x]: 0 });' '({ a: 0, [b]: -> })' "({ ['__proto__']: [] })" '{[5]}' '{[a]}' '{["a"]}' ] invalid: [ code: "({ ['0']: 0 })" output: "({ '0': 0 })" errors: [ message: "Unnecessarily computed property ['0'] found." type: 'Property' ] , code: "({ ['0+1,234']: 0 })" output: "({ '0+1,234': 0 })" errors: [ message: "Unnecessarily computed property ['0+1,234'] found." type: 'Property' ] , code: '({ [0]: 0 })' output: '({ 0: 0 })' errors: [ message: 'Unnecessarily computed property [0] found.' type: 'Property' ] , code: "({ ['x']: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x']: -> })" output: "({ 'x': -> })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [### this comment prevents a fix ### 'x']: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ ['x' ### this comment also prevents a fix ###]: 0 })" output: null errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] , code: "({ [('x')]: 0 })" output: "({ 'x': 0 })" errors: [ message: "Unnecessarily computed property ['x'] found." type: 'Property' ] ]
[ { "context": " output: [\n code: \" thi\"\n class: \"test class a\"\n ", "end": 11485, "score": 0.871407151222229, "start": 11482, "tag": "NAME", "value": "thi" } ]
src/coffee/editor/compiler/generateSyntaxHighlighting.spec.coffee
jameswilddev/influx7
1
describe "editor", -> describe "compiler", -> describe "generateSyntaxHighlighting", -> describe "on calling", -> editorCompilerGenerateSyntaxHighlighting = require "./generateSyntaxHighlighting" run = (config) -> describe config.description, -> result = tokensCopy = undefined beforeEach -> tokensCopy = JSON.parse JSON.stringify config.tokens result = editorCompilerGenerateSyntaxHighlighting config.code, tokensCopy it "does not modify the tokens", -> (expect tokensCopy).toEqual config.tokens it "returns the expected output", -> (expect result).toEqual config.output run description: "one token from start to end" code: "test code" tokens: [ starts: 0 ends: 8 class: "test class a" ] output: [ class: "test class a" code: "test code" ] run description: "one token after start to end" code: "test code" tokens: [ starts: 2 ends: 8 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st code" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 0 ends: 6 class: "test class a" ] output: [ class: "test class a" code: "test co" , class: "Comment" code: "de" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 3 ends: 6 class: "test class a" ] output: [ class: "Comment" code: "tes" , class: "test class a" code: "t co" , class: "Comment" code: "de" ] run description: "two tokens occupying all space in order" code: "test code" tokens: [ starts: 0 ends: 2 class: "test class a" , starts: 3 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens occupying all space out of order" code: "test code" tokens: [ starts: 3 ends: 8 class: "test class b" , starts: 0 ends: 2 class: "test class a" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space before out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 2 ends: 6 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens with a space after out of order" code: "test code" tokens: [ starts: 2 ends: 6 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens separated by a space in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space space out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 7 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space before out of order" code: "test code" tokens: [ starts: 7 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 7 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "two tokens separated by a space with a space after out of order" code: "test code" tokens: [ starts: 6 ends: 7 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "complex scenario" code: " this is test code to be split up by the code under test " tokens: [ starts: 19 ends: 26 class: "test class d" , starts: 0 ends: 4 class: "test class a" , starts: 7 ends: 12 class: "test class b" , starts: 13 ends: 18 class: "test class c" , starts: 32 ends: 48 class: "test class e" ] output: [ code: " thi" class: "test class a" , code: "s " class: "Comment" , code: "is te" class: "test class b" , code: "st cod" class: "test class c" , code: "e to be " class: "test class d" , code: "split" class: "Comment" , code: " up by the code " class: "test class e" , code: "under test " class: "Comment" ]
3217
describe "editor", -> describe "compiler", -> describe "generateSyntaxHighlighting", -> describe "on calling", -> editorCompilerGenerateSyntaxHighlighting = require "./generateSyntaxHighlighting" run = (config) -> describe config.description, -> result = tokensCopy = undefined beforeEach -> tokensCopy = JSON.parse JSON.stringify config.tokens result = editorCompilerGenerateSyntaxHighlighting config.code, tokensCopy it "does not modify the tokens", -> (expect tokensCopy).toEqual config.tokens it "returns the expected output", -> (expect result).toEqual config.output run description: "one token from start to end" code: "test code" tokens: [ starts: 0 ends: 8 class: "test class a" ] output: [ class: "test class a" code: "test code" ] run description: "one token after start to end" code: "test code" tokens: [ starts: 2 ends: 8 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st code" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 0 ends: 6 class: "test class a" ] output: [ class: "test class a" code: "test co" , class: "Comment" code: "de" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 3 ends: 6 class: "test class a" ] output: [ class: "Comment" code: "tes" , class: "test class a" code: "t co" , class: "Comment" code: "de" ] run description: "two tokens occupying all space in order" code: "test code" tokens: [ starts: 0 ends: 2 class: "test class a" , starts: 3 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens occupying all space out of order" code: "test code" tokens: [ starts: 3 ends: 8 class: "test class b" , starts: 0 ends: 2 class: "test class a" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space before out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 2 ends: 6 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens with a space after out of order" code: "test code" tokens: [ starts: 2 ends: 6 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens separated by a space in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space space out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 7 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space before out of order" code: "test code" tokens: [ starts: 7 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 7 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "two tokens separated by a space with a space after out of order" code: "test code" tokens: [ starts: 6 ends: 7 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "complex scenario" code: " this is test code to be split up by the code under test " tokens: [ starts: 19 ends: 26 class: "test class d" , starts: 0 ends: 4 class: "test class a" , starts: 7 ends: 12 class: "test class b" , starts: 13 ends: 18 class: "test class c" , starts: 32 ends: 48 class: "test class e" ] output: [ code: " <NAME>" class: "test class a" , code: "s " class: "Comment" , code: "is te" class: "test class b" , code: "st cod" class: "test class c" , code: "e to be " class: "test class d" , code: "split" class: "Comment" , code: " up by the code " class: "test class e" , code: "under test " class: "Comment" ]
true
describe "editor", -> describe "compiler", -> describe "generateSyntaxHighlighting", -> describe "on calling", -> editorCompilerGenerateSyntaxHighlighting = require "./generateSyntaxHighlighting" run = (config) -> describe config.description, -> result = tokensCopy = undefined beforeEach -> tokensCopy = JSON.parse JSON.stringify config.tokens result = editorCompilerGenerateSyntaxHighlighting config.code, tokensCopy it "does not modify the tokens", -> (expect tokensCopy).toEqual config.tokens it "returns the expected output", -> (expect result).toEqual config.output run description: "one token from start to end" code: "test code" tokens: [ starts: 0 ends: 8 class: "test class a" ] output: [ class: "test class a" code: "test code" ] run description: "one token after start to end" code: "test code" tokens: [ starts: 2 ends: 8 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st code" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 0 ends: 6 class: "test class a" ] output: [ class: "test class a" code: "test co" , class: "Comment" code: "de" ] run description: "one token from start to before end" code: "test code" tokens: [ starts: 3 ends: 6 class: "test class a" ] output: [ class: "Comment" code: "tes" , class: "test class a" code: "t co" , class: "Comment" code: "de" ] run description: "two tokens occupying all space in order" code: "test code" tokens: [ starts: 0 ends: 2 class: "test class a" , starts: 3 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens occupying all space out of order" code: "test code" tokens: [ starts: 3 ends: 8 class: "test class b" , starts: 0 ends: 2 class: "test class a" ] output: [ class: "test class a" code: "tes" , class: "test class b" code: "t code" ] run description: "two tokens with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space before out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 2 ends: 6 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens with a space after out of order" code: "test code" tokens: [ starts: 2 ends: 6 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "test class b" code: "st co" , class: "Comment" code: "de" ] run description: "two tokens separated by a space in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 8 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space space out of order" code: "test code" tokens: [ starts: 6 ends: 8 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "ode" ] run description: "two tokens separated by a space with a space before in order" code: "test code" tokens: [ starts: 2 ends: 5 class: "test class a" , starts: 7 ends: 8 class: "test class b" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space before out of order" code: "test code" tokens: [ starts: 7 ends: 8 class: "test class b" , starts: 2 ends: 5 class: "test class a" ] output: [ class: "Comment" code: "te" , class: "test class a" code: "st c" , class: "Comment" code: "o" , class: "test class b" code: "de" ] run description: "two tokens separated by a space with a space after in order" code: "test code" tokens: [ starts: 0 ends: 1 class: "test class a" , starts: 6 ends: 7 class: "test class b" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "two tokens separated by a space with a space after out of order" code: "test code" tokens: [ starts: 6 ends: 7 class: "test class b" , starts: 0 ends: 1 class: "test class a" ] output: [ class: "test class a" code: "te" , class: "Comment" code: "st c" , class: "test class b" code: "od" , class: "Comment" code: "e" ] run description: "complex scenario" code: " this is test code to be split up by the code under test " tokens: [ starts: 19 ends: 26 class: "test class d" , starts: 0 ends: 4 class: "test class a" , starts: 7 ends: 12 class: "test class b" , starts: 13 ends: 18 class: "test class c" , starts: 32 ends: 48 class: "test class e" ] output: [ code: " PI:NAME:<NAME>END_PI" class: "test class a" , code: "s " class: "Comment" , code: "is te" class: "test class b" , code: "st cod" class: "test class c" , code: "e to be " class: "test class d" , code: "split" class: "Comment" , code: " up by the code " class: "test class e" , code: "under test " class: "Comment" ]
[ { "context": "##!\njQuery Yacal Plugin v0.2.0\nhttps://github.com/eduludi/jquery-yacal\n\nAuthors:\n - Eduardo Ludi @eduludi\n ", "end": 58, "score": 0.9995213150978088, "start": 51, "tag": "USERNAME", "value": "eduludi" }, { "context": "tps://github.com/eduludi/jquery-yacal\n\nAutho...
src/jquery.yacal.coffee
eduludi/yacal
0
###! jQuery Yacal Plugin v0.2.0 https://github.com/eduludi/jquery-yacal Authors: - Eduardo Ludi @eduludi - Some ideas from Pickaday: https://github.com/dbushell/Pikaday (thanks to David Bushell @dbushell and Ramiro Rikkert @RamRik) - isLeapYear: Matti Virkkunen (http://stackoverflow.com/a/4881951) Released under the MIT license ### (( $, doc, win ) -> "use strict" _name = 'yacal' # plugin's name _version = '0.5.0' _msInDay = 86400000 # milliseconds in a day _eStr = '' # empty string # placeholders _ph = d: '#day#' dc: '#dayclass#' dt: '#time#' wd: '#weekday#' we: '#weekend#' t: '#today#' s: '#selected#' a: '#active#' w: '#week#' ws: '#weekSelected#' wt: '#weekTime#' wdn: '#weekdayName#' m: '#month#' mnam: '#monthName#' y: '#year#' nav: '#nav#' prev: '#prev#' next: '#next#' isDate = (obj) -> (/Date/).test(Object.prototype.toString.call(obj)) and !isNaN(+obj) isWeekend = (date) -> date.getDay() in [0,6] inRange = (date,min,max) -> # Validate dates vmi = isDate(min) vmx = isDate(max) if vmi and vmx min <= date and date <= max else if vmi min <= date else if vmx date <= max else true zeroHour = (date) -> date.setHours(0,0,0,0) # !!!: setHours() returns a timestamp isToday = (date) -> zeroHour(date) == zeroHour(new Date()) isLeapYear = (year) -> year % 4 == 0 and year % 100 != 0 || year % 400 == 0 getDaysInMonth = (year, month) -> s = 30 # short month l = 31 # long month f = (if isLeapYear(year) then 29 else 28) # febraury [l,f,l,s,l,s,l,l,s,l,s,l][month] getWeekNumber = (date) -> onejan = new Date(date.getFullYear(), 0, 1) Math.ceil((((date - onejan) / _msInDay) + onejan.getDay() + 1) / 7) getWeekStart = (date) -> new Date(zeroHour(date) - date.getDay()*_msInDay) getWeekEnd = (weekStartDate) -> new Date(+weekStartDate + (7 * _msInDay) - 1) changeMonth = (date,amount) -> new Date(date.getFullYear(),(date.getMonth() + amount),1) tag = (name,classes,content,data) -> '<'+name+' '+ (if classes then ' class="'+classes+'"' else _eStr)+ (if data then ' data-'+data else _eStr)+'>'+ (if content then content else _eStr) + '</'+name+'>' # Plugin definition $.fn.yacal = ( options ) -> this.each( (index) -> # _date = Current date, _selected = Selected date _date = _selected = null # template & internationalization settings _tpl = {} _i18n = {} # other settings _nearMonths = _wdays = _minDate = _maxDate = _firstDay = _pageSize = _isActive = _dayClass = null # runtime templates parts _weekPart = _monthPart = null # Instance Methods isSelected = (date) -> zeroHour(_selected) == zeroHour(date) isSelectedWeek = (wStart) -> inRange(_selected,wStart,getWeekEnd(wStart)) renderNav = () -> _tpl.nav.replace(_ph.prev,_i18n.prev) .replace(_ph.next,_i18n.next) renderDay = (date) -> _tpl.day.replace(_ph.d, date.getDate()) .replace(_ph.dt, +date) .replace(_ph.wd, date.getDay()) .replace(_ph.we, if isWeekend(date) then ' weekend' else _eStr) .replace(_ph.t, if isToday(date) then ' today' else _eStr) .replace(_ph.s, if isSelected(date) then ' selected' else _eStr) .replace(_ph.a, if inRange(date,_minDate,_maxDate) and _isActive?(date) ? true then ' active' else _eStr) .replace(_ph.dc, ' ' + (_dayClass?(date) ? _eStr)) renderMonth = (date,nav=false) -> d = 0 out = _eStr month = date.getMonth() year = date.getFullYear() totalDays = getDaysInMonth(date.getYear(),date.getMonth()) # weekdays if _wdays wd = 0 out += _weekPart[0].replace(_ph.w,wd) .replace(_ph.wt,_eStr) .replace(_ph.ws,_eStr) while wd <= 6 out += _tpl.weekday.replace(_ph.wdn,_i18n.weekdays[wd]) .replace(_ph.wd,wd++) out += _weekPart[1] # month weeks and days while d < totalDays day = new Date(year,month,d+1) if 0 in [d,day.getDay()] wStart = getWeekStart(day) selWeek = if isSelectedWeek(wStart) then ' selected' else _eStr out += _weekPart[0].replace(_ph.w, getWeekNumber(day)) .replace(_ph.wt, wStart) .replace(_ph.ws, selWeek) d++ out += renderDay(day,_tpl.day) if (d == totalDays || day.getDay() == 6) out += _weekPart[1] # replace placeholders and return the output _monthPart[0].replace(_ph.m,month) .replace(_ph.mnam,_i18n.months[month]) .replace(_ph.y,year) + out + _monthPart[1] renderCalendar = (element,move) -> out = '' cal = $(element) if move _date = changeMonth(_date,move) # Render previous month[s] if _nearMonths pm = _nearMonths while pm > 0 out += renderMonth(changeMonth(_date,-pm)) pm-- # Render selected month out += renderMonth(_date,true); # Render next[s] month[s] if _nearMonths nm = 1 while nm <= _nearMonths out += renderMonth(changeMonth(_date,+nm)) nm++ # add wrap, nav, output, and clearfix to the dom element cal.html('').append($(_tpl.wrap).append(renderNav()) .append(out) .append(_tpl.clearfix)) # Navigation Events nav = cal.find('.yclNav') nav.find('.prev').on 'click', -> renderCalendar(cal, -_pageSize) nav.find('.next').on 'click', -> renderCalendar(cal, _pageSize) # End of instance methods - # get config from defaults opts = $.extend(true,{}, $.fn.yacal.defaults, options ) # get config from data-* atrributes opts = $.extend( true, {}, opts, $(this).data() ) if ($(this).data()) # Config _date = _selected = new Date(opts.date) # Ensures get a date _tpl = opts.tpl _i18n = opts.i18n _nearMonths = +opts.nearMonths _wdays = !!opts.showWeekdays _minDate = new Date(opts.minDate) if opts.minDate _maxDate = new Date(opts.maxDate) if opts.maxDate _pageSize = opts.pageSize ? 1 _isActive = opts.isActive _dayClass = opts.dayClass # _firstDay = +opts.firstDay # TODO _weekPart = _tpl.week.split('|') _monthPart = _tpl.month.split('|') renderCalendar(this) ) # Defaults $.fn.yacal.defaults = date: new Date() nearMonths: 0 showWeekdays: 1 minDate: null maxDate: null firstDay: 0 pageSize: 1 tpl: day: tag('a','day d'+_ph.wd+''+_ph.we+''+_ph.t+''+_ph.s+''+_ph.a+''+_ph.dc, _ph.d,'time="'+_ph.dt+'"') weekday: tag('i','wday wd'+_ph.wd,_ph.wdn) week: tag('div','week w'+_ph.w+_ph.ws,'|','time="'+_ph.wt+'"') month: tag('div','month m'+_ph.m,tag('h4',null,_ph.mnam+' '+_ph.y) + '|') nav: tag('div','yclNav', tag('a','prev',tag('span',null,_ph.prev))+ tag('a','next',tag('span',null,_ph.next))) wrap: tag('div','wrap') clearfix: tag('div','clearfix') i18n: weekdays: ['Su','Mo','Tu','We','Th','Fr','Sa'], months: ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'], prev: 'prev', next: 'next', # Version number $.fn.yacal.version = _version; # Autoinitialize .yacal elements on load $('.' + _name).yacal() )( jQuery, document, window )
171739
###! jQuery Yacal Plugin v0.2.0 https://github.com/eduludi/jquery-yacal Authors: - <NAME> @eduludi - Some ideas from Pickaday: https://github.com/dbushell/Pikaday (thanks to <NAME> @dbushell and <NAME> @RamRik) - isLeapYear: <NAME> (http://stackoverflow.com/a/4881951) Released under the MIT license ### (( $, doc, win ) -> "use strict" _name = 'yacal' # plugin's name _version = '0.5.0' _msInDay = 86400000 # milliseconds in a day _eStr = '' # empty string # placeholders _ph = d: '#day#' dc: '#dayclass#' dt: '#time#' wd: '#weekday#' we: '#weekend#' t: '#today#' s: '#selected#' a: '#active#' w: '#week#' ws: '#weekSelected#' wt: '#weekTime#' wdn: '#weekdayName#' m: '#month#' mnam: '#monthName#' y: '#year#' nav: '#nav#' prev: '#prev#' next: '#next#' isDate = (obj) -> (/Date/).test(Object.prototype.toString.call(obj)) and !isNaN(+obj) isWeekend = (date) -> date.getDay() in [0,6] inRange = (date,min,max) -> # Validate dates vmi = isDate(min) vmx = isDate(max) if vmi and vmx min <= date and date <= max else if vmi min <= date else if vmx date <= max else true zeroHour = (date) -> date.setHours(0,0,0,0) # !!!: setHours() returns a timestamp isToday = (date) -> zeroHour(date) == zeroHour(new Date()) isLeapYear = (year) -> year % 4 == 0 and year % 100 != 0 || year % 400 == 0 getDaysInMonth = (year, month) -> s = 30 # short month l = 31 # long month f = (if isLeapYear(year) then 29 else 28) # febraury [l,f,l,s,l,s,l,l,s,l,s,l][month] getWeekNumber = (date) -> onejan = new Date(date.getFullYear(), 0, 1) Math.ceil((((date - onejan) / _msInDay) + onejan.getDay() + 1) / 7) getWeekStart = (date) -> new Date(zeroHour(date) - date.getDay()*_msInDay) getWeekEnd = (weekStartDate) -> new Date(+weekStartDate + (7 * _msInDay) - 1) changeMonth = (date,amount) -> new Date(date.getFullYear(),(date.getMonth() + amount),1) tag = (name,classes,content,data) -> '<'+name+' '+ (if classes then ' class="'+classes+'"' else _eStr)+ (if data then ' data-'+data else _eStr)+'>'+ (if content then content else _eStr) + '</'+name+'>' # Plugin definition $.fn.yacal = ( options ) -> this.each( (index) -> # _date = Current date, _selected = Selected date _date = _selected = null # template & internationalization settings _tpl = {} _i18n = {} # other settings _nearMonths = _wdays = _minDate = _maxDate = _firstDay = _pageSize = _isActive = _dayClass = null # runtime templates parts _weekPart = _monthPart = null # Instance Methods isSelected = (date) -> zeroHour(_selected) == zeroHour(date) isSelectedWeek = (wStart) -> inRange(_selected,wStart,getWeekEnd(wStart)) renderNav = () -> _tpl.nav.replace(_ph.prev,_i18n.prev) .replace(_ph.next,_i18n.next) renderDay = (date) -> _tpl.day.replace(_ph.d, date.getDate()) .replace(_ph.dt, +date) .replace(_ph.wd, date.getDay()) .replace(_ph.we, if isWeekend(date) then ' weekend' else _eStr) .replace(_ph.t, if isToday(date) then ' today' else _eStr) .replace(_ph.s, if isSelected(date) then ' selected' else _eStr) .replace(_ph.a, if inRange(date,_minDate,_maxDate) and _isActive?(date) ? true then ' active' else _eStr) .replace(_ph.dc, ' ' + (_dayClass?(date) ? _eStr)) renderMonth = (date,nav=false) -> d = 0 out = _eStr month = date.getMonth() year = date.getFullYear() totalDays = getDaysInMonth(date.getYear(),date.getMonth()) # weekdays if _wdays wd = 0 out += _weekPart[0].replace(_ph.w,wd) .replace(_ph.wt,_eStr) .replace(_ph.ws,_eStr) while wd <= 6 out += _tpl.weekday.replace(_ph.wdn,_i18n.weekdays[wd]) .replace(_ph.wd,wd++) out += _weekPart[1] # month weeks and days while d < totalDays day = new Date(year,month,d+1) if 0 in [d,day.getDay()] wStart = getWeekStart(day) selWeek = if isSelectedWeek(wStart) then ' selected' else _eStr out += _weekPart[0].replace(_ph.w, getWeekNumber(day)) .replace(_ph.wt, wStart) .replace(_ph.ws, selWeek) d++ out += renderDay(day,_tpl.day) if (d == totalDays || day.getDay() == 6) out += _weekPart[1] # replace placeholders and return the output _monthPart[0].replace(_ph.m,month) .replace(_ph.mnam,_i18n.months[month]) .replace(_ph.y,year) + out + _monthPart[1] renderCalendar = (element,move) -> out = '' cal = $(element) if move _date = changeMonth(_date,move) # Render previous month[s] if _nearMonths pm = _nearMonths while pm > 0 out += renderMonth(changeMonth(_date,-pm)) pm-- # Render selected month out += renderMonth(_date,true); # Render next[s] month[s] if _nearMonths nm = 1 while nm <= _nearMonths out += renderMonth(changeMonth(_date,+nm)) nm++ # add wrap, nav, output, and clearfix to the dom element cal.html('').append($(_tpl.wrap).append(renderNav()) .append(out) .append(_tpl.clearfix)) # Navigation Events nav = cal.find('.yclNav') nav.find('.prev').on 'click', -> renderCalendar(cal, -_pageSize) nav.find('.next').on 'click', -> renderCalendar(cal, _pageSize) # End of instance methods - # get config from defaults opts = $.extend(true,{}, $.fn.yacal.defaults, options ) # get config from data-* atrributes opts = $.extend( true, {}, opts, $(this).data() ) if ($(this).data()) # Config _date = _selected = new Date(opts.date) # Ensures get a date _tpl = opts.tpl _i18n = opts.i18n _nearMonths = +opts.nearMonths _wdays = !!opts.showWeekdays _minDate = new Date(opts.minDate) if opts.minDate _maxDate = new Date(opts.maxDate) if opts.maxDate _pageSize = opts.pageSize ? 1 _isActive = opts.isActive _dayClass = opts.dayClass # _firstDay = +opts.firstDay # TODO _weekPart = _tpl.week.split('|') _monthPart = _tpl.month.split('|') renderCalendar(this) ) # Defaults $.fn.yacal.defaults = date: new Date() nearMonths: 0 showWeekdays: 1 minDate: null maxDate: null firstDay: 0 pageSize: 1 tpl: day: tag('a','day d'+_ph.wd+''+_ph.we+''+_ph.t+''+_ph.s+''+_ph.a+''+_ph.dc, _ph.d,'time="'+_ph.dt+'"') weekday: tag('i','wday wd'+_ph.wd,_ph.wdn) week: tag('div','week w'+_ph.w+_ph.ws,'|','time="'+_ph.wt+'"') month: tag('div','month m'+_ph.m,tag('h4',null,_ph.mnam+' '+_ph.y) + '|') nav: tag('div','yclNav', tag('a','prev',tag('span',null,_ph.prev))+ tag('a','next',tag('span',null,_ph.next))) wrap: tag('div','wrap') clearfix: tag('div','clearfix') i18n: weekdays: ['Su','Mo','Tu','We','Th','Fr','Sa'], months: ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'], prev: 'prev', next: 'next', # Version number $.fn.yacal.version = _version; # Autoinitialize .yacal elements on load $('.' + _name).yacal() )( jQuery, document, window )
true
###! jQuery Yacal Plugin v0.2.0 https://github.com/eduludi/jquery-yacal Authors: - PI:NAME:<NAME>END_PI @eduludi - Some ideas from Pickaday: https://github.com/dbushell/Pikaday (thanks to PI:NAME:<NAME>END_PI @dbushell and PI:NAME:<NAME>END_PI @RamRik) - isLeapYear: PI:NAME:<NAME>END_PI (http://stackoverflow.com/a/4881951) Released under the MIT license ### (( $, doc, win ) -> "use strict" _name = 'yacal' # plugin's name _version = '0.5.0' _msInDay = 86400000 # milliseconds in a day _eStr = '' # empty string # placeholders _ph = d: '#day#' dc: '#dayclass#' dt: '#time#' wd: '#weekday#' we: '#weekend#' t: '#today#' s: '#selected#' a: '#active#' w: '#week#' ws: '#weekSelected#' wt: '#weekTime#' wdn: '#weekdayName#' m: '#month#' mnam: '#monthName#' y: '#year#' nav: '#nav#' prev: '#prev#' next: '#next#' isDate = (obj) -> (/Date/).test(Object.prototype.toString.call(obj)) and !isNaN(+obj) isWeekend = (date) -> date.getDay() in [0,6] inRange = (date,min,max) -> # Validate dates vmi = isDate(min) vmx = isDate(max) if vmi and vmx min <= date and date <= max else if vmi min <= date else if vmx date <= max else true zeroHour = (date) -> date.setHours(0,0,0,0) # !!!: setHours() returns a timestamp isToday = (date) -> zeroHour(date) == zeroHour(new Date()) isLeapYear = (year) -> year % 4 == 0 and year % 100 != 0 || year % 400 == 0 getDaysInMonth = (year, month) -> s = 30 # short month l = 31 # long month f = (if isLeapYear(year) then 29 else 28) # febraury [l,f,l,s,l,s,l,l,s,l,s,l][month] getWeekNumber = (date) -> onejan = new Date(date.getFullYear(), 0, 1) Math.ceil((((date - onejan) / _msInDay) + onejan.getDay() + 1) / 7) getWeekStart = (date) -> new Date(zeroHour(date) - date.getDay()*_msInDay) getWeekEnd = (weekStartDate) -> new Date(+weekStartDate + (7 * _msInDay) - 1) changeMonth = (date,amount) -> new Date(date.getFullYear(),(date.getMonth() + amount),1) tag = (name,classes,content,data) -> '<'+name+' '+ (if classes then ' class="'+classes+'"' else _eStr)+ (if data then ' data-'+data else _eStr)+'>'+ (if content then content else _eStr) + '</'+name+'>' # Plugin definition $.fn.yacal = ( options ) -> this.each( (index) -> # _date = Current date, _selected = Selected date _date = _selected = null # template & internationalization settings _tpl = {} _i18n = {} # other settings _nearMonths = _wdays = _minDate = _maxDate = _firstDay = _pageSize = _isActive = _dayClass = null # runtime templates parts _weekPart = _monthPart = null # Instance Methods isSelected = (date) -> zeroHour(_selected) == zeroHour(date) isSelectedWeek = (wStart) -> inRange(_selected,wStart,getWeekEnd(wStart)) renderNav = () -> _tpl.nav.replace(_ph.prev,_i18n.prev) .replace(_ph.next,_i18n.next) renderDay = (date) -> _tpl.day.replace(_ph.d, date.getDate()) .replace(_ph.dt, +date) .replace(_ph.wd, date.getDay()) .replace(_ph.we, if isWeekend(date) then ' weekend' else _eStr) .replace(_ph.t, if isToday(date) then ' today' else _eStr) .replace(_ph.s, if isSelected(date) then ' selected' else _eStr) .replace(_ph.a, if inRange(date,_minDate,_maxDate) and _isActive?(date) ? true then ' active' else _eStr) .replace(_ph.dc, ' ' + (_dayClass?(date) ? _eStr)) renderMonth = (date,nav=false) -> d = 0 out = _eStr month = date.getMonth() year = date.getFullYear() totalDays = getDaysInMonth(date.getYear(),date.getMonth()) # weekdays if _wdays wd = 0 out += _weekPart[0].replace(_ph.w,wd) .replace(_ph.wt,_eStr) .replace(_ph.ws,_eStr) while wd <= 6 out += _tpl.weekday.replace(_ph.wdn,_i18n.weekdays[wd]) .replace(_ph.wd,wd++) out += _weekPart[1] # month weeks and days while d < totalDays day = new Date(year,month,d+1) if 0 in [d,day.getDay()] wStart = getWeekStart(day) selWeek = if isSelectedWeek(wStart) then ' selected' else _eStr out += _weekPart[0].replace(_ph.w, getWeekNumber(day)) .replace(_ph.wt, wStart) .replace(_ph.ws, selWeek) d++ out += renderDay(day,_tpl.day) if (d == totalDays || day.getDay() == 6) out += _weekPart[1] # replace placeholders and return the output _monthPart[0].replace(_ph.m,month) .replace(_ph.mnam,_i18n.months[month]) .replace(_ph.y,year) + out + _monthPart[1] renderCalendar = (element,move) -> out = '' cal = $(element) if move _date = changeMonth(_date,move) # Render previous month[s] if _nearMonths pm = _nearMonths while pm > 0 out += renderMonth(changeMonth(_date,-pm)) pm-- # Render selected month out += renderMonth(_date,true); # Render next[s] month[s] if _nearMonths nm = 1 while nm <= _nearMonths out += renderMonth(changeMonth(_date,+nm)) nm++ # add wrap, nav, output, and clearfix to the dom element cal.html('').append($(_tpl.wrap).append(renderNav()) .append(out) .append(_tpl.clearfix)) # Navigation Events nav = cal.find('.yclNav') nav.find('.prev').on 'click', -> renderCalendar(cal, -_pageSize) nav.find('.next').on 'click', -> renderCalendar(cal, _pageSize) # End of instance methods - # get config from defaults opts = $.extend(true,{}, $.fn.yacal.defaults, options ) # get config from data-* atrributes opts = $.extend( true, {}, opts, $(this).data() ) if ($(this).data()) # Config _date = _selected = new Date(opts.date) # Ensures get a date _tpl = opts.tpl _i18n = opts.i18n _nearMonths = +opts.nearMonths _wdays = !!opts.showWeekdays _minDate = new Date(opts.minDate) if opts.minDate _maxDate = new Date(opts.maxDate) if opts.maxDate _pageSize = opts.pageSize ? 1 _isActive = opts.isActive _dayClass = opts.dayClass # _firstDay = +opts.firstDay # TODO _weekPart = _tpl.week.split('|') _monthPart = _tpl.month.split('|') renderCalendar(this) ) # Defaults $.fn.yacal.defaults = date: new Date() nearMonths: 0 showWeekdays: 1 minDate: null maxDate: null firstDay: 0 pageSize: 1 tpl: day: tag('a','day d'+_ph.wd+''+_ph.we+''+_ph.t+''+_ph.s+''+_ph.a+''+_ph.dc, _ph.d,'time="'+_ph.dt+'"') weekday: tag('i','wday wd'+_ph.wd,_ph.wdn) week: tag('div','week w'+_ph.w+_ph.ws,'|','time="'+_ph.wt+'"') month: tag('div','month m'+_ph.m,tag('h4',null,_ph.mnam+' '+_ph.y) + '|') nav: tag('div','yclNav', tag('a','prev',tag('span',null,_ph.prev))+ tag('a','next',tag('span',null,_ph.next))) wrap: tag('div','wrap') clearfix: tag('div','clearfix') i18n: weekdays: ['Su','Mo','Tu','We','Th','Fr','Sa'], months: ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'], prev: 'prev', next: 'next', # Version number $.fn.yacal.version = _version; # Autoinitialize .yacal elements on load $('.' + _name).yacal() )( jQuery, document, window )
[ { "context": "'sails-postgresql'\n host: 'localhost'\n user: passwords.db.username\n password: passwords.db.password\n ", "end": 150, "score": 0.6631574630737305, "start": 141, "tag": "USERNAME", "value": "passwords" }, { "context": "esql'\n host: 'localhost'\n user: p...
config/datastores.coffee
nkofl/sails-1.0-template
0
passwords = require './passwords.json' module.exports.datastores = main: adapter: 'sails-postgresql' host: 'localhost' user: passwords.db.username password: passwords.db.password database: 'app_dev' port: 5432
60569
passwords = require './passwords.json' module.exports.datastores = main: adapter: 'sails-postgresql' host: 'localhost' user: passwords.db.username password: <PASSWORD> database: 'app_dev' port: 5432
true
passwords = require './passwords.json' module.exports.datastores = main: adapter: 'sails-postgresql' host: 'localhost' user: passwords.db.username password: PI:PASSWORD:<PASSWORD>END_PI database: 'app_dev' port: 5432
[ { "context": " expect(utils.getQueryVariable('email')).toBe('test@email.com')\n\n it 'returns the given default value if the", "end": 676, "score": 0.9998340606689453, "start": 662, "tag": "EMAIL", "value": "test@email.com" }, { "context": "angen...'\n 'sv':\n ...
test/app/core/utils.spec.coffee
zeen263/codecombat
1
describe 'Utility library', -> utils = require '../../../app/core/utils' describe 'getQueryVariable(param, defaultValue)', -> beforeEach -> spyOn(utils, 'getDocumentSearchString').and.returnValue( '?key=value&bool1=false&bool2=true&email=test%40email.com' ) it 'returns the query parameter', -> expect(utils.getQueryVariable('key')).toBe('value') it 'returns Boolean types if the value is "true" or "false"', -> expect(utils.getQueryVariable('bool1')).toBe(false) expect(utils.getQueryVariable('bool2')).toBe(true) it 'decodes encoded strings', -> expect(utils.getQueryVariable('email')).toBe('test@email.com') it 'returns the given default value if the key is not present', -> expect(utils.getQueryVariable('key', 'other-value')).toBe('value') expect(utils.getQueryVariable('NaN', 'other-value')).toBe('other-value') describe 'i18n', -> beforeEach -> this.fixture1 = 'text': 'G\'day, Wizard! Come to practice? Well, let\'s get started...' 'blurb': 'G\'day' 'i18n': 'es-419': 'text': '¡Buenas, Hechicero! ¿Vienes a practicar? Bueno, empecemos...' 'es-ES': 'text': '¡Buenas Mago! ¿Vienes a practicar? Bien, empecemos...' 'es': 'text': '¡Buenas Mago! ¿Vienes a practicar? Muy bien, empecemos...' 'fr': 'text': 'S\'lut, Magicien! Venu pratiquer? Ok, bien débutons...' 'pt-BR': 'text': 'Bom dia, feiticeiro! Veio praticar? Então vamos começar...' 'en': 'text': 'Ohai Magician!' 'de': 'text': '\'N Tach auch, Zauberer! Kommst Du zum Üben? Dann lass uns anfangen...' 'sv': 'text': 'Godagens, trollkarl! Kommit för att öva? Nå, låt oss börja...' it 'i18n should find a valid target string', -> expect(utils.i18n(this.fixture1, 'text', 'sv')).toEqual(this.fixture1.i18n['sv'].text) expect(utils.i18n(this.fixture1, 'text', 'es-ES')).toEqual(this.fixture1.i18n['es-ES'].text) it 'i18n picks the correct fallback for a specific language', -> expect(utils.i18n(this.fixture1, 'text', 'fr-be')).toEqual(this.fixture1.i18n['fr'].text) it 'i18n picks the correct fallback', -> expect(utils.i18n(this.fixture1, 'text', 'nl')).toEqual(this.fixture1.i18n['en'].text) expect(utils.i18n(this.fixture1, 'text', 'nl', 'de')).toEqual(this.fixture1.i18n['de'].text) it 'i18n falls back to the default text, even for other targets (like blurb)', -> delete this.fixture1.i18n['en'] expect(utils.i18n(this.fixture1, 'text', 'en')).toEqual(this.fixture1.text) expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(this.fixture1.blurb) delete this.fixture1.blurb expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(null) it 'i18n can fall forward if a general language is not found', -> expect(utils.i18n(this.fixture1, 'text', 'pt')).toEqual(this.fixture1.i18n['pt-BR'].text) describe 'inEU', -> it 'EU countries return true', -> euCountries = ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom'] try euCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(true)) catch err # NOTE: without try/catch, exceptions do not yield failed tests. # E.g. utils.inEU used to call Array.find which isn't supported in IE11, try/catch required to register test fail expect(err).not.toBeDefined() it 'non-EU countries return false', -> nonEuCountries = ['united-states', 'peru', 'vietnam'] try nonEuCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(false)) catch err expect(err).not.toBeDefined() describe 'ageOfConsent', -> it 'US is 13', -> expect(utils.ageOfConsent('united-states')).toEqual(13) it 'Latvia is 13', -> expect(utils.ageOfConsent('latvia')).toEqual(13) it 'Austria is 14', -> expect(utils.ageOfConsent('austria')).toEqual(14) it 'Greece is 15', -> expect(utils.ageOfConsent('greece')).toEqual(15) it 'Slovakia is 16', -> expect(utils.ageOfConsent('slovakia')).toEqual(16) it 'default for EU countries 16', -> expect(utils.ageOfConsent('israel')).toEqual(16) it 'default for other countries is 0', -> expect(utils.ageOfConsent('hong-kong')).toEqual(0) it 'default for unknown countries is 0', -> expect(utils.ageOfConsent('codecombat')).toEqual(0) it 'default for undefined countries is 0', -> expect(utils.ageOfConsent(undefined)).toEqual(0) it 'defaultIfUnknown works', -> expect(utils.ageOfConsent(undefined, 13)).toEqual(13) describe 'createLevelNumberMap', -> # r=required p=practice it 'returns correct map for r', -> levels = [ {key: 1, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1']) it 'returns correct map for r r', -> levels = [ {key: 1, practice: false} {key: 2, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '2']) it 'returns correct map for p', -> levels = [ {key: 1, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['0a']) it 'returns correct map for r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '2']) it 'returns correct map for r p p p', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c']) it 'returns correct map for r p p p r p p r r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} {key: 5, practice: false} {key: 6, practice: true} {key: 7, practice: true} {key: 8, practice: false} {key: 9, practice: false} {key: 10, practice: true} {key: 11, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c', '2', '2a', '2b', '3', '4', '4a', '5']) describe 'findNextLevel and findNextAssessmentForLevel', -> # r=required p=practice c=complete *=current a=assessment l=locked # utils.findNextLevel returns next level 0-based index # utils.findNextAssessmentForLevel returns next level 0-based index # Find next available incomplete level, depending on whether practice is needed # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false}] describe 'when no practice needed', -> needsPractice = false it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p r', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p p', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* p rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc* r p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(10) it 'returns correct next levels when rc rc* p p p a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc* p p p ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) describe 'when needs practice', -> needsPractice = true it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* rc', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc pc p rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc pc rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* pc rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false, assessment: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* ac rc pc pc pc a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl* p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl pc* r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1)
221798
describe 'Utility library', -> utils = require '../../../app/core/utils' describe 'getQueryVariable(param, defaultValue)', -> beforeEach -> spyOn(utils, 'getDocumentSearchString').and.returnValue( '?key=value&bool1=false&bool2=true&email=test%40email.com' ) it 'returns the query parameter', -> expect(utils.getQueryVariable('key')).toBe('value') it 'returns Boolean types if the value is "true" or "false"', -> expect(utils.getQueryVariable('bool1')).toBe(false) expect(utils.getQueryVariable('bool2')).toBe(true) it 'decodes encoded strings', -> expect(utils.getQueryVariable('email')).toBe('<EMAIL>') it 'returns the given default value if the key is not present', -> expect(utils.getQueryVariable('key', 'other-value')).toBe('value') expect(utils.getQueryVariable('NaN', 'other-value')).toBe('other-value') describe 'i18n', -> beforeEach -> this.fixture1 = 'text': 'G\'day, Wizard! Come to practice? Well, let\'s get started...' 'blurb': 'G\'day' 'i18n': 'es-419': 'text': '¡Buenas, Hechicero! ¿Vienes a practicar? Bueno, empecemos...' 'es-ES': 'text': '¡Buenas Mago! ¿Vienes a practicar? Bien, empecemos...' 'es': 'text': '¡Buenas Mago! ¿Vienes a practicar? Muy bien, empecemos...' 'fr': 'text': 'S\'lut, Magicien! Venu pratiquer? Ok, bien débutons...' 'pt-BR': 'text': 'Bom dia, feiticeiro! Veio praticar? Então vamos começar...' 'en': 'text': 'Ohai Magician!' 'de': 'text': '\'N Tach auch, Zauberer! Kommst Du zum Üben? Dann lass uns anfangen...' 'sv': 'text': 'God<NAME>, t<NAME>! Kommit för att öva? Nå, låt oss börja...' it 'i18n should find a valid target string', -> expect(utils.i18n(this.fixture1, 'text', 'sv')).toEqual(this.fixture1.i18n['sv'].text) expect(utils.i18n(this.fixture1, 'text', 'es-ES')).toEqual(this.fixture1.i18n['es-ES'].text) it 'i18n picks the correct fallback for a specific language', -> expect(utils.i18n(this.fixture1, 'text', 'fr-be')).toEqual(this.fixture1.i18n['fr'].text) it 'i18n picks the correct fallback', -> expect(utils.i18n(this.fixture1, 'text', 'nl')).toEqual(this.fixture1.i18n['en'].text) expect(utils.i18n(this.fixture1, 'text', 'nl', 'de')).toEqual(this.fixture1.i18n['de'].text) it 'i18n falls back to the default text, even for other targets (like blurb)', -> delete this.fixture1.i18n['en'] expect(utils.i18n(this.fixture1, 'text', 'en')).toEqual(this.fixture1.text) expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(this.fixture1.blurb) delete this.fixture1.blurb expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(null) it 'i18n can fall forward if a general language is not found', -> expect(utils.i18n(this.fixture1, 'text', 'pt')).toEqual(this.fixture1.i18n['pt-BR'].text) describe 'inEU', -> it 'EU countries return true', -> euCountries = ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom'] try euCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(true)) catch err # NOTE: without try/catch, exceptions do not yield failed tests. # E.g. utils.inEU used to call Array.find which isn't supported in IE11, try/catch required to register test fail expect(err).not.toBeDefined() it 'non-EU countries return false', -> nonEuCountries = ['united-states', 'peru', 'vietnam'] try nonEuCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(false)) catch err expect(err).not.toBeDefined() describe 'ageOfConsent', -> it 'US is 13', -> expect(utils.ageOfConsent('united-states')).toEqual(13) it 'Latvia is 13', -> expect(utils.ageOfConsent('latvia')).toEqual(13) it 'Austria is 14', -> expect(utils.ageOfConsent('austria')).toEqual(14) it 'Greece is 15', -> expect(utils.ageOfConsent('greece')).toEqual(15) it 'Slovakia is 16', -> expect(utils.ageOfConsent('slovakia')).toEqual(16) it 'default for EU countries 16', -> expect(utils.ageOfConsent('israel')).toEqual(16) it 'default for other countries is 0', -> expect(utils.ageOfConsent('hong-kong')).toEqual(0) it 'default for unknown countries is 0', -> expect(utils.ageOfConsent('codecombat')).toEqual(0) it 'default for undefined countries is 0', -> expect(utils.ageOfConsent(undefined)).toEqual(0) it 'defaultIfUnknown works', -> expect(utils.ageOfConsent(undefined, 13)).toEqual(13) describe 'createLevelNumberMap', -> # r=required p=practice it 'returns correct map for r', -> levels = [ {key: 1, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1']) it 'returns correct map for r r', -> levels = [ {key: 1, practice: false} {key: 2, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '2']) it 'returns correct map for p', -> levels = [ {key: 1, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['0a']) it 'returns correct map for r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '2']) it 'returns correct map for r p p p', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c']) it 'returns correct map for r p p p r p p r r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} {key: 5, practice: false} {key: 6, practice: true} {key: 7, practice: true} {key: 8, practice: false} {key: 9, practice: false} {key: 10, practice: true} {key: 11, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c', '2', '2a', '2b', '3', '4', '4a', '5']) describe 'findNextLevel and findNextAssessmentForLevel', -> # r=required p=practice c=complete *=current a=assessment l=locked # utils.findNextLevel returns next level 0-based index # utils.findNextAssessmentForLevel returns next level 0-based index # Find next available incomplete level, depending on whether practice is needed # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false}] describe 'when no practice needed', -> needsPractice = false it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p r', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p p', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* p rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc* r p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(10) it 'returns correct next levels when rc rc* p p p a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc* p p p ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) describe 'when needs practice', -> needsPractice = true it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* rc', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc pc p rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc pc rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* pc rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false, assessment: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* ac rc pc pc pc a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl* p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl pc* r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1)
true
describe 'Utility library', -> utils = require '../../../app/core/utils' describe 'getQueryVariable(param, defaultValue)', -> beforeEach -> spyOn(utils, 'getDocumentSearchString').and.returnValue( '?key=value&bool1=false&bool2=true&email=test%40email.com' ) it 'returns the query parameter', -> expect(utils.getQueryVariable('key')).toBe('value') it 'returns Boolean types if the value is "true" or "false"', -> expect(utils.getQueryVariable('bool1')).toBe(false) expect(utils.getQueryVariable('bool2')).toBe(true) it 'decodes encoded strings', -> expect(utils.getQueryVariable('email')).toBe('PI:EMAIL:<EMAIL>END_PI') it 'returns the given default value if the key is not present', -> expect(utils.getQueryVariable('key', 'other-value')).toBe('value') expect(utils.getQueryVariable('NaN', 'other-value')).toBe('other-value') describe 'i18n', -> beforeEach -> this.fixture1 = 'text': 'G\'day, Wizard! Come to practice? Well, let\'s get started...' 'blurb': 'G\'day' 'i18n': 'es-419': 'text': '¡Buenas, Hechicero! ¿Vienes a practicar? Bueno, empecemos...' 'es-ES': 'text': '¡Buenas Mago! ¿Vienes a practicar? Bien, empecemos...' 'es': 'text': '¡Buenas Mago! ¿Vienes a practicar? Muy bien, empecemos...' 'fr': 'text': 'S\'lut, Magicien! Venu pratiquer? Ok, bien débutons...' 'pt-BR': 'text': 'Bom dia, feiticeiro! Veio praticar? Então vamos começar...' 'en': 'text': 'Ohai Magician!' 'de': 'text': '\'N Tach auch, Zauberer! Kommst Du zum Üben? Dann lass uns anfangen...' 'sv': 'text': 'GodPI:NAME:<NAME>END_PI, tPI:NAME:<NAME>END_PI! Kommit för att öva? Nå, låt oss börja...' it 'i18n should find a valid target string', -> expect(utils.i18n(this.fixture1, 'text', 'sv')).toEqual(this.fixture1.i18n['sv'].text) expect(utils.i18n(this.fixture1, 'text', 'es-ES')).toEqual(this.fixture1.i18n['es-ES'].text) it 'i18n picks the correct fallback for a specific language', -> expect(utils.i18n(this.fixture1, 'text', 'fr-be')).toEqual(this.fixture1.i18n['fr'].text) it 'i18n picks the correct fallback', -> expect(utils.i18n(this.fixture1, 'text', 'nl')).toEqual(this.fixture1.i18n['en'].text) expect(utils.i18n(this.fixture1, 'text', 'nl', 'de')).toEqual(this.fixture1.i18n['de'].text) it 'i18n falls back to the default text, even for other targets (like blurb)', -> delete this.fixture1.i18n['en'] expect(utils.i18n(this.fixture1, 'text', 'en')).toEqual(this.fixture1.text) expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(this.fixture1.blurb) delete this.fixture1.blurb expect(utils.i18n(this.fixture1, 'blurb', 'en')).toEqual(null) it 'i18n can fall forward if a general language is not found', -> expect(utils.i18n(this.fixture1, 'text', 'pt')).toEqual(this.fixture1.i18n['pt-BR'].text) describe 'inEU', -> it 'EU countries return true', -> euCountries = ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom'] try euCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(true)) catch err # NOTE: without try/catch, exceptions do not yield failed tests. # E.g. utils.inEU used to call Array.find which isn't supported in IE11, try/catch required to register test fail expect(err).not.toBeDefined() it 'non-EU countries return false', -> nonEuCountries = ['united-states', 'peru', 'vietnam'] try nonEuCountries.forEach((c) -> expect(utils.inEU(c)).toEqual(false)) catch err expect(err).not.toBeDefined() describe 'ageOfConsent', -> it 'US is 13', -> expect(utils.ageOfConsent('united-states')).toEqual(13) it 'Latvia is 13', -> expect(utils.ageOfConsent('latvia')).toEqual(13) it 'Austria is 14', -> expect(utils.ageOfConsent('austria')).toEqual(14) it 'Greece is 15', -> expect(utils.ageOfConsent('greece')).toEqual(15) it 'Slovakia is 16', -> expect(utils.ageOfConsent('slovakia')).toEqual(16) it 'default for EU countries 16', -> expect(utils.ageOfConsent('israel')).toEqual(16) it 'default for other countries is 0', -> expect(utils.ageOfConsent('hong-kong')).toEqual(0) it 'default for unknown countries is 0', -> expect(utils.ageOfConsent('codecombat')).toEqual(0) it 'default for undefined countries is 0', -> expect(utils.ageOfConsent(undefined)).toEqual(0) it 'defaultIfUnknown works', -> expect(utils.ageOfConsent(undefined, 13)).toEqual(13) describe 'createLevelNumberMap', -> # r=required p=practice it 'returns correct map for r', -> levels = [ {key: 1, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1']) it 'returns correct map for r r', -> levels = [ {key: 1, practice: false} {key: 2, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '2']) it 'returns correct map for p', -> levels = [ {key: 1, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['0a']) it 'returns correct map for r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '2']) it 'returns correct map for r p p p', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c']) it 'returns correct map for r p p p r p p r r p r', -> levels = [ {key: 1, practice: false} {key: 2, practice: true} {key: 3, practice: true} {key: 4, practice: true} {key: 5, practice: false} {key: 6, practice: true} {key: 7, practice: true} {key: 8, practice: false} {key: 9, practice: false} {key: 10, practice: true} {key: 11, practice: false} ] levelNumberMap = utils.createLevelNumberMap(levels) expect((val.toString() for key, val of levelNumberMap)).toEqual(['1', '1a', '1b', '1c', '2', '2a', '2b', '3', '4', '4a', '5']) describe 'findNextLevel and findNextAssessmentForLevel', -> # r=required p=practice c=complete *=current a=assessment l=locked # utils.findNextLevel returns next level 0-based index # utils.findNextAssessmentForLevel returns next level 0-based index # Find next available incomplete level, depending on whether practice is needed # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false}] describe 'when no practice needed', -> needsPractice = false it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p r', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when pc* p p', -> levels = [ {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* p rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc* r p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(10) it 'returns correct next levels when rc rc* p p p a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc* p p p ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) describe 'when needs practice', -> needsPractice = true it 'returns correct next levels when rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* rc', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(1) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc*', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rc* a r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: false, assessment: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(3) it 'returns correct next levels when rc pc p rc* p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc p rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(5) expect(utils.findNextAssessmentForLevel(levels, 3)).toEqual(-1) it 'returns correct next levels when rc pc pc rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(4) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc* pc rc', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: false, complete: true} ] expect(utils.findNextLevel(levels, 0, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 3, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* r p', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false, assessment: true} {practice: false, complete: true} {practice: false, complete: false} {practice: true, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc pc p a rc* pc p r', -> levels = [ {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* p p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(2) expect(utils.findNextAssessmentForLevel(levels, 1, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc* p p a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(3) expect(utils.findNextAssessmentForLevel(levels, 2, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac rc* p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 6, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 6, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* ac rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc* a rc p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: true} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(7) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(5) it 'returns correct next levels when rc rc pc pc pc* ac rc pc pc pc a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 4, needsPractice)).toEqual(11) expect(utils.findNextAssessmentForLevel(levels, 4, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc pc pc pc ac* r p p p a r r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: true, complete: true} {practice: true, complete: true} {practice: true, complete: true} {assessment: true, complete: true} {practice: false, complete: false} {practice: true, complete: false} {practice: true, complete: false} {practice: true, complete: false} {assessment: true, complete: false} {practice: false, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 5, needsPractice)).toEqual(6) expect(utils.findNextAssessmentForLevel(levels, 5, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc* rcl p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 1, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl* p r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: false} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 2, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1) it 'returns correct next levels when rc rc rcl pc* r', -> levels = [ {practice: false, complete: true} {practice: false, complete: true} {practice: false, complete: true, locked: true} {practice: true, complete: true} {practice: false, complete: false} ] expect(utils.findNextLevel(levels, 3, needsPractice)).toEqual(-1) expect(utils.findNextAssessmentForLevel(levels, 0, needsPractice)).toEqual(-1)
[ { "context": "'\n\nexports.test1 = (T, cb) ->\n input = \"\"\"\npub:u:2048:1:CC19461E16CD52C8:1388413669:1703773669::u:::scES", "end": 90, "score": 0.7105264067649841, "start": 86, "tag": "IP_ADDRESS", "value": "2048" }, { "context": "orts.test1 = (T, cb) ->\n input = \"\"\"\npub:u...
node_modules/gpg-wrapper/test/files/colgrep.iced
AngelKey/Angelkey.nodeinstaller
151
{colgrep} = require '../../lib/main' exports.test1 = (T, cb) -> input = """ pub:u:2048:1:CC19461E16CD52C8:1388413669:1703773669::u:::scESC: uid:u::::1388413669::4A1C93DDE1779B6BE90393F4394AD983EC785808::Brown Hat I (pw is 'a') <themax+browhat1@gmail.com>: sub:u:2048:1:079F6793014A5F79:1388413669:1703773669:::::e: pub:f:1024:1:5308C23E96D307BE:1387294526:1702654526::-:::escaESCA: uid:f::::1387294526::9A7B91D6B62DC24454C408CB4D98210A31F4235F::keybase.io/taco1 (v0.0.1) <taco1@keybase.io>: sub:f:1024:1:5F8664C8B707AD86:1387294526:1418830526:::::esa: pub:-:1024:1:361D07D32CDF514E:1389274486:1704634486::-:::escaESCA: uid:-::::1389274486::039EE0C3AD2BCAFEA038A768F4288963FDD7C1E6::keybase.io/taco19 (v0.0.1) <taco19@keybase.io>: sub:-:1024:1:6F61BAE56CA1B67A:1389274486:1420810486:::::esa: """ res = colgrep { patterns : { 0 : /pub|sub/ 4 : /A.*7/ }, buffer : (new Buffer input, 'utf8') separator : /:/ } T.equal res[0]?[4], '079F6793014A5F79', 'first row found' T.equal res[1]?[4], '6F61BAE56CA1B67A', '2nd row found' cb()
120564
{colgrep} = require '../../lib/main' exports.test1 = (T, cb) -> input = """ pub:u:2048:1:CC19461E16CD52C8:1388413669:1703773669::u:::scESC: uid:u::::1388413669::4A1C93DDE1779B6BE90393F4394AD983EC785808::Brown Hat I (pw is 'a') <<EMAIL>>: sub:u:2048:1:079F6793014A5F79:1388413669:1703773669:::::e: pub:f:1024:1:<KEY>:1387294526:1702654526::-:::escaESCA: uid:f::::1387294526::9A7B91D6B62DC24454C408CB4D98210A31F4235F::keybase.io/taco1 (v0.0.1) <<EMAIL>>: sub:f:1024:1:5F8664C8B707AD86:1387294526:1418830526:::::esa: pub:-:1024:1:<KEY>:1<KEY>:1<KEY>6::-:::escaESCA: uid:-::::1389274486::039EE0C3AD2BCAFEA038A768F4288963FDD7C1E6::keybase.io/taco19 (v0.0.1) <<EMAIL>>: sub:-:1024:1:6F61BAE56CA1B67A:1389274486:1420810486:::::esa: """ res = colgrep { patterns : { 0 : /pub|sub/ 4 : /A.*7/ }, buffer : (new Buffer input, 'utf8') separator : /:/ } T.equal res[0]?[4], '079F6793014A5F79', 'first row found' T.equal res[1]?[4], '6F61BAE56CA1B67A', '2nd row found' cb()
true
{colgrep} = require '../../lib/main' exports.test1 = (T, cb) -> input = """ pub:u:2048:1:CC19461E16CD52C8:1388413669:1703773669::u:::scESC: uid:u::::1388413669::4A1C93DDE1779B6BE90393F4394AD983EC785808::Brown Hat I (pw is 'a') <PI:EMAIL:<EMAIL>END_PI>: sub:u:2048:1:079F6793014A5F79:1388413669:1703773669:::::e: pub:f:1024:1:PI:KEY:<KEY>END_PI:1387294526:1702654526::-:::escaESCA: uid:f::::1387294526::9A7B91D6B62DC24454C408CB4D98210A31F4235F::keybase.io/taco1 (v0.0.1) <PI:EMAIL:<EMAIL>END_PI>: sub:f:1024:1:5F8664C8B707AD86:1387294526:1418830526:::::esa: pub:-:1024:1:PI:KEY:<KEY>END_PI:1PI:KEY:<KEY>END_PI:1PI:KEY:<KEY>END_PI6::-:::escaESCA: uid:-::::1389274486::039EE0C3AD2BCAFEA038A768F4288963FDD7C1E6::keybase.io/taco19 (v0.0.1) <PI:EMAIL:<EMAIL>END_PI>: sub:-:1024:1:6F61BAE56CA1B67A:1389274486:1420810486:::::esa: """ res = colgrep { patterns : { 0 : /pub|sub/ 4 : /A.*7/ }, buffer : (new Buffer input, 'utf8') separator : /:/ } T.equal res[0]?[4], '079F6793014A5F79', 'first row found' T.equal res[1]?[4], '6F61BAE56CA1B67A', '2nd row found' cb()
[ { "context": ": 'Parameters'\n Password:\n body: 'Password=${1}$0'\n prefix: 'Password'\n PrivilegesRequired:\n ", "end": 23108, "score": 0.727887749671936, "start": 23106, "tag": "PASSWORD", "value": "$0" } ]
snippets/inno-setup.cson
idleberg/language-inno
1
'.source.inno': '32bit': body: '32bit$0' prefix: '32bit' '64bit': body: '64bit$0' prefix: '64bit' 'AllowCancelDuringInstall=no': body: 'AllowCancelDuringInstall=no$0' prefix: 'AllowCancelDuringInstall=no' 'AllowCancelDuringInstall=yes (default)': body: 'AllowCancelDuringInstall=yes$0' prefix: 'AllowCancelDuringInstall=yes (default)' 'AllowNetworkDrive=no': body: 'AllowNetworkDrive=no$0' prefix: 'AllowNetworkDrive=no' 'AllowNetworkDrive=yes (default)': body: 'AllowNetworkDrive=yes$0' prefix: 'AllowNetworkDrive=yes (default)' 'AllowNoIcons=no (default)': body: 'AllowNoIcons=no$0' prefix: 'AllowNoIcons=no (default)' 'AllowNoIcons=yes': body: 'AllowNoIcons=yes$0' prefix: 'AllowNoIcons=yes' 'AllowRootDirectory=no (default)': body: 'AllowRootDirectory=no$0' prefix: 'AllowRootDirectory=no (default)' 'AllowRootDirectory=yes': body: 'AllowRootDirectory=yes$0' prefix: 'AllowRootDirectory=yes' 'AllowUNCPath=no': body: 'AllowUNCPath=no$0' prefix: 'AllowUNCPath=no' 'AllowUNCPath=yes (default)': body: 'AllowUNCPath=yes$0' prefix: 'AllowUNCPath=yes (default)' 'AlwaysRestart=no (default)': body: 'AlwaysRestart=no$0' prefix: 'AlwaysRestart=no (default)' 'AlwaysRestart=yes': body: 'AlwaysRestart=yes$0' prefix: 'AlwaysRestart=yes' 'AlwaysShowComponentsList=no': body: 'AlwaysShowComponentsList=no$0' prefix: 'AlwaysShowComponentsList=no' 'AlwaysShowComponentsList=yes (default)': body: 'AlwaysShowComponentsList=yes$0' prefix: 'AlwaysShowComponentsList=yes (default)' 'AlwaysShowDirOnReadyPage=no (default)': body: 'AlwaysShowDirOnReadyPage=no$0' prefix: 'AlwaysShowDirOnReadyPage=no (default)' 'AlwaysShowDirOnReadyPage=yes': body: 'AlwaysShowDirOnReadyPage=yes$0' prefix: 'AlwaysShowDirOnReadyPage=yes' 'AlwaysShowGroupOnReadyPage=no (default)': body: 'AlwaysShowGroupOnReadyPage=no$0' prefix: 'AlwaysShowGroupOnReadyPage=no (default)' 'AlwaysShowGroupOnReadyPage=yes': body: 'AlwaysShowGroupOnReadyPage=yes$0' prefix: 'AlwaysShowGroupOnReadyPage=yes' 'AlwaysUsePersonalGroup=no (default)': body: 'AlwaysUsePersonalGroup=no$0' prefix: 'AlwaysUsePersonalGroup=no (default)' 'AlwaysUsePersonalGroup=yes': body: 'AlwaysUsePersonalGroup=yes$0' prefix: 'AlwaysUsePersonalGroup=yes' 'AppendDefaultDirName=no': body: 'AppendDefaultDirName=no$0' prefix: 'AppendDefaultDirName=no' 'AppendDefaultDirName=yes (default)': body: 'AppendDefaultDirName=yes$0' prefix: 'AppendDefaultDirName=yes (default)' 'AppendDefaultGroupName=no': body: 'AppendDefaultGroupName=no$0' prefix: 'AppendDefaultGroupName=no' 'AppendDefaultGroupName=yes (default)': body: 'AppendDefaultGroupName=yes$0' prefix: 'AppendDefaultGroupName=yes (default)' 'ChangesAssociations=no (default)': body: 'ChangesAssociations=no$0' prefix: 'ChangesAssociations=no (default)' 'ChangesAssociations=yes': body: 'ChangesAssociations=yes$0' prefix: 'ChangesAssociations=yes' 'ChangesEnvironment=no (default)': body: 'ChangesEnvironment=no$0' prefix: 'ChangesEnvironment=no (default)' 'ChangesEnvironment=yes': body: 'ChangesEnvironment=yes$0' prefix: 'ChangesEnvironment=yes' 'CloseApplications=no': body: 'CloseApplications=no$0' prefix: 'CloseApplications=no' 'CloseApplications=yes (default)': body: 'CloseApplications=yes$0' prefix: 'CloseApplications=yes (default)' 'CreateAppDir=no': body: 'CreateAppDir=no$0' prefix: 'CreateAppDir=no' 'CreateAppDir=yes (default)': body: 'CreateAppDir=yes$0' prefix: 'CreateAppDir=yes (default)' 'CreateUninstallRegKey=no': body: 'CreateUninstallRegKey=no$0' prefix: 'CreateUninstallRegKey=no' 'CreateUninstallRegKey=yes (default)': body: 'CreateUninstallRegKey=yes$0' prefix: 'CreateUninstallRegKey=yes (default)' 'DirExistsWarning=auto (default)': body: 'DirExistsWarning=auto$0' prefix: 'DirExistsWarning=auto (default)' 'DirExistsWarning=no': body: 'DirExistsWarning=no$0' prefix: 'DirExistsWarning=no' 'DirExistsWarning=yes': body: 'DirExistsWarning=yes$0' prefix: 'DirExistsWarning=yes' 'DisableDirPage=auto': body: 'DisableDirPage=yes$0' prefix: 'DisableDirPage=auto' 'DisableDirPage=no (default)': body: 'DisableDirPage=no$0' prefix: 'DisableDirPage=no (default)' 'DisableFinishedPage=no (default)': body: 'DisableFinishedPage=no$0' prefix: 'DisableFinishedPage=no (default)' 'DisableFinishedPage=yes': body: 'DisableFinishedPage=yes$0' prefix: 'DisableFinishedPage=yes' 'DisableProgramGroupPage=auto': body: 'DisableProgramGroupPage=auto$0' prefix: 'DisableProgramGroupPage=auto' 'DisableProgramGroupPage=no (default)': body: 'DisableProgramGroupPage=no$0' prefix: 'DisableProgramGroupPage=no (default)' 'DisableProgramGroupPage=yes': body: 'DisableProgramGroupPage=yes$0' prefix: 'DisableProgramGroupPage=yes' 'DisableReadyMemo=no (default)': body: 'DisableReadyMemo=no$0' prefix: 'DisableReadyMemo=no (default)' 'DisableReadyMemo=yes': body: 'DisableReadyMemo=yes$0' prefix: 'DisableReadyMemo=yes' 'DisableReadyPage=no (default)': body: 'DisableReadyPage=no$0' prefix: 'DisableReadyPage=no (default)' 'DisableReadyPage=yes': body: 'DisableReadyPage=yes$0' prefix: 'DisableReadyPage=yes' 'DisableStartupPrompt=no': body: 'DisableStartupPrompt=no$0' prefix: 'DisableStartupPrompt=no' 'DisableStartupPrompt=yes (default)': body: 'DisableStartupPrompt=yes$0' prefix: 'DisableStartupPrompt=yes (default)' 'DisableWelcomePage=no': body: 'DisableWelcomePage=no$0' prefix: 'DisableWelcomePage=no' 'DisableWelcomePage=yes (default)': body: 'DisableWelcomePage=yes$0' prefix: 'DisableWelcomePage=yes (default)' 'DiskSpanning=no (default)': body: 'DiskSpanning=no$0' prefix: 'DiskSpanning=no (default)' 'DiskSpanning=yes': body: 'DiskSpanning=yes$0' prefix: 'DiskSpanning=yes' 'EnableDirDoesntExistWarning=no (default)': body: 'EnableDirDoesntExistWarning=no$0' prefix: 'EnableDirDoesntExistWarning=no (default)' 'EnableDirDoesntExistWarning=yes': body: 'EnableDirDoesntExistWarning=yes$0' prefix: 'EnableDirDoesntExistWarning=yes' 'FlatComponentsList=no': body: 'FlatComponentsList=no$0' prefix: 'FlatComponentsList=no' 'FlatComponentsList=yes (default)': body: 'FlatComponentsList=yes$0' prefix: 'FlatComponentsList=yes (default)' 'LZMAAlgorithm=0 (default)': body: 'LZMAAlgorithm=0$0' prefix: 'LZMAAlgorithm=0 (default)' 'LZMAAlgorithm=1': body: 'LZMAAlgorithm=1$0' prefix: 'LZMAAlgorithm=1' 'LZMAMatchFinder=BT': body: 'LZMAMatchFinder=BT$0' prefix: 'LZMAMatchFinder=BT' 'LZMAMatchFinder=HC': body: 'LZMAMatchFinder=HC$0' prefix: 'LZMAMatchFinder=HC' 'LZMAUseSeparateProcess=no (default)': body: 'LZMAUseSeparateProcess=no$0' prefix: 'LZMAUseSeparateProcess=no (default)' 'LZMAUseSeparateProcess=x86': body: 'LZMAUseSeparateProcess=x86$0' prefix: 'LZMAUseSeparateProcess=x86' 'LZMAUseSeparateProcess=yes': body: 'LZMAUseSeparateProcess=yes$0' prefix: 'LZMAUseSeparateProcess=yes' 'LanguageDetectionMethod=locale': body: 'LanguageDetectionMethod=locale$0' prefix: 'LanguageDetectionMethod=locale' 'LanguageDetectionMethod=none': body: 'LanguageDetectionMethod=none$0' prefix: 'LanguageDetectionMethod=none' 'LanguageDetectionMethod=uilanguage (default)': body: 'LanguageDetectionMethod=uilanguage$0' prefix: 'LanguageDetectionMethod=uilanguage (default)' 'MergeDuplicateFiles=no': body: 'MergeDuplicateFiles=no$0' prefix: 'MergeDuplicateFiles=no' 'MergeDuplicateFiles=yes (default)': body: 'MergeDuplicateFiles=yes$0' prefix: 'MergeDuplicateFiles=yes (default)' 'Output=no': body: 'Output=no$0' prefix: 'Output=no' 'Output=yes': body: 'Output=yes$0' prefix: 'Output=yes' 'PrivilegesRequired=admin (default)': body: 'PrivilegesRequired=admin$0' prefix: 'PrivilegesRequired=admin (default)' 'PrivilegesRequired=lowest': body: 'PrivilegesRequired=lowest$0' prefix: 'PrivilegesRequired=lowest' 'PrivilegesRequired=none': body: 'PrivilegesRequired=none$0' prefix: 'PrivilegesRequired=none' 'PrivilegesRequired=poweruser': body: 'PrivilegesRequired=poweruser$0' prefix: 'PrivilegesRequired=poweruser' 'RestartApplications=no': body: 'RestartApplications=no$0' prefix: 'RestartApplications=no' 'RestartApplications=yes (default)': body: 'RestartApplications=yes$0' prefix: 'RestartApplications=yes (default)' 'RestartIfNeededByRun=no': body: 'RestartIfNeededByRun=no$0' prefix: 'RestartIfNeededByRun=no' 'RestartIfNeededByRun=yes (default)': body: 'RestartIfNeededByRun=yes$0' prefix: 'RestartIfNeededByRun=yes (default)' 'SetupLogging=no (default)': body: 'SetupLogging=no$0' prefix: 'SetupLogging=no (default)' 'SetupLogging=yes': body: 'SetupLogging=yes$0' prefix: 'SetupLogging=yes' 'ShowComponentSizes=no': body: 'ShowComponentSizes=no$0' prefix: 'ShowComponentSizes=no' 'ShowComponentSizes=yes (default)': body: 'ShowComponentSizes=yes$0' prefix: 'ShowComponentSizes=yes (default)' 'ShowLanguageDialog=auto': body: 'ShowLanguageDialog=auto$0' prefix: 'ShowLanguageDialog=auto' 'ShowLanguageDialog=no': body: 'ShowLanguageDialog=no$0' prefix: 'ShowLanguageDialog=no' 'ShowLanguageDialog=yes (default)': body: 'ShowLanguageDialog=yes$0' prefix: 'ShowLanguageDialog=yes (default)' 'ShowUndisplayableLanguages=no (default)': body: 'ShowUndisplayableLanguages=no$0' prefix: 'ShowUndisplayableLanguages=no (default)' 'ShowUndisplayableLanguages=yes': body: 'ShowUndisplayableLanguages=yes$0' prefix: 'ShowUndisplayableLanguages=yes' 'SignedUninstaller=no': body: 'SignedUninstaller=no$0' prefix: 'SignedUninstaller=no' 'SignedUninstaller=yes (default)': body: 'SignedUninstaller=yes$0' prefix: 'SignedUninstaller=yes (default)' 'SolidCompression=no (default)': body: 'SolidCompression=no$0' prefix: 'SolidCompression=no (default)' 'SolidCompression=yes': body: 'SolidCompression=yes$0' prefix: 'SolidCompression=yes' 'TerminalServicesAware=no': body: 'TerminalServicesAware=no$0' prefix: 'TerminalServicesAware=no' 'TerminalServicesAware=yes (default)': body: 'TerminalServicesAware=yes$0' prefix: 'TerminalServicesAware=yes (default)' 'TimeStampsInUTC=no (default)': body: 'TimeStampsInUTC=no$0' prefix: 'TimeStampsInUTC=no (default)' 'TimeStampsInUTC=yes': body: 'TimeStampsInUTC=yes$0' prefix: 'TimeStampsInUTC=yes' 'UninstallLogMode=append (default)': body: 'UninstallLogMode=append$0' prefix: 'UninstallLogMode=append (default)' 'UninstallLogMode=new': body: 'UninstallLogMode=new$0' prefix: 'UninstallLogMode=new' 'UninstallLogMode=overwrite': body: 'UninstallLogMode=overwrite$0' prefix: 'UninstallLogMode=overwrite' 'UninstallRestartComputer=no (default)': body: 'UninstallRestartComputer=no$0' prefix: 'UninstallRestartComputer=no (default)' 'UninstallRestartComputer=yes': body: 'UninstallRestartComputer=yes$0' prefix: 'UninstallRestartComputer=yes' 'UpdateUninstallLogAppName=no': body: 'UpdateUninstallLogAppName=no$0' prefix: 'UpdateUninstallLogAppName=no' 'UpdateUninstallLogAppName=yes (default)': body: 'UpdateUninstallLogAppName=yes$0' prefix: 'UpdateUninstallLogAppName=yes (default)' 'UsePreviousAppDir=no': body: 'UsePreviousAppDir=no$0' prefix: 'UsePreviousAppDir=no' 'UsePreviousAppDir=yes (default)': body: 'UsePreviousAppDir=yes$0' prefix: 'UsePreviousAppDir=yes (default)' 'UsePreviousGroup=no': body: 'UsePreviousGroup=no$0' prefix: 'UsePreviousGroup=no' 'UsePreviousGroup=yes (default)': body: 'UsePreviousGroup=yes$0' prefix: 'UsePreviousGroup=yes (default)' 'UsePreviousLanguage=no': body: 'UsePreviousLanguage=no$0' prefix: 'UsePreviousLanguage=no' 'UsePreviousLanguage=yes (default)': body: 'UsePreviousLanguage=yes$0' prefix: 'UsePreviousLanguage=yes (default)' 'UsePreviousSetupType=no': body: 'UsePreviousSetupType=no$0' prefix: 'UsePreviousSetupType=no' 'UsePreviousSetupType=yes (default)': body: 'UsePreviousSetupType=yes$0' prefix: 'UsePreviousSetupType=yes (default)' 'UsePreviousTasks=no': body: 'UsePreviousTasks=no$0' prefix: 'UsePreviousTasks=no' 'UsePreviousTasks=yes (default)': body: 'UsePreviousTasks=yes$0' prefix: 'UsePreviousTasks=yes (default)' 'UsePreviousUserInfo=no': body: 'UsePreviousUserInfo=no$0' prefix: 'UsePreviousUserInfo=no' 'UsePreviousUserInfo=yes (default)': body: 'UsePreviousUserInfo=yes$0' prefix: 'UsePreviousUserInfo=yes (default)' 'UseSetupLdr=no': body: 'UseSetupLdr=no$0' prefix: 'UseSetupLdr=no' 'UseSetupLdr=yes (default)': body: 'UseSetupLdr=yes$0' prefix: 'UseSetupLdr=yes (default)' 'UserInfoPage=no (default)': body: 'UserInfoPage=no$0' prefix: 'UserInfoPage=no (default)' 'UserInfoPage=yes': body: 'UserInfoPage=yes$0' prefix: 'UserInfoPage=yes' 'WindowResizable=no': body: 'WindowResizable=no$0' prefix: 'WindowResizable=no' 'WindowResizable=yes (default)': body: 'WindowResizable=yes$0' prefix: 'WindowResizable=yes (default)' 'WindowShowCaption=no': body: 'WindowShowCaption=no$0' prefix: 'WindowShowCaption=no' 'WindowShowCaption=yes (default)': body: 'WindowShowCaption=yes$0' prefix: 'WindowShowCaption=yes (default)' 'WindowStartMaximized=no': body: 'WindowStartMaximized=no$0' prefix: 'WindowStartMaximized=no' 'WindowStartMaximized=yes (default)': body: 'WindowStartMaximized=yes$0' prefix: 'WindowStartMaximized=yes (default)' 'WindowVisible=no (default)': body: 'WindowVisible=no$0' prefix: 'WindowVisible=no (default)' 'WindowVisible=yes': body: 'WindowVisible=yes$0' prefix: 'WindowVisible=yes' 'WizardImageStretch=no': body: 'WizardImageStretch=no$0' prefix: 'WizardImageStretch=no' 'WizardImageStretch=yes (default)': body: 'WizardImageStretch=yes$0' prefix: 'WizardImageStretch=yes (default)' AfterInstall: body: 'AfterInstall: ${1}$0' prefix: 'AfterInstall' AfterMyProgInstall: body: 'AfterMyProgInstall: ${1}$0' prefix: 'AfterMyProgInstall' AllowCancelDuringInstall: body: 'AllowCancelDuringInstall=${1:yes|no}$0' prefix: 'AllowCancelDuringInstall' AllowNetworkDrive: body: 'AllowNetworkDrive=${1:yes|no}$0' prefix: 'AllowNetworkDrive' AllowNoIcons: body: 'AllowNoIcons=${1:no|yes}$0' prefix: 'AllowNoIcons' AllowRootDirectory: body: 'AllowRootDirectory=${1:no|yes}$0' prefix: 'AllowRootDirectory' AllowUNCPath: body: 'AllowUNCPath=${1:yes|no}$0' prefix: 'AllowUNCPath' AlwaysRestart: body: 'AlwaysRestart=${1:no|yes}$0' prefix: 'AlwaysRestart' AlwaysShowComponentsList: body: 'AlwaysShowComponentsList=${1:yes|no}$0' prefix: 'AlwaysShowComponentsList' AlwaysShowDirOnReadyPage: body: 'AlwaysShowDirOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowDirOnReadyPage' AlwaysShowGroupOnReadyPage: body: 'AlwaysShowGroupOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowGroupOnReadyPage' AlwaysUsePersonalGroup: body: 'AlwaysUsePersonalGroup=${1:no|yes}$0' prefix: 'AlwaysUsePersonalGroup' AppComments: body: 'AppComments=${1}$0' prefix: 'AppComments' AppContact: body: 'AppContact=${1}$0' prefix: 'AppContact' AppCopyright: body: 'AppCopyright=${1}$0' prefix: 'AppCopyright' AppId: body: 'AppId=${1}$0' prefix: 'AppId' AppModifyPath: body: 'AppModifyPath=${1}$0' prefix: 'AppModifyPath' AppMutex: body: 'AppMutex=${1}$0' prefix: 'AppMutex' AppName: body: 'AppName=${1}$0' prefix: 'AppName' AppPublisher: body: 'AppPublisher=${1}$0' prefix: 'AppPublisher' AppPublisherURL: body: 'AppPublisherURL=${1}$0' prefix: 'AppPublisherURL' AppReadmeFile: body: 'AppReadmeFile=${1}$0' prefix: 'AppReadmeFile' AppSupportPhone: body: 'AppSupportPhone=${1}$0' prefix: 'AppSupportPhone' AppSupportURL: body: 'AppSupportURL=${1}$0' prefix: 'AppSupportURL' AppUpdatesURL: body: 'AppUpdatesURL=${1}$0' prefix: 'AppUpdatesURL' AppVerName: body: 'AppVerName=${1}$0' prefix: 'AppVerName' AppVersion: body: 'AppVersion=${1}$0' prefix: 'AppVersion' AppendDefaultDirName: body: 'AppendDefaultDirName=${1:yes|no}$0' prefix: 'AppendDefaultDirName' AppendDefaultGroupName: body: 'AppendDefaultGroupName=${1:yes|no}$0' prefix: 'AppendDefaultGroupName' ArchitecturesAllowed: body: 'ArchitecturesAllowed=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesAllowed' ArchitecturesInstallIn64BitMode: body: 'ArchitecturesInstallIn64BitMode=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesInstallIn64BitMode' BackColor: body: 'BackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor' BackColor2: body: 'BackColor2=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor2' BackColorDirection: body: 'BackColorDirection=${1:toptobottom|lefttoright}$0' prefix: 'BackColorDirection' BackSolid: body: 'BackSolid=${1:no|yes}$0' prefix: 'BackSolid' BeforeInstall: body: 'BeforeInstall: ${1}$0' prefix: 'BeforeInstall' BeforeMyProgInstall: body: 'BeforeMyProgInstall: ${1}$0' prefix: 'BeforeMyProgInstall' ChangesAssociations: body: 'ChangesAssociations=${1:no|yes}$0' prefix: 'ChangesAssociations' ChangesEnvironment: body: 'ChangesEnvironment=${1:no|yes}$0' prefix: 'ChangesEnvironment' Check: body: 'Check: ${1}$0' prefix: 'Check' CloseApplications: body: 'CloseApplications=${1:yes|no}$0' prefix: 'CloseApplications' CloseApplicationsFilter: body: 'CloseApplicationsFilter=${1:${2:*.exe}${3:,*.dll}${4:,*.chm}}$0' prefix: 'CloseApplicationsFilter' Components: body: 'Components: ${1}$0' prefix: 'Components' Compression: body: 'Compression=${1:lzma2/max}$0' prefix: 'Compression' CompressionThreads: body: 'CompressionThreads=${1:auto}$0' prefix: 'CompressionThreads' CreateAppDir: body: 'CreateAppDir=${1:yes|no}$0' prefix: 'CreateAppDir' CreateUninstallRegKey: body: 'CreateUninstallRegKey=${1:yes|no}$0' prefix: 'CreateUninstallRegKey' DefaultDialogFontName: body: 'DefaultDialogFontName=${1:Tahoma}$0' prefix: 'DefaultDialogFontName' DefaultDirName: body: 'DefaultDirName=${1}$0' prefix: 'DefaultDirName' DefaultGroupName: body: 'DefaultGroupName=${1}$0' prefix: 'DefaultGroupName' DefaultUserInfoName: body: 'DefaultUserInfoName=${1:{sysuserinfoname}}$0' prefix: 'DefaultUserInfoName' DefaultUserInfoOrg: body: 'DefaultUserInfoOrg=${1:{sysuserinfoorg}}$0' prefix: 'DefaultUserInfoOrg' DefaultUserInfoSerial: body: 'DefaultUserInfoSerial=${1}$0' prefix: 'DefaultUserInfoSerial' Description: body: 'Description: ${1}$0' prefix: 'Description' DestDir: body: 'DestDir: ${1}$0' prefix: 'DestDir' DestName: body: 'DestName: ${1}$0' prefix: 'DestName' DirExistsWarning: body: 'DirExistsWarning=${1:auto|yes|no}$0' prefix: 'DirExistsWarning' DisableDirPage: body: 'DisableDirPage=${1:no|auto|yes}$0' prefix: 'DisableDirPage' DisableFinishedPage: body: 'DisableFinishedPage=${1:no|yes}$0' prefix: 'DisableFinishedPage' DisableProgramGroupPage: body: 'DisableProgramGroupPage=${1:no|auto|yes}$0' prefix: 'DisableProgramGroupPage' DisableReadyMemo: body: 'DisableReadyMemo=${1:no|yes}$0' prefix: 'DisableReadyMemo' DisableReadyPage: body: 'DisableReadyPage=${1:no|yes}$0' prefix: 'DisableReadyPage' DisableStartupPrompt: body: 'DisableStartupPrompt=${1:yes|no}$0' prefix: 'DisableStartupPrompt' DisableWelcomePage: body: 'DisableWelcomePage=${1:yes|no}$0' prefix: 'DisableWelcomePage' DiskClusterSize: body: 'DiskClusterSize=${1:512}$0' prefix: 'DiskClusterSize' DiskSliceSize: body: 'DiskSliceSize=${1:max}$0' prefix: 'DiskSliceSize' DiskSpanning: body: 'DiskSpanning=${1:no|yes}$0' prefix: 'DiskSpanning' EnableDirDoesntExistWarning: body: 'EnableDirDoesntExistWarning=${1:no|yes}$0' prefix: 'EnableDirDoesntExistWarning' Encryption: body: 'Encryption=${1:no|yes}$0' prefix: 'Encryption' ExtraDiskSpaceRequired: body: 'ExtraDiskSpaceRequired=${1:0}$0' prefix: 'ExtraDiskSpaceRequired' Filename: body: 'Filename: ${1}$0' prefix: 'Filename' Flags: body: 'Flags: ${1}$0' prefix: 'Flags' FlatComponentsList: body: 'FlatComponentsList=${1:yes|no}$0' prefix: 'FlatComponentsList' InfoAfterFile: body: 'InfoAfterFile=${1}$0' prefix: 'InfoAfterFile' InfoBeforeFile: body: 'InfoBeforeFile=${1}$0' prefix: 'InfoBeforeFile' InternalCompressLevel: body: 'InternalCompressLevel=${1:normal}$0' prefix: 'InternalCompressLevel' LZMAAlgorithm: body: 'LZMAAlgorithm=${1:0|1}$0' prefix: 'LZMAAlgorithm' LZMABlockSize: body: 'LZMABlockSize=${1:}$0' prefix: 'LZMABlockSize' LZMADictionarySize: body: 'LZMADictionarySize=${1}$0' prefix: 'LZMADictionarySize' LZMAMatchFinder: body: 'LZMAMatchFinder=${1:HC|BT}$0' prefix: 'LZMAMatchFinder' LZMANumBlockThreads: body: 'LZMANumBlockThreads=${1:1}$0' prefix: 'LZMANumBlockThreads' LZMANumFastBytes: body: 'LZMANumFastBytes=${1}$0' prefix: 'LZMANumFastBytes' LZMAUseSeparateProcess: body: 'LZMAUseSeparateProcess=${1:no|yes|x86}$0' prefix: 'LZMAUseSeparateProcess' LanguageDetectionMethod: body: 'LanguageDetectionMethod=${1:uilanguage|locale|none}$0' prefix: 'LanguageDetectionMethod' Languages: body: 'Languages: ${1}$0' prefix: 'Languages' LicenseFile: body: 'LicenseFile=${1}$0' prefix: 'LicenseFile' MergeDuplicateFiles: body: 'MergeDuplicateFiles=${1:yes|no}$0' prefix: 'MergeDuplicateFiles' MinVersion: body: 'MinVersion=${1:5}.${2:0}$0' prefix: 'MinVersion' Name: body: 'Name: ${1}$0' prefix: 'Name' OnlyBelowVersion: body: 'OnlyBelowVersion=${1:0}$0' prefix: 'OnlyBelowVersion' Output: body: 'Output=${1:yes|no}$0' prefix: 'Output' OutputBaseFilename: body: 'OutputBaseFilename=${1:setup}$0' prefix: 'OutputBaseFilename' OutputDir: body: 'OutputDir=${1}$0' prefix: 'OutputDir' OutputManifestFile: body: 'OutputManifestFile=${1}$0' prefix: 'OutputManifestFile' Parameters: body: 'Parameters: ${1}$0' prefix: 'Parameters' Password: body: 'Password=${1}$0' prefix: 'Password' PrivilegesRequired: body: 'PrivilegesRequired=${1:admin|none|poweruser|lowest}$0' prefix: 'PrivilegesRequired' ReserveBytes: body: 'ReserveBytes=${1:0}$0' prefix: 'ReserveBytes' RestartApplications: body: 'RestartApplications=${1:yes|no}$0' prefix: 'RestartApplications' RestartIfNeededByRun: body: 'RestartIfNeededByRun=${1:yes|no}$0' prefix: 'RestartIfNeededByRun' Root: body: 'Root: ${1}$0' prefix: 'Root' SetupIconFile: body: 'SetupIconFile=${1}$0' prefix: 'SetupIconFile' SetupLogging: body: 'SetupLogging=${1:no|yes}$0' prefix: 'SetupLogging' ShowComponentSizes: body: 'ShowComponentSizes=${1:yes|no}$0' prefix: 'ShowComponentSizes' ShowLanguageDialog: body: 'ShowLanguageDialog=${1:yes|no|auto}$0' prefix: 'ShowLanguageDialog' ShowTasksTreeLines: body: 'ShowTasksTreeLines=${1:no|yes}$0' prefix: 'ShowTasksTreeLines' ShowUndisplayableLanguages: body: 'ShowUndisplayableLanguages=${1:no|yes}$0' prefix: 'ShowUndisplayableLanguages' SignTool: body: 'SignTool=${1}$0' prefix: 'SignTool' SignToolMinimumTimeBetween: body: 'SignToolMinimumTimeBetween=${1:0}$0' prefix: 'SignToolMinimumTimeBetween' SignToolRetryCount: body: 'SignToolRetryCount=${1:2}$0' prefix: 'SignToolRetryCount' SignToolRetryDelay: body: 'SignToolRetryDelay=${1:500}$0' prefix: 'SignToolRetryDelay' SignedUninstaller: body: 'SignedUninstaller=${1:yes|no}$0' prefix: 'SignedUninstaller' SignedUninstallerDir: body: 'SignedUninstallerDir=${1}$0' prefix: 'SignedUninstallerDir' SlicesPerDisk: body: 'SlicesPerDisk=${1:1}$0' prefix: 'SlicesPerDisk' SolidCompression: body: 'SolidCompression=${1:no|yes}$0' prefix: 'SolidCompression' Source: body: 'Source: ${1}$0' prefix: 'Source' SourceDir: body: 'SourceDir=${1}$0' prefix: 'SourceDir' StatusMsg: body: 'StatusMsg: ${1}$0' prefix: 'StatusMsg' Subkey: body: 'Subkey: ${1}$0' prefix: 'Subkey' TerminalServicesAware: body: 'TerminalServicesAware=${1:yes|no}$0' prefix: 'TerminalServicesAware' TimeStampRounding: body: 'TimeStampRounding=${1:2}$0' prefix: 'TimeStampRounding' TimeStampsInUTC: body: 'TimeStampsInUTC=${1:no|yes}$0' prefix: 'TimeStampsInUTC' TouchDate: body: 'TouchDate=${1:current|none|YYYY-MM-DD}$0' prefix: 'TouchDate' TouchTime: body: 'TouchTime=${1:current|none|HH:MM|HH:MM:SS}$0' prefix: 'TouchTime' Type: body: 'Type: ${1}$0' prefix: 'Type' Types: body: 'Types: ${1}$0' prefix: 'Types' UninstallDisplayIcon: body: 'UninstallDisplayIcon=${1}$0' prefix: 'UninstallDisplayIcon' UninstallDisplayName: body: 'UninstallDisplayName=${1}$0' prefix: 'UninstallDisplayName' UninstallDisplaySize: body: 'UninstallDisplaySize=${1}$0' prefix: 'UninstallDisplaySize' UninstallFilesDir: body: 'UninstallFilesDir=${1:{app}}$0' prefix: 'UninstallFilesDir' UninstallLogMode: body: 'UninstallLogMode=${1:append|new|overwrite}$0' prefix: 'UninstallLogMode' UninstallRestartComputer: body: 'UninstallRestartComputer=${1:no|yes}$0' prefix: 'UninstallRestartComputer' Uninstallable: body: 'Uninstallable=${1:yes|no}$0' prefix: 'Uninstallable' UpdateUninstallLogAppName: body: 'UpdateUninstallLogAppName=${1:yes|no}$0' prefix: 'UpdateUninstallLogAppName' UsePreviousAppDir: body: 'UsePreviousAppDir=${1:yes|no}$0' prefix: 'UsePreviousAppDir' UsePreviousGroup: body: 'UsePreviousGroup=${1:yes|no}$0' prefix: 'UsePreviousGroup' UsePreviousLanguage: body: 'UsePreviousLanguage=${1:yes|no}$0' prefix: 'UsePreviousLanguage' UsePreviousSetupType: body: 'UsePreviousSetupType=${1:yes|no}$0' prefix: 'UsePreviousSetupType' UsePreviousTasks: body: 'UsePreviousTasks=${1:yes|no}$0' prefix: 'UsePreviousTasks' UsePreviousUserInfo: body: 'UsePreviousUserInfo=${1:yes|no}$0' prefix: 'UsePreviousUserInfo' UseSetupLdr: body: 'UseSetupLdr=${1:yes|no}$0' prefix: 'UseSetupLdr' UserInfoPage: body: 'UserInfoPage=${1:no|yes}$0' prefix: 'UserInfoPage' ValueData: body: 'ValueData: ${1}$0' prefix: 'ValueData' ValueName: body: 'ValueName: ${1}$0' prefix: 'ValueName' ValueType: body: 'ValueType: ${1}$0' prefix: 'ValueType' VersionInfoCompany: body: 'VersionInfoCompany=${1:AppPublisher}$0' prefix: 'VersionInfoCompany' VersionInfoCopyright: body: 'VersionInfoCopyright=${1:AppCopyright}$0' prefix: 'VersionInfoCopyright' VersionInfoDescription: body: 'VersionInfoDescription=${1:AppName Setup}$0' prefix: 'VersionInfoDescription' VersionInfoOriginalFileName: body: 'VersionInfoOriginalFileName=${1:FileName}$0' prefix: 'VersionInfoOriginalFileName' VersionInfoProductName: body: 'VersionInfoProductName=${1:AppName}$0' prefix: 'VersionInfoProductName' VersionInfoProductTextVersion: body: 'VersionInfoProductTextVersion=${1:VersionInfoProductVersion}$0' prefix: 'VersionInfoProductTextVersion' VersionInfoProductVersion: body: 'VersionInfoProductVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoProductVersion' VersionInfoTextVersion: body: 'VersionInfoTextVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoTextVersion' VersionInfoVersion: body: 'VersionInfoVersion=${1:0}.${2:0}.${3:0}.${4:0}$0' prefix: 'VersionInfoVersion' WindowResizable: body: 'WindowResizable=${1:yes|no}$0' prefix: 'WindowResizable' WindowShowCaption: body: 'WindowShowCaption=${1:yes|no}$0' prefix: 'WindowShowCaption' WindowStartMaximized: body: 'WindowStartMaximized=${1:yes|no}$0' prefix: 'WindowStartMaximized' WindowVisible: body: 'WindowVisible=${1:no|yes}$0' prefix: 'WindowVisible' WizardImageBackColor: body: 'WizardImageBackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'WizardImageBackColor' WizardImageFile: body: 'WizardImageFile=${1:compiler:WIZMODERNIMAGE.BMP}$0' prefix: 'WizardImageFile' WizardImageStretch: body: 'WizardImageStretch=${1:yes|no}$0' prefix: 'WizardImageStretch' WizardSmallImageFile: body: 'WizardSmallImageFile=${1:compiler:WIZMODERNSMALLIMAGE.BMP}$0' prefix: 'WizardSmallImageFile' WorkingDir: body: 'WorkingDir: ${1}$0' prefix: 'WorkingDir' admin: body: 'admin$0' prefix: 'admin' allowunsafefiles: body: 'allowunsafefiles$0' prefix: 'allowunsafefiles' append: body: 'append$0' prefix: 'append' auto: body: 'auto$0' prefix: 'auto' binary: body: 'binary$0' prefix: 'binary' bzip: body: 'bzip$0' prefix: 'bzip' checkablealone: body: 'checkablealone$0' prefix: 'checkablealone' checkedonce: body: 'checkedonce$0' prefix: 'checkedonce' clAqua: body: 'clAqua$0' prefix: 'clAqua' clBlack: body: 'clBlack$0' prefix: 'clBlack' clBlue: body: 'clBlue$0' prefix: 'clBlue' clFuchsia: body: 'clFuchsia$0' prefix: 'clFuchsia' clGray: body: 'clGray$0' prefix: 'clGray' clGreen: body: 'clGreen$0' prefix: 'clGreen' clLime: body: 'clLime$0' prefix: 'clLime' clMaroon: body: 'clMaroon$0' prefix: 'clMaroon' clNavy: body: 'clNavy$0' prefix: 'clNavy' clOlive: body: 'clOlive$0' prefix: 'clOlive' clPurple: body: 'clPurple$0' prefix: 'clPurple' clRed: body: 'clRed$0' prefix: 'clRed' clSilver: body: 'clSilver$0' prefix: 'clSilver' clTeal: body: 'clTeal$0' prefix: 'clTeal' clWhite: body: 'clWhite$0' prefix: 'clWhite' clYellow: body: 'clYellow$0' prefix: 'clYellow' closeonexit: body: 'closeonexit$0' prefix: 'closeonexit' compact: body: 'compact$0' prefix: 'compact' comparetimestamp: body: 'comparetimestamp$0' prefix: 'comparetimestamp' compiler: body: 'compiler$0' prefix: 'compiler' confirmoverwrite: body: 'confirmoverwrite$0' prefix: 'confirmoverwrite' createallsubdirs: body: 'createallsubdirs$0' prefix: 'createallsubdirs' createkeyifdoesntexist: body: 'createkeyifdoesntexist$0' prefix: 'createkeyifdoesntexist' createonlyiffileexists: body: 'createonlyiffileexists$0' prefix: 'createonlyiffileexists' createvalueifdoesntexist: body: 'createvalueifdoesntexist$0' prefix: 'createvalueifdoesntexist' current: body: 'current$0' prefix: 'current' custom: body: 'custom$0' prefix: 'custom' deleteafterinstall: body: 'deleteafterinstall$0' prefix: 'deleteafterinstall' deletekey: body: 'deletekey$0' prefix: 'deletekey' deletevalue: body: 'deletevalue$0' prefix: 'deletevalue' desktopicon: body: 'desktopicon$0' prefix: 'desktopicon' dirifempty: body: 'dirifempty$0' prefix: 'dirifempty' disablenouninstallwarning: body: 'disablenouninstallwarning$0' prefix: 'disablenouninstallwarning' dontcloseonexit: body: 'dontcloseonexit$0' prefix: 'dontcloseonexit' dontcopy: body: 'dontcopy$0' prefix: 'dontcopy' dontcreatekey: body: 'dontcreatekey$0' prefix: 'dontcreatekey' dontinheritcheck: body: 'dontinheritcheck$0' prefix: 'dontinheritcheck' dontverifychecksum: body: 'dontverifychecksum$0' prefix: 'dontverifychecksum' dword: body: 'dword$0' prefix: 'dword' excludefromshowinnewinstall: body: 'excludefromshowinnewinstall$0' prefix: 'excludefromshowinnewinstall' exclusive: body: 'exclusive$0' prefix: 'exclusive' expandsz: body: 'expandsz$0' prefix: 'expandsz' external: body: 'external$0' prefix: 'external' fast: body: 'fast$0' prefix: 'fast' files: body: 'files$0' prefix: 'files' filesandordirs: body: 'filesandordirs$0' prefix: 'filesandordirs' fixed: body: 'fixed$0' prefix: 'fixed' foldershortcut: body: 'foldershortcut$0' prefix: 'foldershortcut' fontisnttruetype: body: 'fontisnttruetype$0' prefix: 'fontisnttruetype' full: body: 'full$0' prefix: 'full' gacinstall: body: 'gacinstall$0' prefix: 'gacinstall' help: body: 'help$0' prefix: 'help' hidewizard: body: 'hidewizard$0' prefix: 'hidewizard' ia64: body: 'ia64$0' prefix: 'ia64' ignoreversion: body: 'ignoreversion$0' prefix: 'ignoreversion' iscustom: body: 'iscustom$0' prefix: 'iscustom' isreadme: body: 'isreadme$0' prefix: 'isreadme' lefttoright: body: 'lefttoright$0' prefix: 'lefttoright' locale: body: 'locale$0' prefix: 'locale' lowest: body: 'lowest$0' prefix: 'lowest' lzma: body: 'lzma$0' prefix: 'lzma' lzma2: body: 'lzma2$0' prefix: 'lzma2' main: body: 'main$0' prefix: 'main' max: body: 'max$0' prefix: 'max' modify: body: 'modify$0' prefix: 'modify' multisz: body: 'multisz$0' prefix: 'multisz' new: body: 'new$0' prefix: 'new' no: body: 'no$0' prefix: 'no' nocompression: body: 'nocompression$0' prefix: 'nocompression' noencryption: body: 'noencryption$0' prefix: 'noencryption' noerror: body: 'noerror$0' prefix: 'noerror' none: body: 'none$0' prefix: 'none' noregerror: body: 'noregerror$0' prefix: 'noregerror' normal: body: 'normal$0' prefix: 'normal' nowait: body: 'nowait$0' prefix: 'nowait' onlyifdoesntexist: body: 'onlyifdoesntexist$0' prefix: 'onlyifdoesntexist' overwrite: body: 'overwrite$0' prefix: 'overwrite' overwritereadonly: body: 'overwritereadonly$0' prefix: 'overwritereadonly' postinstall: body: 'postinstall$0' prefix: 'postinstall' poweruser: body: 'poweruser$0' prefix: 'poweruser' preservestringtype: body: 'preservestringtype$0' prefix: 'preservestringtype' preventpinning: body: 'preventpinning$0' prefix: 'preventpinning' program: body: 'program$0' prefix: 'program' promptifolder: body: 'promptifolder$0' prefix: 'promptifolder' qword: body: 'qword$0' prefix: 'qword' read: body: 'read$0' prefix: 'read' readexec: body: 'readexec$0' prefix: 'readexec' readme: body: 'readme$0' prefix: 'readme' recursesubdirs: body: 'recursesubdirs$0' prefix: 'recursesubdirs' regserver: body: 'regserver$0' prefix: 'regserver' regtypelib: body: 'regtypelib$0' prefix: 'regtypelib' replacesameversion: body: 'replacesameversion$0' prefix: 'replacesameversion' restart: body: 'restart$0' prefix: 'restart' restartreplace: body: 'restartreplace$0' prefix: 'restartreplace' runascurrentuser: body: 'runascurrentuser$0' prefix: 'runascurrentuser' runasoriginaluser: body: 'runasoriginaluser$0' prefix: 'runasoriginaluser' runhidden: body: 'runhidden$0' prefix: 'runhidden' runminimized: body: 'runminimized$0' prefix: 'runminimized' setntfscompression: body: 'setntfscompression$0' prefix: 'setntfscompression' sharedfile: body: 'sharedfile$0' prefix: 'sharedfile' shellexec: body: 'shellexec$0' prefix: 'shellexec' skipifdoesntexist: body: 'skipifdoesntexist$0' prefix: 'skipifdoesntexist' skipifnotsilent: body: 'skipifnotsilent$0' prefix: 'skipifnotsilent' skipifsilent: body: 'skipifsilent$0' prefix: 'skipifsilent' skipifsourcedoesntexist: body: 'skipifsourcedoesntexist$0' prefix: 'skipifsourcedoesntexist' solidbreak: body: 'solidbreak$0' prefix: 'solidbreak' sortfilesbyextension: body: 'sortfilesbyextension$0' prefix: 'sortfilesbyextension' sortfilesbyname: body: 'sortfilesbyname$0' prefix: 'sortfilesbyname' string: body: 'string$0' prefix: 'string' toptobottom: body: 'toptobottom$0' prefix: 'toptobottom' touch: body: 'touch$0' prefix: 'touch' uilanguage: body: 'uilanguage$0' prefix: 'uilanguage' ultra: body: 'ultra$0' prefix: 'ultra' unchecked: body: 'unchecked$0' prefix: 'unchecked' uninsalwaysuninstall: body: 'uninsalwaysuninstall$0' prefix: 'uninsalwaysuninstall' uninsclearvalue: body: 'uninsclearvalue$0' prefix: 'uninsclearvalue' uninsdeleteentry: body: 'uninsdeleteentry$0' prefix: 'uninsdeleteentry' uninsdeletekey: body: 'uninsdeletekey$0' prefix: 'uninsdeletekey' uninsdeletekeyifempty: body: 'uninsdeletekeyifempty$0' prefix: 'uninsdeletekeyifempty' uninsdeletesection: body: 'uninsdeletesection$0' prefix: 'uninsdeletesection' uninsdeletesectionifempty: body: 'uninsdeletesectionifempty$0' prefix: 'uninsdeletesectionifempty' uninsdeletevalue: body: 'uninsdeletevalue$0' prefix: 'uninsdeletevalue' uninsneveruninstall: body: 'uninsneveruninstall$0' prefix: 'uninsneveruninstall' uninsnosharedfileprompt: body: 'uninsnosharedfileprompt$0' prefix: 'uninsnosharedfileprompt' uninsremovereadonly: body: 'uninsremovereadonly$0' prefix: 'uninsremovereadonly' uninsrestartdelete: body: 'uninsrestartdelete$0' prefix: 'uninsrestartdelete' unsetntfscompression: body: 'unsetntfscompression$0' prefix: 'unsetntfscompression' useapppaths: body: 'useapppaths$0' prefix: 'useapppaths' waituntilidle: body: 'waituntilidle$0' prefix: 'waituntilidle' waituntilterminated: body: 'waituntilterminated$0' prefix: 'waituntilterminated' x64: body: 'x64$0' prefix: 'x64' x86: body: 'x86$0' prefix: 'x86' yes: body: 'yes$0' prefix: 'yes' zip: body: 'zip$0' prefix: 'zip'
101902
'.source.inno': '32bit': body: '32bit$0' prefix: '32bit' '64bit': body: '64bit$0' prefix: '64bit' 'AllowCancelDuringInstall=no': body: 'AllowCancelDuringInstall=no$0' prefix: 'AllowCancelDuringInstall=no' 'AllowCancelDuringInstall=yes (default)': body: 'AllowCancelDuringInstall=yes$0' prefix: 'AllowCancelDuringInstall=yes (default)' 'AllowNetworkDrive=no': body: 'AllowNetworkDrive=no$0' prefix: 'AllowNetworkDrive=no' 'AllowNetworkDrive=yes (default)': body: 'AllowNetworkDrive=yes$0' prefix: 'AllowNetworkDrive=yes (default)' 'AllowNoIcons=no (default)': body: 'AllowNoIcons=no$0' prefix: 'AllowNoIcons=no (default)' 'AllowNoIcons=yes': body: 'AllowNoIcons=yes$0' prefix: 'AllowNoIcons=yes' 'AllowRootDirectory=no (default)': body: 'AllowRootDirectory=no$0' prefix: 'AllowRootDirectory=no (default)' 'AllowRootDirectory=yes': body: 'AllowRootDirectory=yes$0' prefix: 'AllowRootDirectory=yes' 'AllowUNCPath=no': body: 'AllowUNCPath=no$0' prefix: 'AllowUNCPath=no' 'AllowUNCPath=yes (default)': body: 'AllowUNCPath=yes$0' prefix: 'AllowUNCPath=yes (default)' 'AlwaysRestart=no (default)': body: 'AlwaysRestart=no$0' prefix: 'AlwaysRestart=no (default)' 'AlwaysRestart=yes': body: 'AlwaysRestart=yes$0' prefix: 'AlwaysRestart=yes' 'AlwaysShowComponentsList=no': body: 'AlwaysShowComponentsList=no$0' prefix: 'AlwaysShowComponentsList=no' 'AlwaysShowComponentsList=yes (default)': body: 'AlwaysShowComponentsList=yes$0' prefix: 'AlwaysShowComponentsList=yes (default)' 'AlwaysShowDirOnReadyPage=no (default)': body: 'AlwaysShowDirOnReadyPage=no$0' prefix: 'AlwaysShowDirOnReadyPage=no (default)' 'AlwaysShowDirOnReadyPage=yes': body: 'AlwaysShowDirOnReadyPage=yes$0' prefix: 'AlwaysShowDirOnReadyPage=yes' 'AlwaysShowGroupOnReadyPage=no (default)': body: 'AlwaysShowGroupOnReadyPage=no$0' prefix: 'AlwaysShowGroupOnReadyPage=no (default)' 'AlwaysShowGroupOnReadyPage=yes': body: 'AlwaysShowGroupOnReadyPage=yes$0' prefix: 'AlwaysShowGroupOnReadyPage=yes' 'AlwaysUsePersonalGroup=no (default)': body: 'AlwaysUsePersonalGroup=no$0' prefix: 'AlwaysUsePersonalGroup=no (default)' 'AlwaysUsePersonalGroup=yes': body: 'AlwaysUsePersonalGroup=yes$0' prefix: 'AlwaysUsePersonalGroup=yes' 'AppendDefaultDirName=no': body: 'AppendDefaultDirName=no$0' prefix: 'AppendDefaultDirName=no' 'AppendDefaultDirName=yes (default)': body: 'AppendDefaultDirName=yes$0' prefix: 'AppendDefaultDirName=yes (default)' 'AppendDefaultGroupName=no': body: 'AppendDefaultGroupName=no$0' prefix: 'AppendDefaultGroupName=no' 'AppendDefaultGroupName=yes (default)': body: 'AppendDefaultGroupName=yes$0' prefix: 'AppendDefaultGroupName=yes (default)' 'ChangesAssociations=no (default)': body: 'ChangesAssociations=no$0' prefix: 'ChangesAssociations=no (default)' 'ChangesAssociations=yes': body: 'ChangesAssociations=yes$0' prefix: 'ChangesAssociations=yes' 'ChangesEnvironment=no (default)': body: 'ChangesEnvironment=no$0' prefix: 'ChangesEnvironment=no (default)' 'ChangesEnvironment=yes': body: 'ChangesEnvironment=yes$0' prefix: 'ChangesEnvironment=yes' 'CloseApplications=no': body: 'CloseApplications=no$0' prefix: 'CloseApplications=no' 'CloseApplications=yes (default)': body: 'CloseApplications=yes$0' prefix: 'CloseApplications=yes (default)' 'CreateAppDir=no': body: 'CreateAppDir=no$0' prefix: 'CreateAppDir=no' 'CreateAppDir=yes (default)': body: 'CreateAppDir=yes$0' prefix: 'CreateAppDir=yes (default)' 'CreateUninstallRegKey=no': body: 'CreateUninstallRegKey=no$0' prefix: 'CreateUninstallRegKey=no' 'CreateUninstallRegKey=yes (default)': body: 'CreateUninstallRegKey=yes$0' prefix: 'CreateUninstallRegKey=yes (default)' 'DirExistsWarning=auto (default)': body: 'DirExistsWarning=auto$0' prefix: 'DirExistsWarning=auto (default)' 'DirExistsWarning=no': body: 'DirExistsWarning=no$0' prefix: 'DirExistsWarning=no' 'DirExistsWarning=yes': body: 'DirExistsWarning=yes$0' prefix: 'DirExistsWarning=yes' 'DisableDirPage=auto': body: 'DisableDirPage=yes$0' prefix: 'DisableDirPage=auto' 'DisableDirPage=no (default)': body: 'DisableDirPage=no$0' prefix: 'DisableDirPage=no (default)' 'DisableFinishedPage=no (default)': body: 'DisableFinishedPage=no$0' prefix: 'DisableFinishedPage=no (default)' 'DisableFinishedPage=yes': body: 'DisableFinishedPage=yes$0' prefix: 'DisableFinishedPage=yes' 'DisableProgramGroupPage=auto': body: 'DisableProgramGroupPage=auto$0' prefix: 'DisableProgramGroupPage=auto' 'DisableProgramGroupPage=no (default)': body: 'DisableProgramGroupPage=no$0' prefix: 'DisableProgramGroupPage=no (default)' 'DisableProgramGroupPage=yes': body: 'DisableProgramGroupPage=yes$0' prefix: 'DisableProgramGroupPage=yes' 'DisableReadyMemo=no (default)': body: 'DisableReadyMemo=no$0' prefix: 'DisableReadyMemo=no (default)' 'DisableReadyMemo=yes': body: 'DisableReadyMemo=yes$0' prefix: 'DisableReadyMemo=yes' 'DisableReadyPage=no (default)': body: 'DisableReadyPage=no$0' prefix: 'DisableReadyPage=no (default)' 'DisableReadyPage=yes': body: 'DisableReadyPage=yes$0' prefix: 'DisableReadyPage=yes' 'DisableStartupPrompt=no': body: 'DisableStartupPrompt=no$0' prefix: 'DisableStartupPrompt=no' 'DisableStartupPrompt=yes (default)': body: 'DisableStartupPrompt=yes$0' prefix: 'DisableStartupPrompt=yes (default)' 'DisableWelcomePage=no': body: 'DisableWelcomePage=no$0' prefix: 'DisableWelcomePage=no' 'DisableWelcomePage=yes (default)': body: 'DisableWelcomePage=yes$0' prefix: 'DisableWelcomePage=yes (default)' 'DiskSpanning=no (default)': body: 'DiskSpanning=no$0' prefix: 'DiskSpanning=no (default)' 'DiskSpanning=yes': body: 'DiskSpanning=yes$0' prefix: 'DiskSpanning=yes' 'EnableDirDoesntExistWarning=no (default)': body: 'EnableDirDoesntExistWarning=no$0' prefix: 'EnableDirDoesntExistWarning=no (default)' 'EnableDirDoesntExistWarning=yes': body: 'EnableDirDoesntExistWarning=yes$0' prefix: 'EnableDirDoesntExistWarning=yes' 'FlatComponentsList=no': body: 'FlatComponentsList=no$0' prefix: 'FlatComponentsList=no' 'FlatComponentsList=yes (default)': body: 'FlatComponentsList=yes$0' prefix: 'FlatComponentsList=yes (default)' 'LZMAAlgorithm=0 (default)': body: 'LZMAAlgorithm=0$0' prefix: 'LZMAAlgorithm=0 (default)' 'LZMAAlgorithm=1': body: 'LZMAAlgorithm=1$0' prefix: 'LZMAAlgorithm=1' 'LZMAMatchFinder=BT': body: 'LZMAMatchFinder=BT$0' prefix: 'LZMAMatchFinder=BT' 'LZMAMatchFinder=HC': body: 'LZMAMatchFinder=HC$0' prefix: 'LZMAMatchFinder=HC' 'LZMAUseSeparateProcess=no (default)': body: 'LZMAUseSeparateProcess=no$0' prefix: 'LZMAUseSeparateProcess=no (default)' 'LZMAUseSeparateProcess=x86': body: 'LZMAUseSeparateProcess=x86$0' prefix: 'LZMAUseSeparateProcess=x86' 'LZMAUseSeparateProcess=yes': body: 'LZMAUseSeparateProcess=yes$0' prefix: 'LZMAUseSeparateProcess=yes' 'LanguageDetectionMethod=locale': body: 'LanguageDetectionMethod=locale$0' prefix: 'LanguageDetectionMethod=locale' 'LanguageDetectionMethod=none': body: 'LanguageDetectionMethod=none$0' prefix: 'LanguageDetectionMethod=none' 'LanguageDetectionMethod=uilanguage (default)': body: 'LanguageDetectionMethod=uilanguage$0' prefix: 'LanguageDetectionMethod=uilanguage (default)' 'MergeDuplicateFiles=no': body: 'MergeDuplicateFiles=no$0' prefix: 'MergeDuplicateFiles=no' 'MergeDuplicateFiles=yes (default)': body: 'MergeDuplicateFiles=yes$0' prefix: 'MergeDuplicateFiles=yes (default)' 'Output=no': body: 'Output=no$0' prefix: 'Output=no' 'Output=yes': body: 'Output=yes$0' prefix: 'Output=yes' 'PrivilegesRequired=admin (default)': body: 'PrivilegesRequired=admin$0' prefix: 'PrivilegesRequired=admin (default)' 'PrivilegesRequired=lowest': body: 'PrivilegesRequired=lowest$0' prefix: 'PrivilegesRequired=lowest' 'PrivilegesRequired=none': body: 'PrivilegesRequired=none$0' prefix: 'PrivilegesRequired=none' 'PrivilegesRequired=poweruser': body: 'PrivilegesRequired=poweruser$0' prefix: 'PrivilegesRequired=poweruser' 'RestartApplications=no': body: 'RestartApplications=no$0' prefix: 'RestartApplications=no' 'RestartApplications=yes (default)': body: 'RestartApplications=yes$0' prefix: 'RestartApplications=yes (default)' 'RestartIfNeededByRun=no': body: 'RestartIfNeededByRun=no$0' prefix: 'RestartIfNeededByRun=no' 'RestartIfNeededByRun=yes (default)': body: 'RestartIfNeededByRun=yes$0' prefix: 'RestartIfNeededByRun=yes (default)' 'SetupLogging=no (default)': body: 'SetupLogging=no$0' prefix: 'SetupLogging=no (default)' 'SetupLogging=yes': body: 'SetupLogging=yes$0' prefix: 'SetupLogging=yes' 'ShowComponentSizes=no': body: 'ShowComponentSizes=no$0' prefix: 'ShowComponentSizes=no' 'ShowComponentSizes=yes (default)': body: 'ShowComponentSizes=yes$0' prefix: 'ShowComponentSizes=yes (default)' 'ShowLanguageDialog=auto': body: 'ShowLanguageDialog=auto$0' prefix: 'ShowLanguageDialog=auto' 'ShowLanguageDialog=no': body: 'ShowLanguageDialog=no$0' prefix: 'ShowLanguageDialog=no' 'ShowLanguageDialog=yes (default)': body: 'ShowLanguageDialog=yes$0' prefix: 'ShowLanguageDialog=yes (default)' 'ShowUndisplayableLanguages=no (default)': body: 'ShowUndisplayableLanguages=no$0' prefix: 'ShowUndisplayableLanguages=no (default)' 'ShowUndisplayableLanguages=yes': body: 'ShowUndisplayableLanguages=yes$0' prefix: 'ShowUndisplayableLanguages=yes' 'SignedUninstaller=no': body: 'SignedUninstaller=no$0' prefix: 'SignedUninstaller=no' 'SignedUninstaller=yes (default)': body: 'SignedUninstaller=yes$0' prefix: 'SignedUninstaller=yes (default)' 'SolidCompression=no (default)': body: 'SolidCompression=no$0' prefix: 'SolidCompression=no (default)' 'SolidCompression=yes': body: 'SolidCompression=yes$0' prefix: 'SolidCompression=yes' 'TerminalServicesAware=no': body: 'TerminalServicesAware=no$0' prefix: 'TerminalServicesAware=no' 'TerminalServicesAware=yes (default)': body: 'TerminalServicesAware=yes$0' prefix: 'TerminalServicesAware=yes (default)' 'TimeStampsInUTC=no (default)': body: 'TimeStampsInUTC=no$0' prefix: 'TimeStampsInUTC=no (default)' 'TimeStampsInUTC=yes': body: 'TimeStampsInUTC=yes$0' prefix: 'TimeStampsInUTC=yes' 'UninstallLogMode=append (default)': body: 'UninstallLogMode=append$0' prefix: 'UninstallLogMode=append (default)' 'UninstallLogMode=new': body: 'UninstallLogMode=new$0' prefix: 'UninstallLogMode=new' 'UninstallLogMode=overwrite': body: 'UninstallLogMode=overwrite$0' prefix: 'UninstallLogMode=overwrite' 'UninstallRestartComputer=no (default)': body: 'UninstallRestartComputer=no$0' prefix: 'UninstallRestartComputer=no (default)' 'UninstallRestartComputer=yes': body: 'UninstallRestartComputer=yes$0' prefix: 'UninstallRestartComputer=yes' 'UpdateUninstallLogAppName=no': body: 'UpdateUninstallLogAppName=no$0' prefix: 'UpdateUninstallLogAppName=no' 'UpdateUninstallLogAppName=yes (default)': body: 'UpdateUninstallLogAppName=yes$0' prefix: 'UpdateUninstallLogAppName=yes (default)' 'UsePreviousAppDir=no': body: 'UsePreviousAppDir=no$0' prefix: 'UsePreviousAppDir=no' 'UsePreviousAppDir=yes (default)': body: 'UsePreviousAppDir=yes$0' prefix: 'UsePreviousAppDir=yes (default)' 'UsePreviousGroup=no': body: 'UsePreviousGroup=no$0' prefix: 'UsePreviousGroup=no' 'UsePreviousGroup=yes (default)': body: 'UsePreviousGroup=yes$0' prefix: 'UsePreviousGroup=yes (default)' 'UsePreviousLanguage=no': body: 'UsePreviousLanguage=no$0' prefix: 'UsePreviousLanguage=no' 'UsePreviousLanguage=yes (default)': body: 'UsePreviousLanguage=yes$0' prefix: 'UsePreviousLanguage=yes (default)' 'UsePreviousSetupType=no': body: 'UsePreviousSetupType=no$0' prefix: 'UsePreviousSetupType=no' 'UsePreviousSetupType=yes (default)': body: 'UsePreviousSetupType=yes$0' prefix: 'UsePreviousSetupType=yes (default)' 'UsePreviousTasks=no': body: 'UsePreviousTasks=no$0' prefix: 'UsePreviousTasks=no' 'UsePreviousTasks=yes (default)': body: 'UsePreviousTasks=yes$0' prefix: 'UsePreviousTasks=yes (default)' 'UsePreviousUserInfo=no': body: 'UsePreviousUserInfo=no$0' prefix: 'UsePreviousUserInfo=no' 'UsePreviousUserInfo=yes (default)': body: 'UsePreviousUserInfo=yes$0' prefix: 'UsePreviousUserInfo=yes (default)' 'UseSetupLdr=no': body: 'UseSetupLdr=no$0' prefix: 'UseSetupLdr=no' 'UseSetupLdr=yes (default)': body: 'UseSetupLdr=yes$0' prefix: 'UseSetupLdr=yes (default)' 'UserInfoPage=no (default)': body: 'UserInfoPage=no$0' prefix: 'UserInfoPage=no (default)' 'UserInfoPage=yes': body: 'UserInfoPage=yes$0' prefix: 'UserInfoPage=yes' 'WindowResizable=no': body: 'WindowResizable=no$0' prefix: 'WindowResizable=no' 'WindowResizable=yes (default)': body: 'WindowResizable=yes$0' prefix: 'WindowResizable=yes (default)' 'WindowShowCaption=no': body: 'WindowShowCaption=no$0' prefix: 'WindowShowCaption=no' 'WindowShowCaption=yes (default)': body: 'WindowShowCaption=yes$0' prefix: 'WindowShowCaption=yes (default)' 'WindowStartMaximized=no': body: 'WindowStartMaximized=no$0' prefix: 'WindowStartMaximized=no' 'WindowStartMaximized=yes (default)': body: 'WindowStartMaximized=yes$0' prefix: 'WindowStartMaximized=yes (default)' 'WindowVisible=no (default)': body: 'WindowVisible=no$0' prefix: 'WindowVisible=no (default)' 'WindowVisible=yes': body: 'WindowVisible=yes$0' prefix: 'WindowVisible=yes' 'WizardImageStretch=no': body: 'WizardImageStretch=no$0' prefix: 'WizardImageStretch=no' 'WizardImageStretch=yes (default)': body: 'WizardImageStretch=yes$0' prefix: 'WizardImageStretch=yes (default)' AfterInstall: body: 'AfterInstall: ${1}$0' prefix: 'AfterInstall' AfterMyProgInstall: body: 'AfterMyProgInstall: ${1}$0' prefix: 'AfterMyProgInstall' AllowCancelDuringInstall: body: 'AllowCancelDuringInstall=${1:yes|no}$0' prefix: 'AllowCancelDuringInstall' AllowNetworkDrive: body: 'AllowNetworkDrive=${1:yes|no}$0' prefix: 'AllowNetworkDrive' AllowNoIcons: body: 'AllowNoIcons=${1:no|yes}$0' prefix: 'AllowNoIcons' AllowRootDirectory: body: 'AllowRootDirectory=${1:no|yes}$0' prefix: 'AllowRootDirectory' AllowUNCPath: body: 'AllowUNCPath=${1:yes|no}$0' prefix: 'AllowUNCPath' AlwaysRestart: body: 'AlwaysRestart=${1:no|yes}$0' prefix: 'AlwaysRestart' AlwaysShowComponentsList: body: 'AlwaysShowComponentsList=${1:yes|no}$0' prefix: 'AlwaysShowComponentsList' AlwaysShowDirOnReadyPage: body: 'AlwaysShowDirOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowDirOnReadyPage' AlwaysShowGroupOnReadyPage: body: 'AlwaysShowGroupOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowGroupOnReadyPage' AlwaysUsePersonalGroup: body: 'AlwaysUsePersonalGroup=${1:no|yes}$0' prefix: 'AlwaysUsePersonalGroup' AppComments: body: 'AppComments=${1}$0' prefix: 'AppComments' AppContact: body: 'AppContact=${1}$0' prefix: 'AppContact' AppCopyright: body: 'AppCopyright=${1}$0' prefix: 'AppCopyright' AppId: body: 'AppId=${1}$0' prefix: 'AppId' AppModifyPath: body: 'AppModifyPath=${1}$0' prefix: 'AppModifyPath' AppMutex: body: 'AppMutex=${1}$0' prefix: 'AppMutex' AppName: body: 'AppName=${1}$0' prefix: 'AppName' AppPublisher: body: 'AppPublisher=${1}$0' prefix: 'AppPublisher' AppPublisherURL: body: 'AppPublisherURL=${1}$0' prefix: 'AppPublisherURL' AppReadmeFile: body: 'AppReadmeFile=${1}$0' prefix: 'AppReadmeFile' AppSupportPhone: body: 'AppSupportPhone=${1}$0' prefix: 'AppSupportPhone' AppSupportURL: body: 'AppSupportURL=${1}$0' prefix: 'AppSupportURL' AppUpdatesURL: body: 'AppUpdatesURL=${1}$0' prefix: 'AppUpdatesURL' AppVerName: body: 'AppVerName=${1}$0' prefix: 'AppVerName' AppVersion: body: 'AppVersion=${1}$0' prefix: 'AppVersion' AppendDefaultDirName: body: 'AppendDefaultDirName=${1:yes|no}$0' prefix: 'AppendDefaultDirName' AppendDefaultGroupName: body: 'AppendDefaultGroupName=${1:yes|no}$0' prefix: 'AppendDefaultGroupName' ArchitecturesAllowed: body: 'ArchitecturesAllowed=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesAllowed' ArchitecturesInstallIn64BitMode: body: 'ArchitecturesInstallIn64BitMode=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesInstallIn64BitMode' BackColor: body: 'BackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor' BackColor2: body: 'BackColor2=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor2' BackColorDirection: body: 'BackColorDirection=${1:toptobottom|lefttoright}$0' prefix: 'BackColorDirection' BackSolid: body: 'BackSolid=${1:no|yes}$0' prefix: 'BackSolid' BeforeInstall: body: 'BeforeInstall: ${1}$0' prefix: 'BeforeInstall' BeforeMyProgInstall: body: 'BeforeMyProgInstall: ${1}$0' prefix: 'BeforeMyProgInstall' ChangesAssociations: body: 'ChangesAssociations=${1:no|yes}$0' prefix: 'ChangesAssociations' ChangesEnvironment: body: 'ChangesEnvironment=${1:no|yes}$0' prefix: 'ChangesEnvironment' Check: body: 'Check: ${1}$0' prefix: 'Check' CloseApplications: body: 'CloseApplications=${1:yes|no}$0' prefix: 'CloseApplications' CloseApplicationsFilter: body: 'CloseApplicationsFilter=${1:${2:*.exe}${3:,*.dll}${4:,*.chm}}$0' prefix: 'CloseApplicationsFilter' Components: body: 'Components: ${1}$0' prefix: 'Components' Compression: body: 'Compression=${1:lzma2/max}$0' prefix: 'Compression' CompressionThreads: body: 'CompressionThreads=${1:auto}$0' prefix: 'CompressionThreads' CreateAppDir: body: 'CreateAppDir=${1:yes|no}$0' prefix: 'CreateAppDir' CreateUninstallRegKey: body: 'CreateUninstallRegKey=${1:yes|no}$0' prefix: 'CreateUninstallRegKey' DefaultDialogFontName: body: 'DefaultDialogFontName=${1:Tahoma}$0' prefix: 'DefaultDialogFontName' DefaultDirName: body: 'DefaultDirName=${1}$0' prefix: 'DefaultDirName' DefaultGroupName: body: 'DefaultGroupName=${1}$0' prefix: 'DefaultGroupName' DefaultUserInfoName: body: 'DefaultUserInfoName=${1:{sysuserinfoname}}$0' prefix: 'DefaultUserInfoName' DefaultUserInfoOrg: body: 'DefaultUserInfoOrg=${1:{sysuserinfoorg}}$0' prefix: 'DefaultUserInfoOrg' DefaultUserInfoSerial: body: 'DefaultUserInfoSerial=${1}$0' prefix: 'DefaultUserInfoSerial' Description: body: 'Description: ${1}$0' prefix: 'Description' DestDir: body: 'DestDir: ${1}$0' prefix: 'DestDir' DestName: body: 'DestName: ${1}$0' prefix: 'DestName' DirExistsWarning: body: 'DirExistsWarning=${1:auto|yes|no}$0' prefix: 'DirExistsWarning' DisableDirPage: body: 'DisableDirPage=${1:no|auto|yes}$0' prefix: 'DisableDirPage' DisableFinishedPage: body: 'DisableFinishedPage=${1:no|yes}$0' prefix: 'DisableFinishedPage' DisableProgramGroupPage: body: 'DisableProgramGroupPage=${1:no|auto|yes}$0' prefix: 'DisableProgramGroupPage' DisableReadyMemo: body: 'DisableReadyMemo=${1:no|yes}$0' prefix: 'DisableReadyMemo' DisableReadyPage: body: 'DisableReadyPage=${1:no|yes}$0' prefix: 'DisableReadyPage' DisableStartupPrompt: body: 'DisableStartupPrompt=${1:yes|no}$0' prefix: 'DisableStartupPrompt' DisableWelcomePage: body: 'DisableWelcomePage=${1:yes|no}$0' prefix: 'DisableWelcomePage' DiskClusterSize: body: 'DiskClusterSize=${1:512}$0' prefix: 'DiskClusterSize' DiskSliceSize: body: 'DiskSliceSize=${1:max}$0' prefix: 'DiskSliceSize' DiskSpanning: body: 'DiskSpanning=${1:no|yes}$0' prefix: 'DiskSpanning' EnableDirDoesntExistWarning: body: 'EnableDirDoesntExistWarning=${1:no|yes}$0' prefix: 'EnableDirDoesntExistWarning' Encryption: body: 'Encryption=${1:no|yes}$0' prefix: 'Encryption' ExtraDiskSpaceRequired: body: 'ExtraDiskSpaceRequired=${1:0}$0' prefix: 'ExtraDiskSpaceRequired' Filename: body: 'Filename: ${1}$0' prefix: 'Filename' Flags: body: 'Flags: ${1}$0' prefix: 'Flags' FlatComponentsList: body: 'FlatComponentsList=${1:yes|no}$0' prefix: 'FlatComponentsList' InfoAfterFile: body: 'InfoAfterFile=${1}$0' prefix: 'InfoAfterFile' InfoBeforeFile: body: 'InfoBeforeFile=${1}$0' prefix: 'InfoBeforeFile' InternalCompressLevel: body: 'InternalCompressLevel=${1:normal}$0' prefix: 'InternalCompressLevel' LZMAAlgorithm: body: 'LZMAAlgorithm=${1:0|1}$0' prefix: 'LZMAAlgorithm' LZMABlockSize: body: 'LZMABlockSize=${1:}$0' prefix: 'LZMABlockSize' LZMADictionarySize: body: 'LZMADictionarySize=${1}$0' prefix: 'LZMADictionarySize' LZMAMatchFinder: body: 'LZMAMatchFinder=${1:HC|BT}$0' prefix: 'LZMAMatchFinder' LZMANumBlockThreads: body: 'LZMANumBlockThreads=${1:1}$0' prefix: 'LZMANumBlockThreads' LZMANumFastBytes: body: 'LZMANumFastBytes=${1}$0' prefix: 'LZMANumFastBytes' LZMAUseSeparateProcess: body: 'LZMAUseSeparateProcess=${1:no|yes|x86}$0' prefix: 'LZMAUseSeparateProcess' LanguageDetectionMethod: body: 'LanguageDetectionMethod=${1:uilanguage|locale|none}$0' prefix: 'LanguageDetectionMethod' Languages: body: 'Languages: ${1}$0' prefix: 'Languages' LicenseFile: body: 'LicenseFile=${1}$0' prefix: 'LicenseFile' MergeDuplicateFiles: body: 'MergeDuplicateFiles=${1:yes|no}$0' prefix: 'MergeDuplicateFiles' MinVersion: body: 'MinVersion=${1:5}.${2:0}$0' prefix: 'MinVersion' Name: body: 'Name: ${1}$0' prefix: 'Name' OnlyBelowVersion: body: 'OnlyBelowVersion=${1:0}$0' prefix: 'OnlyBelowVersion' Output: body: 'Output=${1:yes|no}$0' prefix: 'Output' OutputBaseFilename: body: 'OutputBaseFilename=${1:setup}$0' prefix: 'OutputBaseFilename' OutputDir: body: 'OutputDir=${1}$0' prefix: 'OutputDir' OutputManifestFile: body: 'OutputManifestFile=${1}$0' prefix: 'OutputManifestFile' Parameters: body: 'Parameters: ${1}$0' prefix: 'Parameters' Password: body: 'Password=${1}<PASSWORD>' prefix: 'Password' PrivilegesRequired: body: 'PrivilegesRequired=${1:admin|none|poweruser|lowest}$0' prefix: 'PrivilegesRequired' ReserveBytes: body: 'ReserveBytes=${1:0}$0' prefix: 'ReserveBytes' RestartApplications: body: 'RestartApplications=${1:yes|no}$0' prefix: 'RestartApplications' RestartIfNeededByRun: body: 'RestartIfNeededByRun=${1:yes|no}$0' prefix: 'RestartIfNeededByRun' Root: body: 'Root: ${1}$0' prefix: 'Root' SetupIconFile: body: 'SetupIconFile=${1}$0' prefix: 'SetupIconFile' SetupLogging: body: 'SetupLogging=${1:no|yes}$0' prefix: 'SetupLogging' ShowComponentSizes: body: 'ShowComponentSizes=${1:yes|no}$0' prefix: 'ShowComponentSizes' ShowLanguageDialog: body: 'ShowLanguageDialog=${1:yes|no|auto}$0' prefix: 'ShowLanguageDialog' ShowTasksTreeLines: body: 'ShowTasksTreeLines=${1:no|yes}$0' prefix: 'ShowTasksTreeLines' ShowUndisplayableLanguages: body: 'ShowUndisplayableLanguages=${1:no|yes}$0' prefix: 'ShowUndisplayableLanguages' SignTool: body: 'SignTool=${1}$0' prefix: 'SignTool' SignToolMinimumTimeBetween: body: 'SignToolMinimumTimeBetween=${1:0}$0' prefix: 'SignToolMinimumTimeBetween' SignToolRetryCount: body: 'SignToolRetryCount=${1:2}$0' prefix: 'SignToolRetryCount' SignToolRetryDelay: body: 'SignToolRetryDelay=${1:500}$0' prefix: 'SignToolRetryDelay' SignedUninstaller: body: 'SignedUninstaller=${1:yes|no}$0' prefix: 'SignedUninstaller' SignedUninstallerDir: body: 'SignedUninstallerDir=${1}$0' prefix: 'SignedUninstallerDir' SlicesPerDisk: body: 'SlicesPerDisk=${1:1}$0' prefix: 'SlicesPerDisk' SolidCompression: body: 'SolidCompression=${1:no|yes}$0' prefix: 'SolidCompression' Source: body: 'Source: ${1}$0' prefix: 'Source' SourceDir: body: 'SourceDir=${1}$0' prefix: 'SourceDir' StatusMsg: body: 'StatusMsg: ${1}$0' prefix: 'StatusMsg' Subkey: body: 'Subkey: ${1}$0' prefix: 'Subkey' TerminalServicesAware: body: 'TerminalServicesAware=${1:yes|no}$0' prefix: 'TerminalServicesAware' TimeStampRounding: body: 'TimeStampRounding=${1:2}$0' prefix: 'TimeStampRounding' TimeStampsInUTC: body: 'TimeStampsInUTC=${1:no|yes}$0' prefix: 'TimeStampsInUTC' TouchDate: body: 'TouchDate=${1:current|none|YYYY-MM-DD}$0' prefix: 'TouchDate' TouchTime: body: 'TouchTime=${1:current|none|HH:MM|HH:MM:SS}$0' prefix: 'TouchTime' Type: body: 'Type: ${1}$0' prefix: 'Type' Types: body: 'Types: ${1}$0' prefix: 'Types' UninstallDisplayIcon: body: 'UninstallDisplayIcon=${1}$0' prefix: 'UninstallDisplayIcon' UninstallDisplayName: body: 'UninstallDisplayName=${1}$0' prefix: 'UninstallDisplayName' UninstallDisplaySize: body: 'UninstallDisplaySize=${1}$0' prefix: 'UninstallDisplaySize' UninstallFilesDir: body: 'UninstallFilesDir=${1:{app}}$0' prefix: 'UninstallFilesDir' UninstallLogMode: body: 'UninstallLogMode=${1:append|new|overwrite}$0' prefix: 'UninstallLogMode' UninstallRestartComputer: body: 'UninstallRestartComputer=${1:no|yes}$0' prefix: 'UninstallRestartComputer' Uninstallable: body: 'Uninstallable=${1:yes|no}$0' prefix: 'Uninstallable' UpdateUninstallLogAppName: body: 'UpdateUninstallLogAppName=${1:yes|no}$0' prefix: 'UpdateUninstallLogAppName' UsePreviousAppDir: body: 'UsePreviousAppDir=${1:yes|no}$0' prefix: 'UsePreviousAppDir' UsePreviousGroup: body: 'UsePreviousGroup=${1:yes|no}$0' prefix: 'UsePreviousGroup' UsePreviousLanguage: body: 'UsePreviousLanguage=${1:yes|no}$0' prefix: 'UsePreviousLanguage' UsePreviousSetupType: body: 'UsePreviousSetupType=${1:yes|no}$0' prefix: 'UsePreviousSetupType' UsePreviousTasks: body: 'UsePreviousTasks=${1:yes|no}$0' prefix: 'UsePreviousTasks' UsePreviousUserInfo: body: 'UsePreviousUserInfo=${1:yes|no}$0' prefix: 'UsePreviousUserInfo' UseSetupLdr: body: 'UseSetupLdr=${1:yes|no}$0' prefix: 'UseSetupLdr' UserInfoPage: body: 'UserInfoPage=${1:no|yes}$0' prefix: 'UserInfoPage' ValueData: body: 'ValueData: ${1}$0' prefix: 'ValueData' ValueName: body: 'ValueName: ${1}$0' prefix: 'ValueName' ValueType: body: 'ValueType: ${1}$0' prefix: 'ValueType' VersionInfoCompany: body: 'VersionInfoCompany=${1:AppPublisher}$0' prefix: 'VersionInfoCompany' VersionInfoCopyright: body: 'VersionInfoCopyright=${1:AppCopyright}$0' prefix: 'VersionInfoCopyright' VersionInfoDescription: body: 'VersionInfoDescription=${1:AppName Setup}$0' prefix: 'VersionInfoDescription' VersionInfoOriginalFileName: body: 'VersionInfoOriginalFileName=${1:FileName}$0' prefix: 'VersionInfoOriginalFileName' VersionInfoProductName: body: 'VersionInfoProductName=${1:AppName}$0' prefix: 'VersionInfoProductName' VersionInfoProductTextVersion: body: 'VersionInfoProductTextVersion=${1:VersionInfoProductVersion}$0' prefix: 'VersionInfoProductTextVersion' VersionInfoProductVersion: body: 'VersionInfoProductVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoProductVersion' VersionInfoTextVersion: body: 'VersionInfoTextVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoTextVersion' VersionInfoVersion: body: 'VersionInfoVersion=${1:0}.${2:0}.${3:0}.${4:0}$0' prefix: 'VersionInfoVersion' WindowResizable: body: 'WindowResizable=${1:yes|no}$0' prefix: 'WindowResizable' WindowShowCaption: body: 'WindowShowCaption=${1:yes|no}$0' prefix: 'WindowShowCaption' WindowStartMaximized: body: 'WindowStartMaximized=${1:yes|no}$0' prefix: 'WindowStartMaximized' WindowVisible: body: 'WindowVisible=${1:no|yes}$0' prefix: 'WindowVisible' WizardImageBackColor: body: 'WizardImageBackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'WizardImageBackColor' WizardImageFile: body: 'WizardImageFile=${1:compiler:WIZMODERNIMAGE.BMP}$0' prefix: 'WizardImageFile' WizardImageStretch: body: 'WizardImageStretch=${1:yes|no}$0' prefix: 'WizardImageStretch' WizardSmallImageFile: body: 'WizardSmallImageFile=${1:compiler:WIZMODERNSMALLIMAGE.BMP}$0' prefix: 'WizardSmallImageFile' WorkingDir: body: 'WorkingDir: ${1}$0' prefix: 'WorkingDir' admin: body: 'admin$0' prefix: 'admin' allowunsafefiles: body: 'allowunsafefiles$0' prefix: 'allowunsafefiles' append: body: 'append$0' prefix: 'append' auto: body: 'auto$0' prefix: 'auto' binary: body: 'binary$0' prefix: 'binary' bzip: body: 'bzip$0' prefix: 'bzip' checkablealone: body: 'checkablealone$0' prefix: 'checkablealone' checkedonce: body: 'checkedonce$0' prefix: 'checkedonce' clAqua: body: 'clAqua$0' prefix: 'clAqua' clBlack: body: 'clBlack$0' prefix: 'clBlack' clBlue: body: 'clBlue$0' prefix: 'clBlue' clFuchsia: body: 'clFuchsia$0' prefix: 'clFuchsia' clGray: body: 'clGray$0' prefix: 'clGray' clGreen: body: 'clGreen$0' prefix: 'clGreen' clLime: body: 'clLime$0' prefix: 'clLime' clMaroon: body: 'clMaroon$0' prefix: 'clMaroon' clNavy: body: 'clNavy$0' prefix: 'clNavy' clOlive: body: 'clOlive$0' prefix: 'clOlive' clPurple: body: 'clPurple$0' prefix: 'clPurple' clRed: body: 'clRed$0' prefix: 'clRed' clSilver: body: 'clSilver$0' prefix: 'clSilver' clTeal: body: 'clTeal$0' prefix: 'clTeal' clWhite: body: 'clWhite$0' prefix: 'clWhite' clYellow: body: 'clYellow$0' prefix: 'clYellow' closeonexit: body: 'closeonexit$0' prefix: 'closeonexit' compact: body: 'compact$0' prefix: 'compact' comparetimestamp: body: 'comparetimestamp$0' prefix: 'comparetimestamp' compiler: body: 'compiler$0' prefix: 'compiler' confirmoverwrite: body: 'confirmoverwrite$0' prefix: 'confirmoverwrite' createallsubdirs: body: 'createallsubdirs$0' prefix: 'createallsubdirs' createkeyifdoesntexist: body: 'createkeyifdoesntexist$0' prefix: 'createkeyifdoesntexist' createonlyiffileexists: body: 'createonlyiffileexists$0' prefix: 'createonlyiffileexists' createvalueifdoesntexist: body: 'createvalueifdoesntexist$0' prefix: 'createvalueifdoesntexist' current: body: 'current$0' prefix: 'current' custom: body: 'custom$0' prefix: 'custom' deleteafterinstall: body: 'deleteafterinstall$0' prefix: 'deleteafterinstall' deletekey: body: 'deletekey$0' prefix: 'deletekey' deletevalue: body: 'deletevalue$0' prefix: 'deletevalue' desktopicon: body: 'desktopicon$0' prefix: 'desktopicon' dirifempty: body: 'dirifempty$0' prefix: 'dirifempty' disablenouninstallwarning: body: 'disablenouninstallwarning$0' prefix: 'disablenouninstallwarning' dontcloseonexit: body: 'dontcloseonexit$0' prefix: 'dontcloseonexit' dontcopy: body: 'dontcopy$0' prefix: 'dontcopy' dontcreatekey: body: 'dontcreatekey$0' prefix: 'dontcreatekey' dontinheritcheck: body: 'dontinheritcheck$0' prefix: 'dontinheritcheck' dontverifychecksum: body: 'dontverifychecksum$0' prefix: 'dontverifychecksum' dword: body: 'dword$0' prefix: 'dword' excludefromshowinnewinstall: body: 'excludefromshowinnewinstall$0' prefix: 'excludefromshowinnewinstall' exclusive: body: 'exclusive$0' prefix: 'exclusive' expandsz: body: 'expandsz$0' prefix: 'expandsz' external: body: 'external$0' prefix: 'external' fast: body: 'fast$0' prefix: 'fast' files: body: 'files$0' prefix: 'files' filesandordirs: body: 'filesandordirs$0' prefix: 'filesandordirs' fixed: body: 'fixed$0' prefix: 'fixed' foldershortcut: body: 'foldershortcut$0' prefix: 'foldershortcut' fontisnttruetype: body: 'fontisnttruetype$0' prefix: 'fontisnttruetype' full: body: 'full$0' prefix: 'full' gacinstall: body: 'gacinstall$0' prefix: 'gacinstall' help: body: 'help$0' prefix: 'help' hidewizard: body: 'hidewizard$0' prefix: 'hidewizard' ia64: body: 'ia64$0' prefix: 'ia64' ignoreversion: body: 'ignoreversion$0' prefix: 'ignoreversion' iscustom: body: 'iscustom$0' prefix: 'iscustom' isreadme: body: 'isreadme$0' prefix: 'isreadme' lefttoright: body: 'lefttoright$0' prefix: 'lefttoright' locale: body: 'locale$0' prefix: 'locale' lowest: body: 'lowest$0' prefix: 'lowest' lzma: body: 'lzma$0' prefix: 'lzma' lzma2: body: 'lzma2$0' prefix: 'lzma2' main: body: 'main$0' prefix: 'main' max: body: 'max$0' prefix: 'max' modify: body: 'modify$0' prefix: 'modify' multisz: body: 'multisz$0' prefix: 'multisz' new: body: 'new$0' prefix: 'new' no: body: 'no$0' prefix: 'no' nocompression: body: 'nocompression$0' prefix: 'nocompression' noencryption: body: 'noencryption$0' prefix: 'noencryption' noerror: body: 'noerror$0' prefix: 'noerror' none: body: 'none$0' prefix: 'none' noregerror: body: 'noregerror$0' prefix: 'noregerror' normal: body: 'normal$0' prefix: 'normal' nowait: body: 'nowait$0' prefix: 'nowait' onlyifdoesntexist: body: 'onlyifdoesntexist$0' prefix: 'onlyifdoesntexist' overwrite: body: 'overwrite$0' prefix: 'overwrite' overwritereadonly: body: 'overwritereadonly$0' prefix: 'overwritereadonly' postinstall: body: 'postinstall$0' prefix: 'postinstall' poweruser: body: 'poweruser$0' prefix: 'poweruser' preservestringtype: body: 'preservestringtype$0' prefix: 'preservestringtype' preventpinning: body: 'preventpinning$0' prefix: 'preventpinning' program: body: 'program$0' prefix: 'program' promptifolder: body: 'promptifolder$0' prefix: 'promptifolder' qword: body: 'qword$0' prefix: 'qword' read: body: 'read$0' prefix: 'read' readexec: body: 'readexec$0' prefix: 'readexec' readme: body: 'readme$0' prefix: 'readme' recursesubdirs: body: 'recursesubdirs$0' prefix: 'recursesubdirs' regserver: body: 'regserver$0' prefix: 'regserver' regtypelib: body: 'regtypelib$0' prefix: 'regtypelib' replacesameversion: body: 'replacesameversion$0' prefix: 'replacesameversion' restart: body: 'restart$0' prefix: 'restart' restartreplace: body: 'restartreplace$0' prefix: 'restartreplace' runascurrentuser: body: 'runascurrentuser$0' prefix: 'runascurrentuser' runasoriginaluser: body: 'runasoriginaluser$0' prefix: 'runasoriginaluser' runhidden: body: 'runhidden$0' prefix: 'runhidden' runminimized: body: 'runminimized$0' prefix: 'runminimized' setntfscompression: body: 'setntfscompression$0' prefix: 'setntfscompression' sharedfile: body: 'sharedfile$0' prefix: 'sharedfile' shellexec: body: 'shellexec$0' prefix: 'shellexec' skipifdoesntexist: body: 'skipifdoesntexist$0' prefix: 'skipifdoesntexist' skipifnotsilent: body: 'skipifnotsilent$0' prefix: 'skipifnotsilent' skipifsilent: body: 'skipifsilent$0' prefix: 'skipifsilent' skipifsourcedoesntexist: body: 'skipifsourcedoesntexist$0' prefix: 'skipifsourcedoesntexist' solidbreak: body: 'solidbreak$0' prefix: 'solidbreak' sortfilesbyextension: body: 'sortfilesbyextension$0' prefix: 'sortfilesbyextension' sortfilesbyname: body: 'sortfilesbyname$0' prefix: 'sortfilesbyname' string: body: 'string$0' prefix: 'string' toptobottom: body: 'toptobottom$0' prefix: 'toptobottom' touch: body: 'touch$0' prefix: 'touch' uilanguage: body: 'uilanguage$0' prefix: 'uilanguage' ultra: body: 'ultra$0' prefix: 'ultra' unchecked: body: 'unchecked$0' prefix: 'unchecked' uninsalwaysuninstall: body: 'uninsalwaysuninstall$0' prefix: 'uninsalwaysuninstall' uninsclearvalue: body: 'uninsclearvalue$0' prefix: 'uninsclearvalue' uninsdeleteentry: body: 'uninsdeleteentry$0' prefix: 'uninsdeleteentry' uninsdeletekey: body: 'uninsdeletekey$0' prefix: 'uninsdeletekey' uninsdeletekeyifempty: body: 'uninsdeletekeyifempty$0' prefix: 'uninsdeletekeyifempty' uninsdeletesection: body: 'uninsdeletesection$0' prefix: 'uninsdeletesection' uninsdeletesectionifempty: body: 'uninsdeletesectionifempty$0' prefix: 'uninsdeletesectionifempty' uninsdeletevalue: body: 'uninsdeletevalue$0' prefix: 'uninsdeletevalue' uninsneveruninstall: body: 'uninsneveruninstall$0' prefix: 'uninsneveruninstall' uninsnosharedfileprompt: body: 'uninsnosharedfileprompt$0' prefix: 'uninsnosharedfileprompt' uninsremovereadonly: body: 'uninsremovereadonly$0' prefix: 'uninsremovereadonly' uninsrestartdelete: body: 'uninsrestartdelete$0' prefix: 'uninsrestartdelete' unsetntfscompression: body: 'unsetntfscompression$0' prefix: 'unsetntfscompression' useapppaths: body: 'useapppaths$0' prefix: 'useapppaths' waituntilidle: body: 'waituntilidle$0' prefix: 'waituntilidle' waituntilterminated: body: 'waituntilterminated$0' prefix: 'waituntilterminated' x64: body: 'x64$0' prefix: 'x64' x86: body: 'x86$0' prefix: 'x86' yes: body: 'yes$0' prefix: 'yes' zip: body: 'zip$0' prefix: 'zip'
true
'.source.inno': '32bit': body: '32bit$0' prefix: '32bit' '64bit': body: '64bit$0' prefix: '64bit' 'AllowCancelDuringInstall=no': body: 'AllowCancelDuringInstall=no$0' prefix: 'AllowCancelDuringInstall=no' 'AllowCancelDuringInstall=yes (default)': body: 'AllowCancelDuringInstall=yes$0' prefix: 'AllowCancelDuringInstall=yes (default)' 'AllowNetworkDrive=no': body: 'AllowNetworkDrive=no$0' prefix: 'AllowNetworkDrive=no' 'AllowNetworkDrive=yes (default)': body: 'AllowNetworkDrive=yes$0' prefix: 'AllowNetworkDrive=yes (default)' 'AllowNoIcons=no (default)': body: 'AllowNoIcons=no$0' prefix: 'AllowNoIcons=no (default)' 'AllowNoIcons=yes': body: 'AllowNoIcons=yes$0' prefix: 'AllowNoIcons=yes' 'AllowRootDirectory=no (default)': body: 'AllowRootDirectory=no$0' prefix: 'AllowRootDirectory=no (default)' 'AllowRootDirectory=yes': body: 'AllowRootDirectory=yes$0' prefix: 'AllowRootDirectory=yes' 'AllowUNCPath=no': body: 'AllowUNCPath=no$0' prefix: 'AllowUNCPath=no' 'AllowUNCPath=yes (default)': body: 'AllowUNCPath=yes$0' prefix: 'AllowUNCPath=yes (default)' 'AlwaysRestart=no (default)': body: 'AlwaysRestart=no$0' prefix: 'AlwaysRestart=no (default)' 'AlwaysRestart=yes': body: 'AlwaysRestart=yes$0' prefix: 'AlwaysRestart=yes' 'AlwaysShowComponentsList=no': body: 'AlwaysShowComponentsList=no$0' prefix: 'AlwaysShowComponentsList=no' 'AlwaysShowComponentsList=yes (default)': body: 'AlwaysShowComponentsList=yes$0' prefix: 'AlwaysShowComponentsList=yes (default)' 'AlwaysShowDirOnReadyPage=no (default)': body: 'AlwaysShowDirOnReadyPage=no$0' prefix: 'AlwaysShowDirOnReadyPage=no (default)' 'AlwaysShowDirOnReadyPage=yes': body: 'AlwaysShowDirOnReadyPage=yes$0' prefix: 'AlwaysShowDirOnReadyPage=yes' 'AlwaysShowGroupOnReadyPage=no (default)': body: 'AlwaysShowGroupOnReadyPage=no$0' prefix: 'AlwaysShowGroupOnReadyPage=no (default)' 'AlwaysShowGroupOnReadyPage=yes': body: 'AlwaysShowGroupOnReadyPage=yes$0' prefix: 'AlwaysShowGroupOnReadyPage=yes' 'AlwaysUsePersonalGroup=no (default)': body: 'AlwaysUsePersonalGroup=no$0' prefix: 'AlwaysUsePersonalGroup=no (default)' 'AlwaysUsePersonalGroup=yes': body: 'AlwaysUsePersonalGroup=yes$0' prefix: 'AlwaysUsePersonalGroup=yes' 'AppendDefaultDirName=no': body: 'AppendDefaultDirName=no$0' prefix: 'AppendDefaultDirName=no' 'AppendDefaultDirName=yes (default)': body: 'AppendDefaultDirName=yes$0' prefix: 'AppendDefaultDirName=yes (default)' 'AppendDefaultGroupName=no': body: 'AppendDefaultGroupName=no$0' prefix: 'AppendDefaultGroupName=no' 'AppendDefaultGroupName=yes (default)': body: 'AppendDefaultGroupName=yes$0' prefix: 'AppendDefaultGroupName=yes (default)' 'ChangesAssociations=no (default)': body: 'ChangesAssociations=no$0' prefix: 'ChangesAssociations=no (default)' 'ChangesAssociations=yes': body: 'ChangesAssociations=yes$0' prefix: 'ChangesAssociations=yes' 'ChangesEnvironment=no (default)': body: 'ChangesEnvironment=no$0' prefix: 'ChangesEnvironment=no (default)' 'ChangesEnvironment=yes': body: 'ChangesEnvironment=yes$0' prefix: 'ChangesEnvironment=yes' 'CloseApplications=no': body: 'CloseApplications=no$0' prefix: 'CloseApplications=no' 'CloseApplications=yes (default)': body: 'CloseApplications=yes$0' prefix: 'CloseApplications=yes (default)' 'CreateAppDir=no': body: 'CreateAppDir=no$0' prefix: 'CreateAppDir=no' 'CreateAppDir=yes (default)': body: 'CreateAppDir=yes$0' prefix: 'CreateAppDir=yes (default)' 'CreateUninstallRegKey=no': body: 'CreateUninstallRegKey=no$0' prefix: 'CreateUninstallRegKey=no' 'CreateUninstallRegKey=yes (default)': body: 'CreateUninstallRegKey=yes$0' prefix: 'CreateUninstallRegKey=yes (default)' 'DirExistsWarning=auto (default)': body: 'DirExistsWarning=auto$0' prefix: 'DirExistsWarning=auto (default)' 'DirExistsWarning=no': body: 'DirExistsWarning=no$0' prefix: 'DirExistsWarning=no' 'DirExistsWarning=yes': body: 'DirExistsWarning=yes$0' prefix: 'DirExistsWarning=yes' 'DisableDirPage=auto': body: 'DisableDirPage=yes$0' prefix: 'DisableDirPage=auto' 'DisableDirPage=no (default)': body: 'DisableDirPage=no$0' prefix: 'DisableDirPage=no (default)' 'DisableFinishedPage=no (default)': body: 'DisableFinishedPage=no$0' prefix: 'DisableFinishedPage=no (default)' 'DisableFinishedPage=yes': body: 'DisableFinishedPage=yes$0' prefix: 'DisableFinishedPage=yes' 'DisableProgramGroupPage=auto': body: 'DisableProgramGroupPage=auto$0' prefix: 'DisableProgramGroupPage=auto' 'DisableProgramGroupPage=no (default)': body: 'DisableProgramGroupPage=no$0' prefix: 'DisableProgramGroupPage=no (default)' 'DisableProgramGroupPage=yes': body: 'DisableProgramGroupPage=yes$0' prefix: 'DisableProgramGroupPage=yes' 'DisableReadyMemo=no (default)': body: 'DisableReadyMemo=no$0' prefix: 'DisableReadyMemo=no (default)' 'DisableReadyMemo=yes': body: 'DisableReadyMemo=yes$0' prefix: 'DisableReadyMemo=yes' 'DisableReadyPage=no (default)': body: 'DisableReadyPage=no$0' prefix: 'DisableReadyPage=no (default)' 'DisableReadyPage=yes': body: 'DisableReadyPage=yes$0' prefix: 'DisableReadyPage=yes' 'DisableStartupPrompt=no': body: 'DisableStartupPrompt=no$0' prefix: 'DisableStartupPrompt=no' 'DisableStartupPrompt=yes (default)': body: 'DisableStartupPrompt=yes$0' prefix: 'DisableStartupPrompt=yes (default)' 'DisableWelcomePage=no': body: 'DisableWelcomePage=no$0' prefix: 'DisableWelcomePage=no' 'DisableWelcomePage=yes (default)': body: 'DisableWelcomePage=yes$0' prefix: 'DisableWelcomePage=yes (default)' 'DiskSpanning=no (default)': body: 'DiskSpanning=no$0' prefix: 'DiskSpanning=no (default)' 'DiskSpanning=yes': body: 'DiskSpanning=yes$0' prefix: 'DiskSpanning=yes' 'EnableDirDoesntExistWarning=no (default)': body: 'EnableDirDoesntExistWarning=no$0' prefix: 'EnableDirDoesntExistWarning=no (default)' 'EnableDirDoesntExistWarning=yes': body: 'EnableDirDoesntExistWarning=yes$0' prefix: 'EnableDirDoesntExistWarning=yes' 'FlatComponentsList=no': body: 'FlatComponentsList=no$0' prefix: 'FlatComponentsList=no' 'FlatComponentsList=yes (default)': body: 'FlatComponentsList=yes$0' prefix: 'FlatComponentsList=yes (default)' 'LZMAAlgorithm=0 (default)': body: 'LZMAAlgorithm=0$0' prefix: 'LZMAAlgorithm=0 (default)' 'LZMAAlgorithm=1': body: 'LZMAAlgorithm=1$0' prefix: 'LZMAAlgorithm=1' 'LZMAMatchFinder=BT': body: 'LZMAMatchFinder=BT$0' prefix: 'LZMAMatchFinder=BT' 'LZMAMatchFinder=HC': body: 'LZMAMatchFinder=HC$0' prefix: 'LZMAMatchFinder=HC' 'LZMAUseSeparateProcess=no (default)': body: 'LZMAUseSeparateProcess=no$0' prefix: 'LZMAUseSeparateProcess=no (default)' 'LZMAUseSeparateProcess=x86': body: 'LZMAUseSeparateProcess=x86$0' prefix: 'LZMAUseSeparateProcess=x86' 'LZMAUseSeparateProcess=yes': body: 'LZMAUseSeparateProcess=yes$0' prefix: 'LZMAUseSeparateProcess=yes' 'LanguageDetectionMethod=locale': body: 'LanguageDetectionMethod=locale$0' prefix: 'LanguageDetectionMethod=locale' 'LanguageDetectionMethod=none': body: 'LanguageDetectionMethod=none$0' prefix: 'LanguageDetectionMethod=none' 'LanguageDetectionMethod=uilanguage (default)': body: 'LanguageDetectionMethod=uilanguage$0' prefix: 'LanguageDetectionMethod=uilanguage (default)' 'MergeDuplicateFiles=no': body: 'MergeDuplicateFiles=no$0' prefix: 'MergeDuplicateFiles=no' 'MergeDuplicateFiles=yes (default)': body: 'MergeDuplicateFiles=yes$0' prefix: 'MergeDuplicateFiles=yes (default)' 'Output=no': body: 'Output=no$0' prefix: 'Output=no' 'Output=yes': body: 'Output=yes$0' prefix: 'Output=yes' 'PrivilegesRequired=admin (default)': body: 'PrivilegesRequired=admin$0' prefix: 'PrivilegesRequired=admin (default)' 'PrivilegesRequired=lowest': body: 'PrivilegesRequired=lowest$0' prefix: 'PrivilegesRequired=lowest' 'PrivilegesRequired=none': body: 'PrivilegesRequired=none$0' prefix: 'PrivilegesRequired=none' 'PrivilegesRequired=poweruser': body: 'PrivilegesRequired=poweruser$0' prefix: 'PrivilegesRequired=poweruser' 'RestartApplications=no': body: 'RestartApplications=no$0' prefix: 'RestartApplications=no' 'RestartApplications=yes (default)': body: 'RestartApplications=yes$0' prefix: 'RestartApplications=yes (default)' 'RestartIfNeededByRun=no': body: 'RestartIfNeededByRun=no$0' prefix: 'RestartIfNeededByRun=no' 'RestartIfNeededByRun=yes (default)': body: 'RestartIfNeededByRun=yes$0' prefix: 'RestartIfNeededByRun=yes (default)' 'SetupLogging=no (default)': body: 'SetupLogging=no$0' prefix: 'SetupLogging=no (default)' 'SetupLogging=yes': body: 'SetupLogging=yes$0' prefix: 'SetupLogging=yes' 'ShowComponentSizes=no': body: 'ShowComponentSizes=no$0' prefix: 'ShowComponentSizes=no' 'ShowComponentSizes=yes (default)': body: 'ShowComponentSizes=yes$0' prefix: 'ShowComponentSizes=yes (default)' 'ShowLanguageDialog=auto': body: 'ShowLanguageDialog=auto$0' prefix: 'ShowLanguageDialog=auto' 'ShowLanguageDialog=no': body: 'ShowLanguageDialog=no$0' prefix: 'ShowLanguageDialog=no' 'ShowLanguageDialog=yes (default)': body: 'ShowLanguageDialog=yes$0' prefix: 'ShowLanguageDialog=yes (default)' 'ShowUndisplayableLanguages=no (default)': body: 'ShowUndisplayableLanguages=no$0' prefix: 'ShowUndisplayableLanguages=no (default)' 'ShowUndisplayableLanguages=yes': body: 'ShowUndisplayableLanguages=yes$0' prefix: 'ShowUndisplayableLanguages=yes' 'SignedUninstaller=no': body: 'SignedUninstaller=no$0' prefix: 'SignedUninstaller=no' 'SignedUninstaller=yes (default)': body: 'SignedUninstaller=yes$0' prefix: 'SignedUninstaller=yes (default)' 'SolidCompression=no (default)': body: 'SolidCompression=no$0' prefix: 'SolidCompression=no (default)' 'SolidCompression=yes': body: 'SolidCompression=yes$0' prefix: 'SolidCompression=yes' 'TerminalServicesAware=no': body: 'TerminalServicesAware=no$0' prefix: 'TerminalServicesAware=no' 'TerminalServicesAware=yes (default)': body: 'TerminalServicesAware=yes$0' prefix: 'TerminalServicesAware=yes (default)' 'TimeStampsInUTC=no (default)': body: 'TimeStampsInUTC=no$0' prefix: 'TimeStampsInUTC=no (default)' 'TimeStampsInUTC=yes': body: 'TimeStampsInUTC=yes$0' prefix: 'TimeStampsInUTC=yes' 'UninstallLogMode=append (default)': body: 'UninstallLogMode=append$0' prefix: 'UninstallLogMode=append (default)' 'UninstallLogMode=new': body: 'UninstallLogMode=new$0' prefix: 'UninstallLogMode=new' 'UninstallLogMode=overwrite': body: 'UninstallLogMode=overwrite$0' prefix: 'UninstallLogMode=overwrite' 'UninstallRestartComputer=no (default)': body: 'UninstallRestartComputer=no$0' prefix: 'UninstallRestartComputer=no (default)' 'UninstallRestartComputer=yes': body: 'UninstallRestartComputer=yes$0' prefix: 'UninstallRestartComputer=yes' 'UpdateUninstallLogAppName=no': body: 'UpdateUninstallLogAppName=no$0' prefix: 'UpdateUninstallLogAppName=no' 'UpdateUninstallLogAppName=yes (default)': body: 'UpdateUninstallLogAppName=yes$0' prefix: 'UpdateUninstallLogAppName=yes (default)' 'UsePreviousAppDir=no': body: 'UsePreviousAppDir=no$0' prefix: 'UsePreviousAppDir=no' 'UsePreviousAppDir=yes (default)': body: 'UsePreviousAppDir=yes$0' prefix: 'UsePreviousAppDir=yes (default)' 'UsePreviousGroup=no': body: 'UsePreviousGroup=no$0' prefix: 'UsePreviousGroup=no' 'UsePreviousGroup=yes (default)': body: 'UsePreviousGroup=yes$0' prefix: 'UsePreviousGroup=yes (default)' 'UsePreviousLanguage=no': body: 'UsePreviousLanguage=no$0' prefix: 'UsePreviousLanguage=no' 'UsePreviousLanguage=yes (default)': body: 'UsePreviousLanguage=yes$0' prefix: 'UsePreviousLanguage=yes (default)' 'UsePreviousSetupType=no': body: 'UsePreviousSetupType=no$0' prefix: 'UsePreviousSetupType=no' 'UsePreviousSetupType=yes (default)': body: 'UsePreviousSetupType=yes$0' prefix: 'UsePreviousSetupType=yes (default)' 'UsePreviousTasks=no': body: 'UsePreviousTasks=no$0' prefix: 'UsePreviousTasks=no' 'UsePreviousTasks=yes (default)': body: 'UsePreviousTasks=yes$0' prefix: 'UsePreviousTasks=yes (default)' 'UsePreviousUserInfo=no': body: 'UsePreviousUserInfo=no$0' prefix: 'UsePreviousUserInfo=no' 'UsePreviousUserInfo=yes (default)': body: 'UsePreviousUserInfo=yes$0' prefix: 'UsePreviousUserInfo=yes (default)' 'UseSetupLdr=no': body: 'UseSetupLdr=no$0' prefix: 'UseSetupLdr=no' 'UseSetupLdr=yes (default)': body: 'UseSetupLdr=yes$0' prefix: 'UseSetupLdr=yes (default)' 'UserInfoPage=no (default)': body: 'UserInfoPage=no$0' prefix: 'UserInfoPage=no (default)' 'UserInfoPage=yes': body: 'UserInfoPage=yes$0' prefix: 'UserInfoPage=yes' 'WindowResizable=no': body: 'WindowResizable=no$0' prefix: 'WindowResizable=no' 'WindowResizable=yes (default)': body: 'WindowResizable=yes$0' prefix: 'WindowResizable=yes (default)' 'WindowShowCaption=no': body: 'WindowShowCaption=no$0' prefix: 'WindowShowCaption=no' 'WindowShowCaption=yes (default)': body: 'WindowShowCaption=yes$0' prefix: 'WindowShowCaption=yes (default)' 'WindowStartMaximized=no': body: 'WindowStartMaximized=no$0' prefix: 'WindowStartMaximized=no' 'WindowStartMaximized=yes (default)': body: 'WindowStartMaximized=yes$0' prefix: 'WindowStartMaximized=yes (default)' 'WindowVisible=no (default)': body: 'WindowVisible=no$0' prefix: 'WindowVisible=no (default)' 'WindowVisible=yes': body: 'WindowVisible=yes$0' prefix: 'WindowVisible=yes' 'WizardImageStretch=no': body: 'WizardImageStretch=no$0' prefix: 'WizardImageStretch=no' 'WizardImageStretch=yes (default)': body: 'WizardImageStretch=yes$0' prefix: 'WizardImageStretch=yes (default)' AfterInstall: body: 'AfterInstall: ${1}$0' prefix: 'AfterInstall' AfterMyProgInstall: body: 'AfterMyProgInstall: ${1}$0' prefix: 'AfterMyProgInstall' AllowCancelDuringInstall: body: 'AllowCancelDuringInstall=${1:yes|no}$0' prefix: 'AllowCancelDuringInstall' AllowNetworkDrive: body: 'AllowNetworkDrive=${1:yes|no}$0' prefix: 'AllowNetworkDrive' AllowNoIcons: body: 'AllowNoIcons=${1:no|yes}$0' prefix: 'AllowNoIcons' AllowRootDirectory: body: 'AllowRootDirectory=${1:no|yes}$0' prefix: 'AllowRootDirectory' AllowUNCPath: body: 'AllowUNCPath=${1:yes|no}$0' prefix: 'AllowUNCPath' AlwaysRestart: body: 'AlwaysRestart=${1:no|yes}$0' prefix: 'AlwaysRestart' AlwaysShowComponentsList: body: 'AlwaysShowComponentsList=${1:yes|no}$0' prefix: 'AlwaysShowComponentsList' AlwaysShowDirOnReadyPage: body: 'AlwaysShowDirOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowDirOnReadyPage' AlwaysShowGroupOnReadyPage: body: 'AlwaysShowGroupOnReadyPage=${1:no|yes}$0' prefix: 'AlwaysShowGroupOnReadyPage' AlwaysUsePersonalGroup: body: 'AlwaysUsePersonalGroup=${1:no|yes}$0' prefix: 'AlwaysUsePersonalGroup' AppComments: body: 'AppComments=${1}$0' prefix: 'AppComments' AppContact: body: 'AppContact=${1}$0' prefix: 'AppContact' AppCopyright: body: 'AppCopyright=${1}$0' prefix: 'AppCopyright' AppId: body: 'AppId=${1}$0' prefix: 'AppId' AppModifyPath: body: 'AppModifyPath=${1}$0' prefix: 'AppModifyPath' AppMutex: body: 'AppMutex=${1}$0' prefix: 'AppMutex' AppName: body: 'AppName=${1}$0' prefix: 'AppName' AppPublisher: body: 'AppPublisher=${1}$0' prefix: 'AppPublisher' AppPublisherURL: body: 'AppPublisherURL=${1}$0' prefix: 'AppPublisherURL' AppReadmeFile: body: 'AppReadmeFile=${1}$0' prefix: 'AppReadmeFile' AppSupportPhone: body: 'AppSupportPhone=${1}$0' prefix: 'AppSupportPhone' AppSupportURL: body: 'AppSupportURL=${1}$0' prefix: 'AppSupportURL' AppUpdatesURL: body: 'AppUpdatesURL=${1}$0' prefix: 'AppUpdatesURL' AppVerName: body: 'AppVerName=${1}$0' prefix: 'AppVerName' AppVersion: body: 'AppVersion=${1}$0' prefix: 'AppVersion' AppendDefaultDirName: body: 'AppendDefaultDirName=${1:yes|no}$0' prefix: 'AppendDefaultDirName' AppendDefaultGroupName: body: 'AppendDefaultGroupName=${1:yes|no}$0' prefix: 'AppendDefaultGroupName' ArchitecturesAllowed: body: 'ArchitecturesAllowed=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesAllowed' ArchitecturesInstallIn64BitMode: body: 'ArchitecturesInstallIn64BitMode=${1:${2:x86}${3: x64}${4: ia64}}$0' prefix: 'ArchitecturesInstallIn64BitMode' BackColor: body: 'BackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor' BackColor2: body: 'BackColor2=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'BackColor2' BackColorDirection: body: 'BackColorDirection=${1:toptobottom|lefttoright}$0' prefix: 'BackColorDirection' BackSolid: body: 'BackSolid=${1:no|yes}$0' prefix: 'BackSolid' BeforeInstall: body: 'BeforeInstall: ${1}$0' prefix: 'BeforeInstall' BeforeMyProgInstall: body: 'BeforeMyProgInstall: ${1}$0' prefix: 'BeforeMyProgInstall' ChangesAssociations: body: 'ChangesAssociations=${1:no|yes}$0' prefix: 'ChangesAssociations' ChangesEnvironment: body: 'ChangesEnvironment=${1:no|yes}$0' prefix: 'ChangesEnvironment' Check: body: 'Check: ${1}$0' prefix: 'Check' CloseApplications: body: 'CloseApplications=${1:yes|no}$0' prefix: 'CloseApplications' CloseApplicationsFilter: body: 'CloseApplicationsFilter=${1:${2:*.exe}${3:,*.dll}${4:,*.chm}}$0' prefix: 'CloseApplicationsFilter' Components: body: 'Components: ${1}$0' prefix: 'Components' Compression: body: 'Compression=${1:lzma2/max}$0' prefix: 'Compression' CompressionThreads: body: 'CompressionThreads=${1:auto}$0' prefix: 'CompressionThreads' CreateAppDir: body: 'CreateAppDir=${1:yes|no}$0' prefix: 'CreateAppDir' CreateUninstallRegKey: body: 'CreateUninstallRegKey=${1:yes|no}$0' prefix: 'CreateUninstallRegKey' DefaultDialogFontName: body: 'DefaultDialogFontName=${1:Tahoma}$0' prefix: 'DefaultDialogFontName' DefaultDirName: body: 'DefaultDirName=${1}$0' prefix: 'DefaultDirName' DefaultGroupName: body: 'DefaultGroupName=${1}$0' prefix: 'DefaultGroupName' DefaultUserInfoName: body: 'DefaultUserInfoName=${1:{sysuserinfoname}}$0' prefix: 'DefaultUserInfoName' DefaultUserInfoOrg: body: 'DefaultUserInfoOrg=${1:{sysuserinfoorg}}$0' prefix: 'DefaultUserInfoOrg' DefaultUserInfoSerial: body: 'DefaultUserInfoSerial=${1}$0' prefix: 'DefaultUserInfoSerial' Description: body: 'Description: ${1}$0' prefix: 'Description' DestDir: body: 'DestDir: ${1}$0' prefix: 'DestDir' DestName: body: 'DestName: ${1}$0' prefix: 'DestName' DirExistsWarning: body: 'DirExistsWarning=${1:auto|yes|no}$0' prefix: 'DirExistsWarning' DisableDirPage: body: 'DisableDirPage=${1:no|auto|yes}$0' prefix: 'DisableDirPage' DisableFinishedPage: body: 'DisableFinishedPage=${1:no|yes}$0' prefix: 'DisableFinishedPage' DisableProgramGroupPage: body: 'DisableProgramGroupPage=${1:no|auto|yes}$0' prefix: 'DisableProgramGroupPage' DisableReadyMemo: body: 'DisableReadyMemo=${1:no|yes}$0' prefix: 'DisableReadyMemo' DisableReadyPage: body: 'DisableReadyPage=${1:no|yes}$0' prefix: 'DisableReadyPage' DisableStartupPrompt: body: 'DisableStartupPrompt=${1:yes|no}$0' prefix: 'DisableStartupPrompt' DisableWelcomePage: body: 'DisableWelcomePage=${1:yes|no}$0' prefix: 'DisableWelcomePage' DiskClusterSize: body: 'DiskClusterSize=${1:512}$0' prefix: 'DiskClusterSize' DiskSliceSize: body: 'DiskSliceSize=${1:max}$0' prefix: 'DiskSliceSize' DiskSpanning: body: 'DiskSpanning=${1:no|yes}$0' prefix: 'DiskSpanning' EnableDirDoesntExistWarning: body: 'EnableDirDoesntExistWarning=${1:no|yes}$0' prefix: 'EnableDirDoesntExistWarning' Encryption: body: 'Encryption=${1:no|yes}$0' prefix: 'Encryption' ExtraDiskSpaceRequired: body: 'ExtraDiskSpaceRequired=${1:0}$0' prefix: 'ExtraDiskSpaceRequired' Filename: body: 'Filename: ${1}$0' prefix: 'Filename' Flags: body: 'Flags: ${1}$0' prefix: 'Flags' FlatComponentsList: body: 'FlatComponentsList=${1:yes|no}$0' prefix: 'FlatComponentsList' InfoAfterFile: body: 'InfoAfterFile=${1}$0' prefix: 'InfoAfterFile' InfoBeforeFile: body: 'InfoBeforeFile=${1}$0' prefix: 'InfoBeforeFile' InternalCompressLevel: body: 'InternalCompressLevel=${1:normal}$0' prefix: 'InternalCompressLevel' LZMAAlgorithm: body: 'LZMAAlgorithm=${1:0|1}$0' prefix: 'LZMAAlgorithm' LZMABlockSize: body: 'LZMABlockSize=${1:}$0' prefix: 'LZMABlockSize' LZMADictionarySize: body: 'LZMADictionarySize=${1}$0' prefix: 'LZMADictionarySize' LZMAMatchFinder: body: 'LZMAMatchFinder=${1:HC|BT}$0' prefix: 'LZMAMatchFinder' LZMANumBlockThreads: body: 'LZMANumBlockThreads=${1:1}$0' prefix: 'LZMANumBlockThreads' LZMANumFastBytes: body: 'LZMANumFastBytes=${1}$0' prefix: 'LZMANumFastBytes' LZMAUseSeparateProcess: body: 'LZMAUseSeparateProcess=${1:no|yes|x86}$0' prefix: 'LZMAUseSeparateProcess' LanguageDetectionMethod: body: 'LanguageDetectionMethod=${1:uilanguage|locale|none}$0' prefix: 'LanguageDetectionMethod' Languages: body: 'Languages: ${1}$0' prefix: 'Languages' LicenseFile: body: 'LicenseFile=${1}$0' prefix: 'LicenseFile' MergeDuplicateFiles: body: 'MergeDuplicateFiles=${1:yes|no}$0' prefix: 'MergeDuplicateFiles' MinVersion: body: 'MinVersion=${1:5}.${2:0}$0' prefix: 'MinVersion' Name: body: 'Name: ${1}$0' prefix: 'Name' OnlyBelowVersion: body: 'OnlyBelowVersion=${1:0}$0' prefix: 'OnlyBelowVersion' Output: body: 'Output=${1:yes|no}$0' prefix: 'Output' OutputBaseFilename: body: 'OutputBaseFilename=${1:setup}$0' prefix: 'OutputBaseFilename' OutputDir: body: 'OutputDir=${1}$0' prefix: 'OutputDir' OutputManifestFile: body: 'OutputManifestFile=${1}$0' prefix: 'OutputManifestFile' Parameters: body: 'Parameters: ${1}$0' prefix: 'Parameters' Password: body: 'Password=${1}PI:PASSWORD:<PASSWORD>END_PI' prefix: 'Password' PrivilegesRequired: body: 'PrivilegesRequired=${1:admin|none|poweruser|lowest}$0' prefix: 'PrivilegesRequired' ReserveBytes: body: 'ReserveBytes=${1:0}$0' prefix: 'ReserveBytes' RestartApplications: body: 'RestartApplications=${1:yes|no}$0' prefix: 'RestartApplications' RestartIfNeededByRun: body: 'RestartIfNeededByRun=${1:yes|no}$0' prefix: 'RestartIfNeededByRun' Root: body: 'Root: ${1}$0' prefix: 'Root' SetupIconFile: body: 'SetupIconFile=${1}$0' prefix: 'SetupIconFile' SetupLogging: body: 'SetupLogging=${1:no|yes}$0' prefix: 'SetupLogging' ShowComponentSizes: body: 'ShowComponentSizes=${1:yes|no}$0' prefix: 'ShowComponentSizes' ShowLanguageDialog: body: 'ShowLanguageDialog=${1:yes|no|auto}$0' prefix: 'ShowLanguageDialog' ShowTasksTreeLines: body: 'ShowTasksTreeLines=${1:no|yes}$0' prefix: 'ShowTasksTreeLines' ShowUndisplayableLanguages: body: 'ShowUndisplayableLanguages=${1:no|yes}$0' prefix: 'ShowUndisplayableLanguages' SignTool: body: 'SignTool=${1}$0' prefix: 'SignTool' SignToolMinimumTimeBetween: body: 'SignToolMinimumTimeBetween=${1:0}$0' prefix: 'SignToolMinimumTimeBetween' SignToolRetryCount: body: 'SignToolRetryCount=${1:2}$0' prefix: 'SignToolRetryCount' SignToolRetryDelay: body: 'SignToolRetryDelay=${1:500}$0' prefix: 'SignToolRetryDelay' SignedUninstaller: body: 'SignedUninstaller=${1:yes|no}$0' prefix: 'SignedUninstaller' SignedUninstallerDir: body: 'SignedUninstallerDir=${1}$0' prefix: 'SignedUninstallerDir' SlicesPerDisk: body: 'SlicesPerDisk=${1:1}$0' prefix: 'SlicesPerDisk' SolidCompression: body: 'SolidCompression=${1:no|yes}$0' prefix: 'SolidCompression' Source: body: 'Source: ${1}$0' prefix: 'Source' SourceDir: body: 'SourceDir=${1}$0' prefix: 'SourceDir' StatusMsg: body: 'StatusMsg: ${1}$0' prefix: 'StatusMsg' Subkey: body: 'Subkey: ${1}$0' prefix: 'Subkey' TerminalServicesAware: body: 'TerminalServicesAware=${1:yes|no}$0' prefix: 'TerminalServicesAware' TimeStampRounding: body: 'TimeStampRounding=${1:2}$0' prefix: 'TimeStampRounding' TimeStampsInUTC: body: 'TimeStampsInUTC=${1:no|yes}$0' prefix: 'TimeStampsInUTC' TouchDate: body: 'TouchDate=${1:current|none|YYYY-MM-DD}$0' prefix: 'TouchDate' TouchTime: body: 'TouchTime=${1:current|none|HH:MM|HH:MM:SS}$0' prefix: 'TouchTime' Type: body: 'Type: ${1}$0' prefix: 'Type' Types: body: 'Types: ${1}$0' prefix: 'Types' UninstallDisplayIcon: body: 'UninstallDisplayIcon=${1}$0' prefix: 'UninstallDisplayIcon' UninstallDisplayName: body: 'UninstallDisplayName=${1}$0' prefix: 'UninstallDisplayName' UninstallDisplaySize: body: 'UninstallDisplaySize=${1}$0' prefix: 'UninstallDisplaySize' UninstallFilesDir: body: 'UninstallFilesDir=${1:{app}}$0' prefix: 'UninstallFilesDir' UninstallLogMode: body: 'UninstallLogMode=${1:append|new|overwrite}$0' prefix: 'UninstallLogMode' UninstallRestartComputer: body: 'UninstallRestartComputer=${1:no|yes}$0' prefix: 'UninstallRestartComputer' Uninstallable: body: 'Uninstallable=${1:yes|no}$0' prefix: 'Uninstallable' UpdateUninstallLogAppName: body: 'UpdateUninstallLogAppName=${1:yes|no}$0' prefix: 'UpdateUninstallLogAppName' UsePreviousAppDir: body: 'UsePreviousAppDir=${1:yes|no}$0' prefix: 'UsePreviousAppDir' UsePreviousGroup: body: 'UsePreviousGroup=${1:yes|no}$0' prefix: 'UsePreviousGroup' UsePreviousLanguage: body: 'UsePreviousLanguage=${1:yes|no}$0' prefix: 'UsePreviousLanguage' UsePreviousSetupType: body: 'UsePreviousSetupType=${1:yes|no}$0' prefix: 'UsePreviousSetupType' UsePreviousTasks: body: 'UsePreviousTasks=${1:yes|no}$0' prefix: 'UsePreviousTasks' UsePreviousUserInfo: body: 'UsePreviousUserInfo=${1:yes|no}$0' prefix: 'UsePreviousUserInfo' UseSetupLdr: body: 'UseSetupLdr=${1:yes|no}$0' prefix: 'UseSetupLdr' UserInfoPage: body: 'UserInfoPage=${1:no|yes}$0' prefix: 'UserInfoPage' ValueData: body: 'ValueData: ${1}$0' prefix: 'ValueData' ValueName: body: 'ValueName: ${1}$0' prefix: 'ValueName' ValueType: body: 'ValueType: ${1}$0' prefix: 'ValueType' VersionInfoCompany: body: 'VersionInfoCompany=${1:AppPublisher}$0' prefix: 'VersionInfoCompany' VersionInfoCopyright: body: 'VersionInfoCopyright=${1:AppCopyright}$0' prefix: 'VersionInfoCopyright' VersionInfoDescription: body: 'VersionInfoDescription=${1:AppName Setup}$0' prefix: 'VersionInfoDescription' VersionInfoOriginalFileName: body: 'VersionInfoOriginalFileName=${1:FileName}$0' prefix: 'VersionInfoOriginalFileName' VersionInfoProductName: body: 'VersionInfoProductName=${1:AppName}$0' prefix: 'VersionInfoProductName' VersionInfoProductTextVersion: body: 'VersionInfoProductTextVersion=${1:VersionInfoProductVersion}$0' prefix: 'VersionInfoProductTextVersion' VersionInfoProductVersion: body: 'VersionInfoProductVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoProductVersion' VersionInfoTextVersion: body: 'VersionInfoTextVersion=${1:VersionInfoVersion}$0' prefix: 'VersionInfoTextVersion' VersionInfoVersion: body: 'VersionInfoVersion=${1:0}.${2:0}.${3:0}.${4:0}$0' prefix: 'VersionInfoVersion' WindowResizable: body: 'WindowResizable=${1:yes|no}$0' prefix: 'WindowResizable' WindowShowCaption: body: 'WindowShowCaption=${1:yes|no}$0' prefix: 'WindowShowCaption' WindowStartMaximized: body: 'WindowStartMaximized=${1:yes|no}$0' prefix: 'WindowStartMaximized' WindowVisible: body: 'WindowVisible=${1:no|yes}$0' prefix: 'WindowVisible' WizardImageBackColor: body: 'WizardImageBackColor=${1:\\$${2:BB}${3:GG}${4:RR}}$0' prefix: 'WizardImageBackColor' WizardImageFile: body: 'WizardImageFile=${1:compiler:WIZMODERNIMAGE.BMP}$0' prefix: 'WizardImageFile' WizardImageStretch: body: 'WizardImageStretch=${1:yes|no}$0' prefix: 'WizardImageStretch' WizardSmallImageFile: body: 'WizardSmallImageFile=${1:compiler:WIZMODERNSMALLIMAGE.BMP}$0' prefix: 'WizardSmallImageFile' WorkingDir: body: 'WorkingDir: ${1}$0' prefix: 'WorkingDir' admin: body: 'admin$0' prefix: 'admin' allowunsafefiles: body: 'allowunsafefiles$0' prefix: 'allowunsafefiles' append: body: 'append$0' prefix: 'append' auto: body: 'auto$0' prefix: 'auto' binary: body: 'binary$0' prefix: 'binary' bzip: body: 'bzip$0' prefix: 'bzip' checkablealone: body: 'checkablealone$0' prefix: 'checkablealone' checkedonce: body: 'checkedonce$0' prefix: 'checkedonce' clAqua: body: 'clAqua$0' prefix: 'clAqua' clBlack: body: 'clBlack$0' prefix: 'clBlack' clBlue: body: 'clBlue$0' prefix: 'clBlue' clFuchsia: body: 'clFuchsia$0' prefix: 'clFuchsia' clGray: body: 'clGray$0' prefix: 'clGray' clGreen: body: 'clGreen$0' prefix: 'clGreen' clLime: body: 'clLime$0' prefix: 'clLime' clMaroon: body: 'clMaroon$0' prefix: 'clMaroon' clNavy: body: 'clNavy$0' prefix: 'clNavy' clOlive: body: 'clOlive$0' prefix: 'clOlive' clPurple: body: 'clPurple$0' prefix: 'clPurple' clRed: body: 'clRed$0' prefix: 'clRed' clSilver: body: 'clSilver$0' prefix: 'clSilver' clTeal: body: 'clTeal$0' prefix: 'clTeal' clWhite: body: 'clWhite$0' prefix: 'clWhite' clYellow: body: 'clYellow$0' prefix: 'clYellow' closeonexit: body: 'closeonexit$0' prefix: 'closeonexit' compact: body: 'compact$0' prefix: 'compact' comparetimestamp: body: 'comparetimestamp$0' prefix: 'comparetimestamp' compiler: body: 'compiler$0' prefix: 'compiler' confirmoverwrite: body: 'confirmoverwrite$0' prefix: 'confirmoverwrite' createallsubdirs: body: 'createallsubdirs$0' prefix: 'createallsubdirs' createkeyifdoesntexist: body: 'createkeyifdoesntexist$0' prefix: 'createkeyifdoesntexist' createonlyiffileexists: body: 'createonlyiffileexists$0' prefix: 'createonlyiffileexists' createvalueifdoesntexist: body: 'createvalueifdoesntexist$0' prefix: 'createvalueifdoesntexist' current: body: 'current$0' prefix: 'current' custom: body: 'custom$0' prefix: 'custom' deleteafterinstall: body: 'deleteafterinstall$0' prefix: 'deleteafterinstall' deletekey: body: 'deletekey$0' prefix: 'deletekey' deletevalue: body: 'deletevalue$0' prefix: 'deletevalue' desktopicon: body: 'desktopicon$0' prefix: 'desktopicon' dirifempty: body: 'dirifempty$0' prefix: 'dirifempty' disablenouninstallwarning: body: 'disablenouninstallwarning$0' prefix: 'disablenouninstallwarning' dontcloseonexit: body: 'dontcloseonexit$0' prefix: 'dontcloseonexit' dontcopy: body: 'dontcopy$0' prefix: 'dontcopy' dontcreatekey: body: 'dontcreatekey$0' prefix: 'dontcreatekey' dontinheritcheck: body: 'dontinheritcheck$0' prefix: 'dontinheritcheck' dontverifychecksum: body: 'dontverifychecksum$0' prefix: 'dontverifychecksum' dword: body: 'dword$0' prefix: 'dword' excludefromshowinnewinstall: body: 'excludefromshowinnewinstall$0' prefix: 'excludefromshowinnewinstall' exclusive: body: 'exclusive$0' prefix: 'exclusive' expandsz: body: 'expandsz$0' prefix: 'expandsz' external: body: 'external$0' prefix: 'external' fast: body: 'fast$0' prefix: 'fast' files: body: 'files$0' prefix: 'files' filesandordirs: body: 'filesandordirs$0' prefix: 'filesandordirs' fixed: body: 'fixed$0' prefix: 'fixed' foldershortcut: body: 'foldershortcut$0' prefix: 'foldershortcut' fontisnttruetype: body: 'fontisnttruetype$0' prefix: 'fontisnttruetype' full: body: 'full$0' prefix: 'full' gacinstall: body: 'gacinstall$0' prefix: 'gacinstall' help: body: 'help$0' prefix: 'help' hidewizard: body: 'hidewizard$0' prefix: 'hidewizard' ia64: body: 'ia64$0' prefix: 'ia64' ignoreversion: body: 'ignoreversion$0' prefix: 'ignoreversion' iscustom: body: 'iscustom$0' prefix: 'iscustom' isreadme: body: 'isreadme$0' prefix: 'isreadme' lefttoright: body: 'lefttoright$0' prefix: 'lefttoright' locale: body: 'locale$0' prefix: 'locale' lowest: body: 'lowest$0' prefix: 'lowest' lzma: body: 'lzma$0' prefix: 'lzma' lzma2: body: 'lzma2$0' prefix: 'lzma2' main: body: 'main$0' prefix: 'main' max: body: 'max$0' prefix: 'max' modify: body: 'modify$0' prefix: 'modify' multisz: body: 'multisz$0' prefix: 'multisz' new: body: 'new$0' prefix: 'new' no: body: 'no$0' prefix: 'no' nocompression: body: 'nocompression$0' prefix: 'nocompression' noencryption: body: 'noencryption$0' prefix: 'noencryption' noerror: body: 'noerror$0' prefix: 'noerror' none: body: 'none$0' prefix: 'none' noregerror: body: 'noregerror$0' prefix: 'noregerror' normal: body: 'normal$0' prefix: 'normal' nowait: body: 'nowait$0' prefix: 'nowait' onlyifdoesntexist: body: 'onlyifdoesntexist$0' prefix: 'onlyifdoesntexist' overwrite: body: 'overwrite$0' prefix: 'overwrite' overwritereadonly: body: 'overwritereadonly$0' prefix: 'overwritereadonly' postinstall: body: 'postinstall$0' prefix: 'postinstall' poweruser: body: 'poweruser$0' prefix: 'poweruser' preservestringtype: body: 'preservestringtype$0' prefix: 'preservestringtype' preventpinning: body: 'preventpinning$0' prefix: 'preventpinning' program: body: 'program$0' prefix: 'program' promptifolder: body: 'promptifolder$0' prefix: 'promptifolder' qword: body: 'qword$0' prefix: 'qword' read: body: 'read$0' prefix: 'read' readexec: body: 'readexec$0' prefix: 'readexec' readme: body: 'readme$0' prefix: 'readme' recursesubdirs: body: 'recursesubdirs$0' prefix: 'recursesubdirs' regserver: body: 'regserver$0' prefix: 'regserver' regtypelib: body: 'regtypelib$0' prefix: 'regtypelib' replacesameversion: body: 'replacesameversion$0' prefix: 'replacesameversion' restart: body: 'restart$0' prefix: 'restart' restartreplace: body: 'restartreplace$0' prefix: 'restartreplace' runascurrentuser: body: 'runascurrentuser$0' prefix: 'runascurrentuser' runasoriginaluser: body: 'runasoriginaluser$0' prefix: 'runasoriginaluser' runhidden: body: 'runhidden$0' prefix: 'runhidden' runminimized: body: 'runminimized$0' prefix: 'runminimized' setntfscompression: body: 'setntfscompression$0' prefix: 'setntfscompression' sharedfile: body: 'sharedfile$0' prefix: 'sharedfile' shellexec: body: 'shellexec$0' prefix: 'shellexec' skipifdoesntexist: body: 'skipifdoesntexist$0' prefix: 'skipifdoesntexist' skipifnotsilent: body: 'skipifnotsilent$0' prefix: 'skipifnotsilent' skipifsilent: body: 'skipifsilent$0' prefix: 'skipifsilent' skipifsourcedoesntexist: body: 'skipifsourcedoesntexist$0' prefix: 'skipifsourcedoesntexist' solidbreak: body: 'solidbreak$0' prefix: 'solidbreak' sortfilesbyextension: body: 'sortfilesbyextension$0' prefix: 'sortfilesbyextension' sortfilesbyname: body: 'sortfilesbyname$0' prefix: 'sortfilesbyname' string: body: 'string$0' prefix: 'string' toptobottom: body: 'toptobottom$0' prefix: 'toptobottom' touch: body: 'touch$0' prefix: 'touch' uilanguage: body: 'uilanguage$0' prefix: 'uilanguage' ultra: body: 'ultra$0' prefix: 'ultra' unchecked: body: 'unchecked$0' prefix: 'unchecked' uninsalwaysuninstall: body: 'uninsalwaysuninstall$0' prefix: 'uninsalwaysuninstall' uninsclearvalue: body: 'uninsclearvalue$0' prefix: 'uninsclearvalue' uninsdeleteentry: body: 'uninsdeleteentry$0' prefix: 'uninsdeleteentry' uninsdeletekey: body: 'uninsdeletekey$0' prefix: 'uninsdeletekey' uninsdeletekeyifempty: body: 'uninsdeletekeyifempty$0' prefix: 'uninsdeletekeyifempty' uninsdeletesection: body: 'uninsdeletesection$0' prefix: 'uninsdeletesection' uninsdeletesectionifempty: body: 'uninsdeletesectionifempty$0' prefix: 'uninsdeletesectionifempty' uninsdeletevalue: body: 'uninsdeletevalue$0' prefix: 'uninsdeletevalue' uninsneveruninstall: body: 'uninsneveruninstall$0' prefix: 'uninsneveruninstall' uninsnosharedfileprompt: body: 'uninsnosharedfileprompt$0' prefix: 'uninsnosharedfileprompt' uninsremovereadonly: body: 'uninsremovereadonly$0' prefix: 'uninsremovereadonly' uninsrestartdelete: body: 'uninsrestartdelete$0' prefix: 'uninsrestartdelete' unsetntfscompression: body: 'unsetntfscompression$0' prefix: 'unsetntfscompression' useapppaths: body: 'useapppaths$0' prefix: 'useapppaths' waituntilidle: body: 'waituntilidle$0' prefix: 'waituntilidle' waituntilterminated: body: 'waituntilterminated$0' prefix: 'waituntilterminated' x64: body: 'x64$0' prefix: 'x64' x86: body: 'x86$0' prefix: 'x86' yes: body: 'yes$0' prefix: 'yes' zip: body: 'zip$0' prefix: 'zip'
[ { "context": "@fileoverview Tests for wrap-regex rule.\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\n#-----------------------------", "end": 75, "score": 0.9998056888580322, "start": 58, "tag": "NAME", "value": "Nicholas C. Zakas" }, { "context": "ype: 'Literal'\n ]\n ,\n ...
src/tests/rules/wrap-regex.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for wrap-regex rule. # @author Nicholas C. Zakas ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/wrap-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'wrap-regex', rule, valid: [ '(/foo/).test(bar)' '(/foo/ig).test(bar)' '/foo/' 'f = 0' 'a[/b/]' '///foo///.test(bar)' 'x = ///foo///.test(bar)' ] invalid: [ code: '/foo/.test(bar)' output: '(/foo/).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , code: '/foo/ig.test(bar)' output: '(/foo/ig).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , # https://github.com/eslint/eslint/issues/10573 code: 'if(/foo/ig.test(bar)) then ;' output: 'if((/foo/ig).test(bar)) then ;' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] ]
183671
###* # @fileoverview Tests for wrap-regex rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/wrap-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'wrap-regex', rule, valid: [ '(/foo/).test(bar)' '(/foo/ig).test(bar)' '/foo/' 'f = 0' 'a[/b/]' '///foo///.test(bar)' 'x = ///foo///.test(bar)' ] invalid: [ code: '/foo/.test(bar)' output: '(/foo/).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , code: '/foo/ig.test(bar)' output: '(/foo/ig).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , # https://github.com/eslint/eslint/issues/10573 code: 'if(/foo/ig.test(bar)) then ;' output: 'if((/foo/ig).test(bar)) then ;' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] ]
true
###* # @fileoverview Tests for wrap-regex rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/wrap-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'wrap-regex', rule, valid: [ '(/foo/).test(bar)' '(/foo/ig).test(bar)' '/foo/' 'f = 0' 'a[/b/]' '///foo///.test(bar)' 'x = ///foo///.test(bar)' ] invalid: [ code: '/foo/.test(bar)' output: '(/foo/).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , code: '/foo/ig.test(bar)' output: '(/foo/ig).test(bar)' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] , # https://github.com/eslint/eslint/issues/10573 code: 'if(/foo/ig.test(bar)) then ;' output: 'if((/foo/ig).test(bar)) then ;' errors: [ message: 'Wrap the regexp literal in parens to disambiguate the slash.' type: 'Literal' ] ]
[ { "context": "cope.signin = ->\n# $scope.credentials.email = 'juan@joukou.co'\n# $scope.credentials.password = 'juantest11'\n", "end": 2376, "score": 0.99992835521698, "start": 2362, "tag": "EMAIL", "value": "juan@joukou.co" }, { "context": "an@joukou.co'\n# $scope.credentia...
src/app/signin/signin.coffee
joukou/joukou-control
0
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This is the module for the signin form. ### SignInCtrl = ( $scope, $rootScope, AuthService, $base64, $location, ApiService ) -> ###* The controller for the signin form. It is decoupled from the actual authentication logic in the ngJoukou.auth module. Based on https://medium.com/opinionated-angularjs/7bbf0346acec ### $scope.credentials = email: '' message: '' password: '' $scope.signupForm = null $scope.submitted = false $scope.showErrorMessage = false $scope.existingUser = false $scope.apiError = null $scope.cannotAccessApi = ApiService.isNotAvailable() $scope.navigateToPersona = -> $location.path( "/persona" ).replace() $scope.$apply() $scope.setAuthorizationHeader = (authHeader) -> Hyperagent.configure("ajax", ajax = (options) -> options.headers = { Authorization: authHeader } jQuery.ajax(options) ) $scope.executeLogin = -> _gaq.push(['_trackEvent', 'SignIn', 'Attempt', $scope.credentials.email]) username = $scope.credentials.email password = $scope.credentials.password authHeader = 'Basic ' + $base64.encode(username + ':' + password) $scope.setAuthorizationHeader(authHeader) ApiService.executeLink('joukou:agent-authn').then( (user) -> _gaq.push(['_trackEvent', 'SignIn', 'Success', $scope.credentials.email]) $rootScope.authenticated = true ApiService.saveLinks(user.links) $scope.navigateToPersona() ).fail( (error) -> _gaq.push(['_trackEvent', 'SignIn', 'Fail', $scope.credentials.email]) #console.warn("Error fetching API root", error) $rootScope.authenticated = false $scope.apiError = 'An error has occured while contacting the API' ) $scope.signin = -> # $scope.credentials.email = 'juan@joukou.co' # $scope.credentials.password = 'juantest11' # $scope.executeLogin() $scope.submitted = true $scope.signinForm.$setDirty( true ) return if $scope.signinForm.$invalid $scope.executeLogin() $scope.signup = -> $scope.submitted = true $scope.signupForm.$setDirty( true ) return if $scope.signupForm.$invalid _gaq.push(['_trackEvent', 'SignUp', 'Attempt', $scope.credentials.email]) ApiService.executeLink('joukou:agent-create',{ data: $scope.credentials }).then( (user) -> _gaq.push(['_trackEvent', 'SignUp', 'Success', $scope.credentials.email]) $scope.executeLogin() ) .fail( (error) -> _gaq.push(['_trackEvent', 'SignUp', 'Fail', $scope.credentials.email]) console.warn("Error fetching API root", error) $scope.apiError = 'An error has occured while contacting the API' ) $scope.showError = -> return ($scope.submitted and $scope.signupForm.$dirty and $scope.signupForm.$invalid) or $scope.cannotAccessApi or $scope.apiError $scope.getErrorMessage = -> return "" unless $scope.showError() return "The API cannot be accessed at this time" if $scope.cannotAccessApi return "An error has occured" unless $scope.submitted return $scope.apiError if $scope.apiError return "An email address is required" if $scope.signupForm.email.$error.required return "Please enter a valid email address" if $scope.signupForm.email.$error.email return "Password is required" if $scope.signupForm.password.$error.required return "Password must be at least 6 characters" if $scope.signupForm.password.$error.minlength "An error has occured" SignInCtrl.$inject = ['$scope', '$rootScope', 'AuthService', '$base64', '$location', 'ApiService'] Config = ( $stateProvider ) -> $stateProvider.state( 'signin', url: '/signin' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign In' existingUser: true ) $stateProvider.state( 'signup', url: '/signup' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign Up' existingUser: false ) Config.$inject = ['$stateProvider'] angular.module( 'ngJoukou.signin', [ 'ngJoukou.auth' 'ui.router' 'base64' 'ngJoukou.api' ] ) .config(Config) .controller( 'SignInCtrl', SignInCtrl)
45122
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This is the module for the signin form. ### SignInCtrl = ( $scope, $rootScope, AuthService, $base64, $location, ApiService ) -> ###* The controller for the signin form. It is decoupled from the actual authentication logic in the ngJoukou.auth module. Based on https://medium.com/opinionated-angularjs/7bbf0346acec ### $scope.credentials = email: '' message: '' password: '' $scope.signupForm = null $scope.submitted = false $scope.showErrorMessage = false $scope.existingUser = false $scope.apiError = null $scope.cannotAccessApi = ApiService.isNotAvailable() $scope.navigateToPersona = -> $location.path( "/persona" ).replace() $scope.$apply() $scope.setAuthorizationHeader = (authHeader) -> Hyperagent.configure("ajax", ajax = (options) -> options.headers = { Authorization: authHeader } jQuery.ajax(options) ) $scope.executeLogin = -> _gaq.push(['_trackEvent', 'SignIn', 'Attempt', $scope.credentials.email]) username = $scope.credentials.email password = $scope.credentials.password authHeader = 'Basic ' + $base64.encode(username + ':' + password) $scope.setAuthorizationHeader(authHeader) ApiService.executeLink('joukou:agent-authn').then( (user) -> _gaq.push(['_trackEvent', 'SignIn', 'Success', $scope.credentials.email]) $rootScope.authenticated = true ApiService.saveLinks(user.links) $scope.navigateToPersona() ).fail( (error) -> _gaq.push(['_trackEvent', 'SignIn', 'Fail', $scope.credentials.email]) #console.warn("Error fetching API root", error) $rootScope.authenticated = false $scope.apiError = 'An error has occured while contacting the API' ) $scope.signin = -> # $scope.credentials.email = '<EMAIL>' # $scope.credentials.password = '<PASSWORD>' # $scope.executeLogin() $scope.submitted = true $scope.signinForm.$setDirty( true ) return if $scope.signinForm.$invalid $scope.executeLogin() $scope.signup = -> $scope.submitted = true $scope.signupForm.$setDirty( true ) return if $scope.signupForm.$invalid _gaq.push(['_trackEvent', 'SignUp', 'Attempt', $scope.credentials.email]) ApiService.executeLink('joukou:agent-create',{ data: $scope.credentials }).then( (user) -> _gaq.push(['_trackEvent', 'SignUp', 'Success', $scope.credentials.email]) $scope.executeLogin() ) .fail( (error) -> _gaq.push(['_trackEvent', 'SignUp', 'Fail', $scope.credentials.email]) console.warn("Error fetching API root", error) $scope.apiError = 'An error has occured while contacting the API' ) $scope.showError = -> return ($scope.submitted and $scope.signupForm.$dirty and $scope.signupForm.$invalid) or $scope.cannotAccessApi or $scope.apiError $scope.getErrorMessage = -> return "" unless $scope.showError() return "The API cannot be accessed at this time" if $scope.cannotAccessApi return "An error has occured" unless $scope.submitted return $scope.apiError if $scope.apiError return "An email address is required" if $scope.signupForm.email.$error.required return "Please enter a valid email address" if $scope.signupForm.email.$error.email return "Password is required" if $scope.signupForm.password.$error.required return "Password must be at least 6 characters" if $scope.signupForm.password.$error.minlength "An error has occured" SignInCtrl.$inject = ['$scope', '$rootScope', 'AuthService', '$base64', '$location', 'ApiService'] Config = ( $stateProvider ) -> $stateProvider.state( 'signin', url: '/signin' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign In' existingUser: true ) $stateProvider.state( 'signup', url: '/signup' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign Up' existingUser: false ) Config.$inject = ['$stateProvider'] angular.module( 'ngJoukou.signin', [ 'ngJoukou.auth' 'ui.router' 'base64' 'ngJoukou.api' ] ) .config(Config) .controller( 'SignInCtrl', SignInCtrl)
true
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This is the module for the signin form. ### SignInCtrl = ( $scope, $rootScope, AuthService, $base64, $location, ApiService ) -> ###* The controller for the signin form. It is decoupled from the actual authentication logic in the ngJoukou.auth module. Based on https://medium.com/opinionated-angularjs/7bbf0346acec ### $scope.credentials = email: '' message: '' password: '' $scope.signupForm = null $scope.submitted = false $scope.showErrorMessage = false $scope.existingUser = false $scope.apiError = null $scope.cannotAccessApi = ApiService.isNotAvailable() $scope.navigateToPersona = -> $location.path( "/persona" ).replace() $scope.$apply() $scope.setAuthorizationHeader = (authHeader) -> Hyperagent.configure("ajax", ajax = (options) -> options.headers = { Authorization: authHeader } jQuery.ajax(options) ) $scope.executeLogin = -> _gaq.push(['_trackEvent', 'SignIn', 'Attempt', $scope.credentials.email]) username = $scope.credentials.email password = $scope.credentials.password authHeader = 'Basic ' + $base64.encode(username + ':' + password) $scope.setAuthorizationHeader(authHeader) ApiService.executeLink('joukou:agent-authn').then( (user) -> _gaq.push(['_trackEvent', 'SignIn', 'Success', $scope.credentials.email]) $rootScope.authenticated = true ApiService.saveLinks(user.links) $scope.navigateToPersona() ).fail( (error) -> _gaq.push(['_trackEvent', 'SignIn', 'Fail', $scope.credentials.email]) #console.warn("Error fetching API root", error) $rootScope.authenticated = false $scope.apiError = 'An error has occured while contacting the API' ) $scope.signin = -> # $scope.credentials.email = 'PI:EMAIL:<EMAIL>END_PI' # $scope.credentials.password = 'PI:PASSWORD:<PASSWORD>END_PI' # $scope.executeLogin() $scope.submitted = true $scope.signinForm.$setDirty( true ) return if $scope.signinForm.$invalid $scope.executeLogin() $scope.signup = -> $scope.submitted = true $scope.signupForm.$setDirty( true ) return if $scope.signupForm.$invalid _gaq.push(['_trackEvent', 'SignUp', 'Attempt', $scope.credentials.email]) ApiService.executeLink('joukou:agent-create',{ data: $scope.credentials }).then( (user) -> _gaq.push(['_trackEvent', 'SignUp', 'Success', $scope.credentials.email]) $scope.executeLogin() ) .fail( (error) -> _gaq.push(['_trackEvent', 'SignUp', 'Fail', $scope.credentials.email]) console.warn("Error fetching API root", error) $scope.apiError = 'An error has occured while contacting the API' ) $scope.showError = -> return ($scope.submitted and $scope.signupForm.$dirty and $scope.signupForm.$invalid) or $scope.cannotAccessApi or $scope.apiError $scope.getErrorMessage = -> return "" unless $scope.showError() return "The API cannot be accessed at this time" if $scope.cannotAccessApi return "An error has occured" unless $scope.submitted return $scope.apiError if $scope.apiError return "An email address is required" if $scope.signupForm.email.$error.required return "Please enter a valid email address" if $scope.signupForm.email.$error.email return "Password is required" if $scope.signupForm.password.$error.required return "Password must be at least 6 characters" if $scope.signupForm.password.$error.minlength "An error has occured" SignInCtrl.$inject = ['$scope', '$rootScope', 'AuthService', '$base64', '$location', 'ApiService'] Config = ( $stateProvider ) -> $stateProvider.state( 'signin', url: '/signin' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign In' existingUser: true ) $stateProvider.state( 'signup', url: '/signup' views: main: controller: 'SignInCtrl' templateUrl: 'app/signin/signin.html' data: pageTitle: 'Sign Up' existingUser: false ) Config.$inject = ['$stateProvider'] angular.module( 'ngJoukou.signin', [ 'ngJoukou.auth' 'ui.router' 'base64' 'ngJoukou.api' ] ) .config(Config) .controller( 'SignInCtrl', SignInCtrl)
[ { "context": " of completions, eg:\n # { \"Giraffe (Giraffa camelopardalis)\": {\n ", "end": 20184, "score": 0.7170422077178955, "start": 20183, "tag": "NAME", "value": "G" } ]
webapp/climasng/src/coffee/mapview/views/app.coffee
jcu-eresearch/wallace-3
0
# $ = require 'jquery' # _ = require 'lodash' # Backbone = require 'backbone' # L = require 'leaflet' MapLayer = require '../models/maplayer' require '../util/shims' # disable the jshint warning about "did you mean to return a # conditional" which crops up all the time in coffeescript compiled # code. ### jshint -W093 ### # ------------------------------------------------------------------- debug = (itemToLog, itemLevel)-> levels = ['verydebug', 'debug', 'message', 'warning'] itemLevel = 'debug' unless itemLevel # threshold = 'verydebug' threshold = 'debug' # threshold = 'message' thresholdNum = levels.indexOf threshold messageNum = levels.indexOf itemLevel return if thresholdNum > messageNum if itemToLog + '' == itemToLog # it's a string.. console.log "[#{itemLevel}] #{itemToLog}" else console.log itemToLog # ------------------------------------------------------------------- # ------------------------------------------------------------------- AppView = Backbone.View.extend { # --------------------------------------------------------------- # this view's base element tagName: 'div' className: 'splitmap showforms' id: 'splitmap' # --------------------------------------------------------------- # some settings speciesDataUrl: window.mapConfig.speciesDataUrl climateDataUrl: window.mapConfig.climateDataUrl summariesDataUrl: window.mapConfig.summariesDataUrl biodivDataUrl: window.mapConfig.biodivDataUrl rasterApiUrl: window.mapConfig.rasterApiUrl # --------------------------------------------------------------- # tracking the splitter bar trackSplitter: false trackPeriod: 100 # --------------------------------------------------------------- events: 'click .btn-change': 'toggleForms' 'click .btn-compare': 'toggleSplitter' 'click .btn-copy.left-valid-map': 'copyMapLeftToRight' 'click .btn-copy.right-valid-map': 'copyMapRightToLeft' 'leftmapupdate': 'leftSideUpdate' 'rightmapupdate': 'rightSideUpdate' 'change select.left': 'leftSideUpdate' 'change select.right': 'rightSideUpdate' 'change input.left': 'leftSideUpdate' 'change input.right': 'rightSideUpdate' 'change #sync': 'toggleSync' # --------------------------------------------------------------- tick: ()-> # if @map if false # if @leftInfo # debug @map.getPixelOrigin() debug @leftInfo.scenario else debug 'tick' setTimeout(@tick, 1000) # --------------------------------------------------------------- initialize: ()-> debug 'AppView.initialize' # more annoying version of bindAll requires this concat stuff _.bindAll.apply _, [this].concat _.functions(this) @nameIndex = {} # map of nice name -to-> "id name" @mapList = {} # map of "id name" -to-> url, type etc # @sideUpdate('left') # @tick() # --------------------------------------------------------------- render: ()-> debug 'AppView.render' @$el.append AppView.templates.layout { leftTag: AppView.templates.leftTag() rightTag: AppView.templates.rightTag() leftForm: AppView.templates.leftForm() rightForm: AppView.templates.rightForm() } $('#contentwrap').append @$el @map = L.map 'map', { center: [0, 0] zoom: 2 } @map.on 'move', @resizeThings # add a distance scale bar L.control.scale().addTo @map # add a legend @legend = L.control {uri: ''} @legend.onAdd = (map)=> this._div = L.DomUtil.create 'div', 'info' @legend.update = (props)=> this._div.innerHTML = '<object type="image/svg+xml" data="' + (if props then props.uri else '.') + '" />' @legend.addTo @map ## removed MapQuest base layer 2016-07-20 due to licencing changes # L.tileLayer('https://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { # subdomains: '1234' # maxZoom: 18 # attribution: ''' # Map data &copy; <a href="https://openstreetmap.org">OpenStreetMap</a>, # tiles &copy; <a href="https://www.mapquest.com/" target="_blank">MapQuest</a> # ''' # }).addTo @map # ## replaced with HERE maps base layer ## removing HERE maps base layer # L.tileLayer('https://{s}.{base}.maps.cit.api.here.com/maptile/2.1/{type}/{mapID}/{scheme}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', { # attribution: 'Map &copy; 2016 <a href="https://developer.here.com">HERE</a>' # subdomains: '1234' # base: 'aerial' # type: 'maptile' # scheme: 'terrain.day' # app_id: 'l2Rye6zwq3u2cHZpVIPO' # app_code: 'MpXSlNLcLSQIpdU6XHB0TQ' # mapID: 'newest' # maxZoom: 18 # language: 'eng' # format: 'png8' # size: '256' # }).addTo @map ## switching to ESRI baselayer L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri' variant: 'World_Topo_Map' }).addTo @map @leftForm = @$ '.left.form' @buildForm 'left' @rightForm = @$ '.right.form' @buildForm 'right' @leftTag = @$ '.left.tag' @rightTag = @$ '.right.tag' @splitLine = @$ '.splitline' @splitThumb = @$ '.splitthumb' @leftSideUpdate() @rightSideUpdate() # show the splitter by default @toggleSplitter() # --------------------------------------------------------------- resolvePlaceholders: (strWithPlaceholders, replacements)-> ans = strWithPlaceholders ans = ans.replace /\{\{\s*location.protocol\s*\}\}/g, location.protocol ans = ans.replace /\{\{\s*location.host\s*\}\}/g, location.host ans = ans.replace /\{\{\s*location.hostname\s*\}\}/g, location.hostname for key, value of replacements re = new RegExp "\\{\\{\\s*" + key + "\\s*\\}\\}", "g" ans = ans.replace re, value ans # --------------------------------------------------------------- # --------------------------------------------------------------- # map interaction # --------------------------------------------------------------- copyMapLeftToRight: ()-> debug 'AppView.copyMapLeftToRight' return unless @leftInfo @$('#rightmapspp').val @leftInfo.mapName @$('#rightmapyear').val @leftInfo.year @$('input[name=rightmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @leftInfo.scenario) @$('#rightmapgcm').val @leftInfo.gcm @rightSideUpdate() # --------------------------------------------------------------- copyMapRightToLeft: ()-> debug 'AppView.copyMapRightToLeft' return unless @rightInfo @$('#leftmapspp').val @rightInfo.mapName @$('#leftmapyear').val @rightInfo.year @$('input[name=leftmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @rightInfo.scenario) @$('#leftmapgcm').val @rightInfo.gcm @leftSideUpdate() # --------------------------------------------------------------- sideUpdate: (side)-> debug 'AppView.sideUpdate (' + side + ')' # # Collect info from the form on that side # newInfo = { mapName: @$('#' + side + 'mapspp').val() degs: @$('#' + side + 'mapdegs').val() range: @$('input[name=' + side + 'maprange]:checked').val() confidence: @$('#' + side + 'mapconfidence').val() } # # enable and disable the form parts that don't # apply, eg. if you're looking at baseline, # disable the future-y things # # set disabled for range-adaptation and model-summary-confidence atBaseline = (newInfo.degs == 'baseline') @$("input[name=#{side}maprange], ##{side}mapconfidence").prop 'disabled', atBaseline # now, add a disabled style to the fieldsets holding disabled items @$(".#{side}.side.form fieldset").removeClass 'disabled' @$( "input[name^=#{side}]:disabled, [id^=#{side}]:disabled" ).closest('fieldset').addClass 'disabled' # # check if what they typed is an available map # if newInfo.mapName of @nameIndex # it's real, so enable the things that need valid maps # e.g. downloads, copy to the other side, etc @$(".#{side}-valid-map").removeClass('disabled').prop 'disabled', false else # it's NOT real, disable those things and bail out right now @$(".#{side}-valid-map").addClass('disabled').prop 'disabled', true return false currInfo = if side == 'left' then @leftInfo else @rightInfo # bail if nothing changed return false if currInfo and _.isEqual newInfo, currInfo # also bail if they're both same species at baseline, even # if future-projection stuff differs, coz that's a special # case of being "the same" if ( currInfo and newInfo.mapName == currInfo.mapName and newInfo.degs == currInfo.degs and newInfo.degs == 'baseline' ) return false # if we got here, something has changed. if side is 'left' # save the new setup @leftInfo = newInfo else @rightInfo = newInfo # apply the changes to the map @addMapLayer side # apply the changes to the tag @addMapTag side # --------------------------------------------------------------- leftSideUpdate: ()-> @sideUpdate 'left' if @$('#sync')[0].checked debug 'Sync checked - syncing right side', 'message' @copySppToRightSide() # --------------------------------------------------------------- rightSideUpdate: ()-> return @sideUpdate 'right' # --------------------------------------------------------------- copySppToRightSide: ()-> @$('#rightmapspp').val @$('#leftmapspp').val() @rightSideUpdate() # --------------------------------------------------------------- addMapTag: (side)-> debug 'AppView.addMapTag' info = @leftInfo if side == 'left' info = @rightInfo if side == 'right' tag = "<b><i>#{info.mapName}</i></b>" dispLookup = { 'no.disp': 'no range adaptation' 'real.disp': 'range adaptation' } if info.degs is 'baseline' tag = "baseline #{tag} distribution" else tag = "<b>#{info.confidence}th</b> percentile projections for #{tag} at <b>+#{info.degs}&deg;C</b> with <b>#{dispLookup[info.range]}</b>" if side == 'left' @leftTag.find('.leftlayername').html tag if side == 'right' @rightTag.find('.rightlayername').html tag # --------------------------------------------------------------- addMapLayer: (side)-> debug 'AppView.addMapLayer' sideInfo = @leftInfo if side == 'left' sideInfo = @rightInfo if side == 'right' futureModelPoint = '' mapUrl = '' zipUrl = '' # TODO: use mapInfo.type instead of these booleans isRichness = sideInfo.mapName.startsWith 'Richness -' isRefugia = sideInfo.mapName.startsWith 'Refugia -' isConcern = sideInfo.mapName.startsWith 'Concern -' if isRichness # ...then they've selected a richness map. style = 'taxa-richness-change' projectionName = "prop.richness_#{sideInfo.degs}_#{sideInfo.range}_#{sideInfo.confidence}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' style = 'taxa-richness' else if isRefugia # ...then they've selected a refugia map. style = 'taxa-refugia' projectionName = "refuge.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else if isConcern # ...then they've selected an area-of-concern map. style = 'taxa-aoc' projectionName = "AreaOfConcern.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else # ...it's a plain old species map they're after. style = 'spp-suitability-purple' # work out the string that gets to the projection point they want projectionName = "TEMP_#{sideInfo.degs}_#{sideInfo.confidence}.#{sideInfo.range}" # if they want baseline, just get the baseline projection projectionName = 'current' if sideInfo.degs == 'baseline' mapInfo = @mapList[@nameIndex[sideInfo.mapName]] if mapInfo # set up for the type we're looking at: start by assuming species and tif url = @speciesDataUrl ext = '.tif' # then override as required if mapInfo.type is 'climate' url = @climateDataUrl ext = '.asc' else if mapInfo.type is 'richness' url = @summariesDataUrl # now set the URL for this type of map mapUrl = [ @resolvePlaceholders url, { path: mapInfo.path } projectionName + ext ].join '/' # update the download links @$('#' + side + 'mapdl').attr 'href', mapUrl else console.log "Can't map that -- no '#{sideInfo.mapName}' in index" # at this point we've worked out everything we can about the map # the user is asking for. # now we have to ask for a URL to the geoserver with that map, # and the layerName to use when loading it. # TODO: use a pair of globals (leftfetch and rightfetch) to ensure # early ajaxes are abandoned before starting a new one. $.ajax({ url: '/api/preplayer/' method: 'POST' data: { 'info': mapInfo, 'proj': projectionName } }).done( (data)=> # when the layer prep is complete.. console.log ['layer prepped, answer is ', data] wmsUrl = data.mapUrl wmsLayer = data.layerName # update the download links # TODO: we don't have the url of the map anymore.. # @$('#' + side + 'mapdl').attr 'href', mapUrl # start the map layer loading layer = L.tileLayer.wms wmsUrl, { layers: wmsLayer format: 'image/png' styles: style transparent: true } # add a class to our element when there's tiles loading loadClass = '' + side + 'loading' layer.on 'loading', ()=> @$el.addClass loadClass layer.on 'load', ()=> @$el.removeClass loadClass if side == 'left' @map.removeLayer @leftLayer if @leftLayer @leftLayer = layer if side == 'right' @map.removeLayer @rightLayer if @rightLayer @rightLayer = layer layer.addTo @map # udpate the legend @legend.update {uri: '/static/images/legends/' + style + '.sld.svg'} @resizeThings() # re-establish the splitter ).fail( (jqx, status)=> # when the layer prep has failed.. debug status, 'warning' ) # # update the download links # @$('#' + side + 'mapdl').attr 'href', mapUrl # # we've made a url, start the map layer loading # layer = L.tileLayer.wms @resolvePlaceholders(@rasterApiUrl), { # DATA_URL: mapUrl # layers: 'DEFAULT' # format: 'image/png' # transparent: true # } # # add a class to our element when there's tiles loading # loadClass = '' + side + 'loading' # layer.on 'loading', ()=> @$el.addClass loadClass # layer.on 'load', ()=> @$el.removeClass loadClass # if side == 'left' # @map.removeLayer @leftLayer if @leftLayer # @leftLayer = layer # if side == 'right' # @map.removeLayer @rightLayer if @rightLayer # @rightLayer = layer # layer.addTo @map # @resizeThings() # re-establish the splitter # # if we're local, log the map URL to the console # if window.location.hostname == 'localhost' # console.log 'map URL is: ', mapUrl # # log this as an action in Google Analytics # if ga and typeof(ga) == 'function' # # we have a ga thing which is probaby a google analytics thing. # # "value" is year.percentile, eg. for 90th percentile in 2055, # # we will send 2055.9 as the value. # if sideInfo.year == 'baseline' # val = 1990 # else # val = parseInt(sideInfo.year, 10) # val = val + { 'tenth': 0.1, 'fiftieth': 0.5, 'ninetieth': 0.9 }[sideInfo.gcm] # ga('send', { # 'hitType': 'event', # 'eventCategory': 'mapshow', # 'eventAction': sideInfo.mapName, # 'eventLabel': sideInfo.scenario, # 'eventValue': val # }) # --------------------------------------------------------------- # --------------------------------------------------------------- # UI actions # --------------------------------------------------------------- centreMap: (repeatedlyFor)-> debug 'AppView.centreMap' repeatedlyFor = 500 unless repeatedlyFor recentre = ()=> @map.invalidateSize(false) @resizeThings() setTimeout( recentre, later ) for later in [0..repeatedlyFor] by 25 # --------------------------------------------------------------- toggleForms: ()-> debug 'AppView.toggleForms' @$el.toggleClass 'showforms' @centreMap() # --------------------------------------------------------------- toggleSplitter: ()-> debug 'AppView.toggleSplitter' @$el.toggleClass 'split' if @$el.hasClass 'split' @activateSplitter() else @deactivateSplitter() @centreMap() # --------------------------------------------------------------- toggleSync: ()-> debug 'AppView.toggleSync' if @$('#sync')[0].checked # .. checked now, so was unchecked before @$('.rightmapspp').prop 'disabled', true @copySppToRightSide() else @$('.rightmapspp').prop 'disabled', false # --------------------------------------------------------------- # --------------------------------------------------------------- # form creation # --------------------------------------------------------------- buildForm: (side)-> debug 'AppView.buildForm' $mapspp = @$ "##{side}mapspp" $mapspp.autocomplete { delay: 200 close: => @$el.trigger "#{side}mapupdate" source: (req, response)=> $.ajax { url: '/api/mapsearch/' data: { term: req.term } success: (answer)=> # answer is a list of completions, eg: # { "Giraffe (Giraffa camelopardalis)": { # "type": "species", # "mapId": "Giraffa camelopardalis", # "path": "..." # }, ... } selectable = [] for nice, info of answer # add each nice name to the completion list selectable.push nice # put the data into our local caches @mapList[info.mapId] = info @nameIndex[nice] = info.mapId console.log answer console.log selectable # finally, give the nice names to the autocomplete response selectable } } # --------------------------------------------------------------- # --------------------------------------------------------------- # splitter handling # --------------------------------------------------------------- startSplitterTracking: ()-> debug 'AppView.startSplitterTracking' @trackSplitter = true @splitLine.addClass 'dragging' @locateSplitter() # --------------------------------------------------------------- locateSplitter: ()-> debug 'AppView.locateSplitter' if @trackSplitter @resizeThings() # decrement remaining track count, unless it's true if @trackSplitter == 0 @trackSplitter = false else if @trackSplitter != true @trackSplitter -= 1 setTimeout @locateSplitter, @trackPeriod # --------------------------------------------------------------- resizeThings: ()-> debug 'AppView.resizeThings' if @leftLayer leftMap = $ @leftLayer.getContainer() if @rightLayer rightMap = $ @rightLayer.getContainer() if @$el.hasClass 'split' # we're still in split mode newLeftWidth = @splitThumb.position().left + (@splitThumb.width() / 2.0) mapBox = @map.getContainer() $mapBox = $ mapBox mapBounds = mapBox.getBoundingClientRect() topLeft = @map.containerPointToLayerPoint [0,0] splitPoint = @map.containerPointToLayerPoint [newLeftWidth, 0] bottomRight = @map.containerPointToLayerPoint [$mapBox.width(), $mapBox.height()] layerTop = topLeft.y layerBottom = bottomRight.y splitX = splitPoint.x - mapBounds.left leftLeft = topLeft.x - mapBounds.left rightRight = bottomRight.x @splitLine.css 'left', newLeftWidth ##### have to use attr to set style, for this to work in frickin IE8. # @leftTag.css 'clip', "rect(0, #{newLeftWidth}px, auto, 0)" @leftTag.attr 'style', "clip: rect(0, #{newLeftWidth}px, auto, 0)" ##### have to use attr to set style, for this to work in IE8. # leftMap.css 'clip', "rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer # rightMap.css 'clip', "rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer leftMap.attr 'style', "clip: rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer rightMap.attr 'style', "clip: rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer else # we're not in split mode (this is probably the last # resizeThings call before exiting split mode), so go # full left side only. ##### have to set style attr for IE8 to work. # @leftTag.css 'clip', 'inherit' # leftMap.css 'clip', 'inherit' if @leftLayer # rightMap.css 'clip', 'rect(0,0,0,0)' if @rightLayer @leftTag.attr 'style', 'clip: inherit' leftMap.attr 'style', 'clip: inherit' if @leftLayer rightMap.attr 'style', 'clip: rect(0,0,0,0)' if @rightLayer # --------------------------------------------------------------- stopSplitterTracking: ()-> debug 'AppView.stopSplitterTracking' @splitLine.removeClass 'dragging' @trackSplitter = 5 # five more resizings, then stop # --------------------------------------------------------------- activateSplitter: ()-> debug 'AppView.activateSplitter' @splitThumb.draggable { containment: $ '#mapwrapper' scroll: false start: @startSplitterTracking drag: @resizeThings stop: @stopSplitterTracking } @resizeThings() # --------------------------------------------------------------- deactivateSplitter: ()-> debug 'AppView.deactivateSplitter' @splitThumb.draggable 'destroy' @resizeThings() # --------------------------------------------------------------- },{ templates: { # ================================================== # templates here # --------------------------------------------------------------- layout: _.template """ <div clas="ui-front"></div> <div class="splitline">&nbsp;</div> <div class="splitthumb"><span>&#x276e; &#x276f;</span></div> <div class="left tag"><%= leftTag %></div> <div class="right tag"><%= rightTag %></div> <div class="left side form"><%= leftForm %></div> <div class="right side form"><%= rightForm %></div> <div class="left loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div class="right loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div id="mapwrapper"><div id="map"></div></div> """ # --------------------------------------------------------------- leftTag: _.template """ <div class="show"> <span class="leftlayername">plain map</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="left syncbox"></label> <input id="leftmapspp" class="left" type="text" name="leftmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- rightTag: _.template """ <div class="show"> <span class="rightlayername">(no distribution)</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="right syncbox"><input id="sync" type="checkbox" value="sync" checked="checked" /> same as left side</label> <input id="rightmapspp" type="text" class="right" name="rightmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- leftForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="left" id="leftmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="leftmaprange" class="left" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="leftmaprange" class="left" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="left" id="leftmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy right-valid-map">copy right map &laquo;</button> <a id="leftmapdl" class="download left-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- rightForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="right" id="rightmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="rightmaprange" class="right" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="rightmaprange" class="right" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="right" id="rightmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy left-valid-map">copy left map &laquo;</button> <a id="rightmapdl" class="download right-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- }} module.exports = AppView
55208
# $ = require 'jquery' # _ = require 'lodash' # Backbone = require 'backbone' # L = require 'leaflet' MapLayer = require '../models/maplayer' require '../util/shims' # disable the jshint warning about "did you mean to return a # conditional" which crops up all the time in coffeescript compiled # code. ### jshint -W093 ### # ------------------------------------------------------------------- debug = (itemToLog, itemLevel)-> levels = ['verydebug', 'debug', 'message', 'warning'] itemLevel = 'debug' unless itemLevel # threshold = 'verydebug' threshold = 'debug' # threshold = 'message' thresholdNum = levels.indexOf threshold messageNum = levels.indexOf itemLevel return if thresholdNum > messageNum if itemToLog + '' == itemToLog # it's a string.. console.log "[#{itemLevel}] #{itemToLog}" else console.log itemToLog # ------------------------------------------------------------------- # ------------------------------------------------------------------- AppView = Backbone.View.extend { # --------------------------------------------------------------- # this view's base element tagName: 'div' className: 'splitmap showforms' id: 'splitmap' # --------------------------------------------------------------- # some settings speciesDataUrl: window.mapConfig.speciesDataUrl climateDataUrl: window.mapConfig.climateDataUrl summariesDataUrl: window.mapConfig.summariesDataUrl biodivDataUrl: window.mapConfig.biodivDataUrl rasterApiUrl: window.mapConfig.rasterApiUrl # --------------------------------------------------------------- # tracking the splitter bar trackSplitter: false trackPeriod: 100 # --------------------------------------------------------------- events: 'click .btn-change': 'toggleForms' 'click .btn-compare': 'toggleSplitter' 'click .btn-copy.left-valid-map': 'copyMapLeftToRight' 'click .btn-copy.right-valid-map': 'copyMapRightToLeft' 'leftmapupdate': 'leftSideUpdate' 'rightmapupdate': 'rightSideUpdate' 'change select.left': 'leftSideUpdate' 'change select.right': 'rightSideUpdate' 'change input.left': 'leftSideUpdate' 'change input.right': 'rightSideUpdate' 'change #sync': 'toggleSync' # --------------------------------------------------------------- tick: ()-> # if @map if false # if @leftInfo # debug @map.getPixelOrigin() debug @leftInfo.scenario else debug 'tick' setTimeout(@tick, 1000) # --------------------------------------------------------------- initialize: ()-> debug 'AppView.initialize' # more annoying version of bindAll requires this concat stuff _.bindAll.apply _, [this].concat _.functions(this) @nameIndex = {} # map of nice name -to-> "id name" @mapList = {} # map of "id name" -to-> url, type etc # @sideUpdate('left') # @tick() # --------------------------------------------------------------- render: ()-> debug 'AppView.render' @$el.append AppView.templates.layout { leftTag: AppView.templates.leftTag() rightTag: AppView.templates.rightTag() leftForm: AppView.templates.leftForm() rightForm: AppView.templates.rightForm() } $('#contentwrap').append @$el @map = L.map 'map', { center: [0, 0] zoom: 2 } @map.on 'move', @resizeThings # add a distance scale bar L.control.scale().addTo @map # add a legend @legend = L.control {uri: ''} @legend.onAdd = (map)=> this._div = L.DomUtil.create 'div', 'info' @legend.update = (props)=> this._div.innerHTML = '<object type="image/svg+xml" data="' + (if props then props.uri else '.') + '" />' @legend.addTo @map ## removed MapQuest base layer 2016-07-20 due to licencing changes # L.tileLayer('https://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { # subdomains: '1234' # maxZoom: 18 # attribution: ''' # Map data &copy; <a href="https://openstreetmap.org">OpenStreetMap</a>, # tiles &copy; <a href="https://www.mapquest.com/" target="_blank">MapQuest</a> # ''' # }).addTo @map # ## replaced with HERE maps base layer ## removing HERE maps base layer # L.tileLayer('https://{s}.{base}.maps.cit.api.here.com/maptile/2.1/{type}/{mapID}/{scheme}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', { # attribution: 'Map &copy; 2016 <a href="https://developer.here.com">HERE</a>' # subdomains: '1234' # base: 'aerial' # type: 'maptile' # scheme: 'terrain.day' # app_id: 'l2Rye6zwq3u2cHZpVIPO' # app_code: 'MpXSlNLcLSQIpdU6XHB0TQ' # mapID: 'newest' # maxZoom: 18 # language: 'eng' # format: 'png8' # size: '256' # }).addTo @map ## switching to ESRI baselayer L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri' variant: 'World_Topo_Map' }).addTo @map @leftForm = @$ '.left.form' @buildForm 'left' @rightForm = @$ '.right.form' @buildForm 'right' @leftTag = @$ '.left.tag' @rightTag = @$ '.right.tag' @splitLine = @$ '.splitline' @splitThumb = @$ '.splitthumb' @leftSideUpdate() @rightSideUpdate() # show the splitter by default @toggleSplitter() # --------------------------------------------------------------- resolvePlaceholders: (strWithPlaceholders, replacements)-> ans = strWithPlaceholders ans = ans.replace /\{\{\s*location.protocol\s*\}\}/g, location.protocol ans = ans.replace /\{\{\s*location.host\s*\}\}/g, location.host ans = ans.replace /\{\{\s*location.hostname\s*\}\}/g, location.hostname for key, value of replacements re = new RegExp "\\{\\{\\s*" + key + "\\s*\\}\\}", "g" ans = ans.replace re, value ans # --------------------------------------------------------------- # --------------------------------------------------------------- # map interaction # --------------------------------------------------------------- copyMapLeftToRight: ()-> debug 'AppView.copyMapLeftToRight' return unless @leftInfo @$('#rightmapspp').val @leftInfo.mapName @$('#rightmapyear').val @leftInfo.year @$('input[name=rightmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @leftInfo.scenario) @$('#rightmapgcm').val @leftInfo.gcm @rightSideUpdate() # --------------------------------------------------------------- copyMapRightToLeft: ()-> debug 'AppView.copyMapRightToLeft' return unless @rightInfo @$('#leftmapspp').val @rightInfo.mapName @$('#leftmapyear').val @rightInfo.year @$('input[name=leftmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @rightInfo.scenario) @$('#leftmapgcm').val @rightInfo.gcm @leftSideUpdate() # --------------------------------------------------------------- sideUpdate: (side)-> debug 'AppView.sideUpdate (' + side + ')' # # Collect info from the form on that side # newInfo = { mapName: @$('#' + side + 'mapspp').val() degs: @$('#' + side + 'mapdegs').val() range: @$('input[name=' + side + 'maprange]:checked').val() confidence: @$('#' + side + 'mapconfidence').val() } # # enable and disable the form parts that don't # apply, eg. if you're looking at baseline, # disable the future-y things # # set disabled for range-adaptation and model-summary-confidence atBaseline = (newInfo.degs == 'baseline') @$("input[name=#{side}maprange], ##{side}mapconfidence").prop 'disabled', atBaseline # now, add a disabled style to the fieldsets holding disabled items @$(".#{side}.side.form fieldset").removeClass 'disabled' @$( "input[name^=#{side}]:disabled, [id^=#{side}]:disabled" ).closest('fieldset').addClass 'disabled' # # check if what they typed is an available map # if newInfo.mapName of @nameIndex # it's real, so enable the things that need valid maps # e.g. downloads, copy to the other side, etc @$(".#{side}-valid-map").removeClass('disabled').prop 'disabled', false else # it's NOT real, disable those things and bail out right now @$(".#{side}-valid-map").addClass('disabled').prop 'disabled', true return false currInfo = if side == 'left' then @leftInfo else @rightInfo # bail if nothing changed return false if currInfo and _.isEqual newInfo, currInfo # also bail if they're both same species at baseline, even # if future-projection stuff differs, coz that's a special # case of being "the same" if ( currInfo and newInfo.mapName == currInfo.mapName and newInfo.degs == currInfo.degs and newInfo.degs == 'baseline' ) return false # if we got here, something has changed. if side is 'left' # save the new setup @leftInfo = newInfo else @rightInfo = newInfo # apply the changes to the map @addMapLayer side # apply the changes to the tag @addMapTag side # --------------------------------------------------------------- leftSideUpdate: ()-> @sideUpdate 'left' if @$('#sync')[0].checked debug 'Sync checked - syncing right side', 'message' @copySppToRightSide() # --------------------------------------------------------------- rightSideUpdate: ()-> return @sideUpdate 'right' # --------------------------------------------------------------- copySppToRightSide: ()-> @$('#rightmapspp').val @$('#leftmapspp').val() @rightSideUpdate() # --------------------------------------------------------------- addMapTag: (side)-> debug 'AppView.addMapTag' info = @leftInfo if side == 'left' info = @rightInfo if side == 'right' tag = "<b><i>#{info.mapName}</i></b>" dispLookup = { 'no.disp': 'no range adaptation' 'real.disp': 'range adaptation' } if info.degs is 'baseline' tag = "baseline #{tag} distribution" else tag = "<b>#{info.confidence}th</b> percentile projections for #{tag} at <b>+#{info.degs}&deg;C</b> with <b>#{dispLookup[info.range]}</b>" if side == 'left' @leftTag.find('.leftlayername').html tag if side == 'right' @rightTag.find('.rightlayername').html tag # --------------------------------------------------------------- addMapLayer: (side)-> debug 'AppView.addMapLayer' sideInfo = @leftInfo if side == 'left' sideInfo = @rightInfo if side == 'right' futureModelPoint = '' mapUrl = '' zipUrl = '' # TODO: use mapInfo.type instead of these booleans isRichness = sideInfo.mapName.startsWith 'Richness -' isRefugia = sideInfo.mapName.startsWith 'Refugia -' isConcern = sideInfo.mapName.startsWith 'Concern -' if isRichness # ...then they've selected a richness map. style = 'taxa-richness-change' projectionName = "prop.richness_#{sideInfo.degs}_#{sideInfo.range}_#{sideInfo.confidence}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' style = 'taxa-richness' else if isRefugia # ...then they've selected a refugia map. style = 'taxa-refugia' projectionName = "refuge.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else if isConcern # ...then they've selected an area-of-concern map. style = 'taxa-aoc' projectionName = "AreaOfConcern.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else # ...it's a plain old species map they're after. style = 'spp-suitability-purple' # work out the string that gets to the projection point they want projectionName = "TEMP_#{sideInfo.degs}_#{sideInfo.confidence}.#{sideInfo.range}" # if they want baseline, just get the baseline projection projectionName = 'current' if sideInfo.degs == 'baseline' mapInfo = @mapList[@nameIndex[sideInfo.mapName]] if mapInfo # set up for the type we're looking at: start by assuming species and tif url = @speciesDataUrl ext = '.tif' # then override as required if mapInfo.type is 'climate' url = @climateDataUrl ext = '.asc' else if mapInfo.type is 'richness' url = @summariesDataUrl # now set the URL for this type of map mapUrl = [ @resolvePlaceholders url, { path: mapInfo.path } projectionName + ext ].join '/' # update the download links @$('#' + side + 'mapdl').attr 'href', mapUrl else console.log "Can't map that -- no '#{sideInfo.mapName}' in index" # at this point we've worked out everything we can about the map # the user is asking for. # now we have to ask for a URL to the geoserver with that map, # and the layerName to use when loading it. # TODO: use a pair of globals (leftfetch and rightfetch) to ensure # early ajaxes are abandoned before starting a new one. $.ajax({ url: '/api/preplayer/' method: 'POST' data: { 'info': mapInfo, 'proj': projectionName } }).done( (data)=> # when the layer prep is complete.. console.log ['layer prepped, answer is ', data] wmsUrl = data.mapUrl wmsLayer = data.layerName # update the download links # TODO: we don't have the url of the map anymore.. # @$('#' + side + 'mapdl').attr 'href', mapUrl # start the map layer loading layer = L.tileLayer.wms wmsUrl, { layers: wmsLayer format: 'image/png' styles: style transparent: true } # add a class to our element when there's tiles loading loadClass = '' + side + 'loading' layer.on 'loading', ()=> @$el.addClass loadClass layer.on 'load', ()=> @$el.removeClass loadClass if side == 'left' @map.removeLayer @leftLayer if @leftLayer @leftLayer = layer if side == 'right' @map.removeLayer @rightLayer if @rightLayer @rightLayer = layer layer.addTo @map # udpate the legend @legend.update {uri: '/static/images/legends/' + style + '.sld.svg'} @resizeThings() # re-establish the splitter ).fail( (jqx, status)=> # when the layer prep has failed.. debug status, 'warning' ) # # update the download links # @$('#' + side + 'mapdl').attr 'href', mapUrl # # we've made a url, start the map layer loading # layer = L.tileLayer.wms @resolvePlaceholders(@rasterApiUrl), { # DATA_URL: mapUrl # layers: 'DEFAULT' # format: 'image/png' # transparent: true # } # # add a class to our element when there's tiles loading # loadClass = '' + side + 'loading' # layer.on 'loading', ()=> @$el.addClass loadClass # layer.on 'load', ()=> @$el.removeClass loadClass # if side == 'left' # @map.removeLayer @leftLayer if @leftLayer # @leftLayer = layer # if side == 'right' # @map.removeLayer @rightLayer if @rightLayer # @rightLayer = layer # layer.addTo @map # @resizeThings() # re-establish the splitter # # if we're local, log the map URL to the console # if window.location.hostname == 'localhost' # console.log 'map URL is: ', mapUrl # # log this as an action in Google Analytics # if ga and typeof(ga) == 'function' # # we have a ga thing which is probaby a google analytics thing. # # "value" is year.percentile, eg. for 90th percentile in 2055, # # we will send 2055.9 as the value. # if sideInfo.year == 'baseline' # val = 1990 # else # val = parseInt(sideInfo.year, 10) # val = val + { 'tenth': 0.1, 'fiftieth': 0.5, 'ninetieth': 0.9 }[sideInfo.gcm] # ga('send', { # 'hitType': 'event', # 'eventCategory': 'mapshow', # 'eventAction': sideInfo.mapName, # 'eventLabel': sideInfo.scenario, # 'eventValue': val # }) # --------------------------------------------------------------- # --------------------------------------------------------------- # UI actions # --------------------------------------------------------------- centreMap: (repeatedlyFor)-> debug 'AppView.centreMap' repeatedlyFor = 500 unless repeatedlyFor recentre = ()=> @map.invalidateSize(false) @resizeThings() setTimeout( recentre, later ) for later in [0..repeatedlyFor] by 25 # --------------------------------------------------------------- toggleForms: ()-> debug 'AppView.toggleForms' @$el.toggleClass 'showforms' @centreMap() # --------------------------------------------------------------- toggleSplitter: ()-> debug 'AppView.toggleSplitter' @$el.toggleClass 'split' if @$el.hasClass 'split' @activateSplitter() else @deactivateSplitter() @centreMap() # --------------------------------------------------------------- toggleSync: ()-> debug 'AppView.toggleSync' if @$('#sync')[0].checked # .. checked now, so was unchecked before @$('.rightmapspp').prop 'disabled', true @copySppToRightSide() else @$('.rightmapspp').prop 'disabled', false # --------------------------------------------------------------- # --------------------------------------------------------------- # form creation # --------------------------------------------------------------- buildForm: (side)-> debug 'AppView.buildForm' $mapspp = @$ "##{side}mapspp" $mapspp.autocomplete { delay: 200 close: => @$el.trigger "#{side}mapupdate" source: (req, response)=> $.ajax { url: '/api/mapsearch/' data: { term: req.term } success: (answer)=> # answer is a list of completions, eg: # { "<NAME>iraffe (Giraffa camelopardalis)": { # "type": "species", # "mapId": "Giraffa camelopardalis", # "path": "..." # }, ... } selectable = [] for nice, info of answer # add each nice name to the completion list selectable.push nice # put the data into our local caches @mapList[info.mapId] = info @nameIndex[nice] = info.mapId console.log answer console.log selectable # finally, give the nice names to the autocomplete response selectable } } # --------------------------------------------------------------- # --------------------------------------------------------------- # splitter handling # --------------------------------------------------------------- startSplitterTracking: ()-> debug 'AppView.startSplitterTracking' @trackSplitter = true @splitLine.addClass 'dragging' @locateSplitter() # --------------------------------------------------------------- locateSplitter: ()-> debug 'AppView.locateSplitter' if @trackSplitter @resizeThings() # decrement remaining track count, unless it's true if @trackSplitter == 0 @trackSplitter = false else if @trackSplitter != true @trackSplitter -= 1 setTimeout @locateSplitter, @trackPeriod # --------------------------------------------------------------- resizeThings: ()-> debug 'AppView.resizeThings' if @leftLayer leftMap = $ @leftLayer.getContainer() if @rightLayer rightMap = $ @rightLayer.getContainer() if @$el.hasClass 'split' # we're still in split mode newLeftWidth = @splitThumb.position().left + (@splitThumb.width() / 2.0) mapBox = @map.getContainer() $mapBox = $ mapBox mapBounds = mapBox.getBoundingClientRect() topLeft = @map.containerPointToLayerPoint [0,0] splitPoint = @map.containerPointToLayerPoint [newLeftWidth, 0] bottomRight = @map.containerPointToLayerPoint [$mapBox.width(), $mapBox.height()] layerTop = topLeft.y layerBottom = bottomRight.y splitX = splitPoint.x - mapBounds.left leftLeft = topLeft.x - mapBounds.left rightRight = bottomRight.x @splitLine.css 'left', newLeftWidth ##### have to use attr to set style, for this to work in frickin IE8. # @leftTag.css 'clip', "rect(0, #{newLeftWidth}px, auto, 0)" @leftTag.attr 'style', "clip: rect(0, #{newLeftWidth}px, auto, 0)" ##### have to use attr to set style, for this to work in IE8. # leftMap.css 'clip', "rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer # rightMap.css 'clip', "rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer leftMap.attr 'style', "clip: rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer rightMap.attr 'style', "clip: rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer else # we're not in split mode (this is probably the last # resizeThings call before exiting split mode), so go # full left side only. ##### have to set style attr for IE8 to work. # @leftTag.css 'clip', 'inherit' # leftMap.css 'clip', 'inherit' if @leftLayer # rightMap.css 'clip', 'rect(0,0,0,0)' if @rightLayer @leftTag.attr 'style', 'clip: inherit' leftMap.attr 'style', 'clip: inherit' if @leftLayer rightMap.attr 'style', 'clip: rect(0,0,0,0)' if @rightLayer # --------------------------------------------------------------- stopSplitterTracking: ()-> debug 'AppView.stopSplitterTracking' @splitLine.removeClass 'dragging' @trackSplitter = 5 # five more resizings, then stop # --------------------------------------------------------------- activateSplitter: ()-> debug 'AppView.activateSplitter' @splitThumb.draggable { containment: $ '#mapwrapper' scroll: false start: @startSplitterTracking drag: @resizeThings stop: @stopSplitterTracking } @resizeThings() # --------------------------------------------------------------- deactivateSplitter: ()-> debug 'AppView.deactivateSplitter' @splitThumb.draggable 'destroy' @resizeThings() # --------------------------------------------------------------- },{ templates: { # ================================================== # templates here # --------------------------------------------------------------- layout: _.template """ <div clas="ui-front"></div> <div class="splitline">&nbsp;</div> <div class="splitthumb"><span>&#x276e; &#x276f;</span></div> <div class="left tag"><%= leftTag %></div> <div class="right tag"><%= rightTag %></div> <div class="left side form"><%= leftForm %></div> <div class="right side form"><%= rightForm %></div> <div class="left loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div class="right loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div id="mapwrapper"><div id="map"></div></div> """ # --------------------------------------------------------------- leftTag: _.template """ <div class="show"> <span class="leftlayername">plain map</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="left syncbox"></label> <input id="leftmapspp" class="left" type="text" name="leftmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- rightTag: _.template """ <div class="show"> <span class="rightlayername">(no distribution)</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="right syncbox"><input id="sync" type="checkbox" value="sync" checked="checked" /> same as left side</label> <input id="rightmapspp" type="text" class="right" name="rightmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- leftForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="left" id="leftmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="leftmaprange" class="left" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="leftmaprange" class="left" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="left" id="leftmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy right-valid-map">copy right map &laquo;</button> <a id="leftmapdl" class="download left-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- rightForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="right" id="rightmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="rightmaprange" class="right" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="rightmaprange" class="right" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="right" id="rightmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy left-valid-map">copy left map &laquo;</button> <a id="rightmapdl" class="download right-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- }} module.exports = AppView
true
# $ = require 'jquery' # _ = require 'lodash' # Backbone = require 'backbone' # L = require 'leaflet' MapLayer = require '../models/maplayer' require '../util/shims' # disable the jshint warning about "did you mean to return a # conditional" which crops up all the time in coffeescript compiled # code. ### jshint -W093 ### # ------------------------------------------------------------------- debug = (itemToLog, itemLevel)-> levels = ['verydebug', 'debug', 'message', 'warning'] itemLevel = 'debug' unless itemLevel # threshold = 'verydebug' threshold = 'debug' # threshold = 'message' thresholdNum = levels.indexOf threshold messageNum = levels.indexOf itemLevel return if thresholdNum > messageNum if itemToLog + '' == itemToLog # it's a string.. console.log "[#{itemLevel}] #{itemToLog}" else console.log itemToLog # ------------------------------------------------------------------- # ------------------------------------------------------------------- AppView = Backbone.View.extend { # --------------------------------------------------------------- # this view's base element tagName: 'div' className: 'splitmap showforms' id: 'splitmap' # --------------------------------------------------------------- # some settings speciesDataUrl: window.mapConfig.speciesDataUrl climateDataUrl: window.mapConfig.climateDataUrl summariesDataUrl: window.mapConfig.summariesDataUrl biodivDataUrl: window.mapConfig.biodivDataUrl rasterApiUrl: window.mapConfig.rasterApiUrl # --------------------------------------------------------------- # tracking the splitter bar trackSplitter: false trackPeriod: 100 # --------------------------------------------------------------- events: 'click .btn-change': 'toggleForms' 'click .btn-compare': 'toggleSplitter' 'click .btn-copy.left-valid-map': 'copyMapLeftToRight' 'click .btn-copy.right-valid-map': 'copyMapRightToLeft' 'leftmapupdate': 'leftSideUpdate' 'rightmapupdate': 'rightSideUpdate' 'change select.left': 'leftSideUpdate' 'change select.right': 'rightSideUpdate' 'change input.left': 'leftSideUpdate' 'change input.right': 'rightSideUpdate' 'change #sync': 'toggleSync' # --------------------------------------------------------------- tick: ()-> # if @map if false # if @leftInfo # debug @map.getPixelOrigin() debug @leftInfo.scenario else debug 'tick' setTimeout(@tick, 1000) # --------------------------------------------------------------- initialize: ()-> debug 'AppView.initialize' # more annoying version of bindAll requires this concat stuff _.bindAll.apply _, [this].concat _.functions(this) @nameIndex = {} # map of nice name -to-> "id name" @mapList = {} # map of "id name" -to-> url, type etc # @sideUpdate('left') # @tick() # --------------------------------------------------------------- render: ()-> debug 'AppView.render' @$el.append AppView.templates.layout { leftTag: AppView.templates.leftTag() rightTag: AppView.templates.rightTag() leftForm: AppView.templates.leftForm() rightForm: AppView.templates.rightForm() } $('#contentwrap').append @$el @map = L.map 'map', { center: [0, 0] zoom: 2 } @map.on 'move', @resizeThings # add a distance scale bar L.control.scale().addTo @map # add a legend @legend = L.control {uri: ''} @legend.onAdd = (map)=> this._div = L.DomUtil.create 'div', 'info' @legend.update = (props)=> this._div.innerHTML = '<object type="image/svg+xml" data="' + (if props then props.uri else '.') + '" />' @legend.addTo @map ## removed MapQuest base layer 2016-07-20 due to licencing changes # L.tileLayer('https://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { # subdomains: '1234' # maxZoom: 18 # attribution: ''' # Map data &copy; <a href="https://openstreetmap.org">OpenStreetMap</a>, # tiles &copy; <a href="https://www.mapquest.com/" target="_blank">MapQuest</a> # ''' # }).addTo @map # ## replaced with HERE maps base layer ## removing HERE maps base layer # L.tileLayer('https://{s}.{base}.maps.cit.api.here.com/maptile/2.1/{type}/{mapID}/{scheme}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', { # attribution: 'Map &copy; 2016 <a href="https://developer.here.com">HERE</a>' # subdomains: '1234' # base: 'aerial' # type: 'maptile' # scheme: 'terrain.day' # app_id: 'l2Rye6zwq3u2cHZpVIPO' # app_code: 'MpXSlNLcLSQIpdU6XHB0TQ' # mapID: 'newest' # maxZoom: 18 # language: 'eng' # format: 'png8' # size: '256' # }).addTo @map ## switching to ESRI baselayer L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri' variant: 'World_Topo_Map' }).addTo @map @leftForm = @$ '.left.form' @buildForm 'left' @rightForm = @$ '.right.form' @buildForm 'right' @leftTag = @$ '.left.tag' @rightTag = @$ '.right.tag' @splitLine = @$ '.splitline' @splitThumb = @$ '.splitthumb' @leftSideUpdate() @rightSideUpdate() # show the splitter by default @toggleSplitter() # --------------------------------------------------------------- resolvePlaceholders: (strWithPlaceholders, replacements)-> ans = strWithPlaceholders ans = ans.replace /\{\{\s*location.protocol\s*\}\}/g, location.protocol ans = ans.replace /\{\{\s*location.host\s*\}\}/g, location.host ans = ans.replace /\{\{\s*location.hostname\s*\}\}/g, location.hostname for key, value of replacements re = new RegExp "\\{\\{\\s*" + key + "\\s*\\}\\}", "g" ans = ans.replace re, value ans # --------------------------------------------------------------- # --------------------------------------------------------------- # map interaction # --------------------------------------------------------------- copyMapLeftToRight: ()-> debug 'AppView.copyMapLeftToRight' return unless @leftInfo @$('#rightmapspp').val @leftInfo.mapName @$('#rightmapyear').val @leftInfo.year @$('input[name=rightmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @leftInfo.scenario) @$('#rightmapgcm').val @leftInfo.gcm @rightSideUpdate() # --------------------------------------------------------------- copyMapRightToLeft: ()-> debug 'AppView.copyMapRightToLeft' return unless @rightInfo @$('#leftmapspp').val @rightInfo.mapName @$('#leftmapyear').val @rightInfo.year @$('input[name=leftmapscenario]').each (index, item)=> $(item).prop 'checked', ($(item).val() == @rightInfo.scenario) @$('#leftmapgcm').val @rightInfo.gcm @leftSideUpdate() # --------------------------------------------------------------- sideUpdate: (side)-> debug 'AppView.sideUpdate (' + side + ')' # # Collect info from the form on that side # newInfo = { mapName: @$('#' + side + 'mapspp').val() degs: @$('#' + side + 'mapdegs').val() range: @$('input[name=' + side + 'maprange]:checked').val() confidence: @$('#' + side + 'mapconfidence').val() } # # enable and disable the form parts that don't # apply, eg. if you're looking at baseline, # disable the future-y things # # set disabled for range-adaptation and model-summary-confidence atBaseline = (newInfo.degs == 'baseline') @$("input[name=#{side}maprange], ##{side}mapconfidence").prop 'disabled', atBaseline # now, add a disabled style to the fieldsets holding disabled items @$(".#{side}.side.form fieldset").removeClass 'disabled' @$( "input[name^=#{side}]:disabled, [id^=#{side}]:disabled" ).closest('fieldset').addClass 'disabled' # # check if what they typed is an available map # if newInfo.mapName of @nameIndex # it's real, so enable the things that need valid maps # e.g. downloads, copy to the other side, etc @$(".#{side}-valid-map").removeClass('disabled').prop 'disabled', false else # it's NOT real, disable those things and bail out right now @$(".#{side}-valid-map").addClass('disabled').prop 'disabled', true return false currInfo = if side == 'left' then @leftInfo else @rightInfo # bail if nothing changed return false if currInfo and _.isEqual newInfo, currInfo # also bail if they're both same species at baseline, even # if future-projection stuff differs, coz that's a special # case of being "the same" if ( currInfo and newInfo.mapName == currInfo.mapName and newInfo.degs == currInfo.degs and newInfo.degs == 'baseline' ) return false # if we got here, something has changed. if side is 'left' # save the new setup @leftInfo = newInfo else @rightInfo = newInfo # apply the changes to the map @addMapLayer side # apply the changes to the tag @addMapTag side # --------------------------------------------------------------- leftSideUpdate: ()-> @sideUpdate 'left' if @$('#sync')[0].checked debug 'Sync checked - syncing right side', 'message' @copySppToRightSide() # --------------------------------------------------------------- rightSideUpdate: ()-> return @sideUpdate 'right' # --------------------------------------------------------------- copySppToRightSide: ()-> @$('#rightmapspp').val @$('#leftmapspp').val() @rightSideUpdate() # --------------------------------------------------------------- addMapTag: (side)-> debug 'AppView.addMapTag' info = @leftInfo if side == 'left' info = @rightInfo if side == 'right' tag = "<b><i>#{info.mapName}</i></b>" dispLookup = { 'no.disp': 'no range adaptation' 'real.disp': 'range adaptation' } if info.degs is 'baseline' tag = "baseline #{tag} distribution" else tag = "<b>#{info.confidence}th</b> percentile projections for #{tag} at <b>+#{info.degs}&deg;C</b> with <b>#{dispLookup[info.range]}</b>" if side == 'left' @leftTag.find('.leftlayername').html tag if side == 'right' @rightTag.find('.rightlayername').html tag # --------------------------------------------------------------- addMapLayer: (side)-> debug 'AppView.addMapLayer' sideInfo = @leftInfo if side == 'left' sideInfo = @rightInfo if side == 'right' futureModelPoint = '' mapUrl = '' zipUrl = '' # TODO: use mapInfo.type instead of these booleans isRichness = sideInfo.mapName.startsWith 'Richness -' isRefugia = sideInfo.mapName.startsWith 'Refugia -' isConcern = sideInfo.mapName.startsWith 'Concern -' if isRichness # ...then they've selected a richness map. style = 'taxa-richness-change' projectionName = "prop.richness_#{sideInfo.degs}_#{sideInfo.range}_#{sideInfo.confidence}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' style = 'taxa-richness' else if isRefugia # ...then they've selected a refugia map. style = 'taxa-refugia' projectionName = "refuge.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else if isConcern # ...then they've selected an area-of-concern map. style = 'taxa-aoc' projectionName = "AreaOfConcern.certainty_#{sideInfo.degs}_#{sideInfo.range}" if sideInfo.degs == 'baseline' projectionName = 'current.richness' else # ...it's a plain old species map they're after. style = 'spp-suitability-purple' # work out the string that gets to the projection point they want projectionName = "TEMP_#{sideInfo.degs}_#{sideInfo.confidence}.#{sideInfo.range}" # if they want baseline, just get the baseline projection projectionName = 'current' if sideInfo.degs == 'baseline' mapInfo = @mapList[@nameIndex[sideInfo.mapName]] if mapInfo # set up for the type we're looking at: start by assuming species and tif url = @speciesDataUrl ext = '.tif' # then override as required if mapInfo.type is 'climate' url = @climateDataUrl ext = '.asc' else if mapInfo.type is 'richness' url = @summariesDataUrl # now set the URL for this type of map mapUrl = [ @resolvePlaceholders url, { path: mapInfo.path } projectionName + ext ].join '/' # update the download links @$('#' + side + 'mapdl').attr 'href', mapUrl else console.log "Can't map that -- no '#{sideInfo.mapName}' in index" # at this point we've worked out everything we can about the map # the user is asking for. # now we have to ask for a URL to the geoserver with that map, # and the layerName to use when loading it. # TODO: use a pair of globals (leftfetch and rightfetch) to ensure # early ajaxes are abandoned before starting a new one. $.ajax({ url: '/api/preplayer/' method: 'POST' data: { 'info': mapInfo, 'proj': projectionName } }).done( (data)=> # when the layer prep is complete.. console.log ['layer prepped, answer is ', data] wmsUrl = data.mapUrl wmsLayer = data.layerName # update the download links # TODO: we don't have the url of the map anymore.. # @$('#' + side + 'mapdl').attr 'href', mapUrl # start the map layer loading layer = L.tileLayer.wms wmsUrl, { layers: wmsLayer format: 'image/png' styles: style transparent: true } # add a class to our element when there's tiles loading loadClass = '' + side + 'loading' layer.on 'loading', ()=> @$el.addClass loadClass layer.on 'load', ()=> @$el.removeClass loadClass if side == 'left' @map.removeLayer @leftLayer if @leftLayer @leftLayer = layer if side == 'right' @map.removeLayer @rightLayer if @rightLayer @rightLayer = layer layer.addTo @map # udpate the legend @legend.update {uri: '/static/images/legends/' + style + '.sld.svg'} @resizeThings() # re-establish the splitter ).fail( (jqx, status)=> # when the layer prep has failed.. debug status, 'warning' ) # # update the download links # @$('#' + side + 'mapdl').attr 'href', mapUrl # # we've made a url, start the map layer loading # layer = L.tileLayer.wms @resolvePlaceholders(@rasterApiUrl), { # DATA_URL: mapUrl # layers: 'DEFAULT' # format: 'image/png' # transparent: true # } # # add a class to our element when there's tiles loading # loadClass = '' + side + 'loading' # layer.on 'loading', ()=> @$el.addClass loadClass # layer.on 'load', ()=> @$el.removeClass loadClass # if side == 'left' # @map.removeLayer @leftLayer if @leftLayer # @leftLayer = layer # if side == 'right' # @map.removeLayer @rightLayer if @rightLayer # @rightLayer = layer # layer.addTo @map # @resizeThings() # re-establish the splitter # # if we're local, log the map URL to the console # if window.location.hostname == 'localhost' # console.log 'map URL is: ', mapUrl # # log this as an action in Google Analytics # if ga and typeof(ga) == 'function' # # we have a ga thing which is probaby a google analytics thing. # # "value" is year.percentile, eg. for 90th percentile in 2055, # # we will send 2055.9 as the value. # if sideInfo.year == 'baseline' # val = 1990 # else # val = parseInt(sideInfo.year, 10) # val = val + { 'tenth': 0.1, 'fiftieth': 0.5, 'ninetieth': 0.9 }[sideInfo.gcm] # ga('send', { # 'hitType': 'event', # 'eventCategory': 'mapshow', # 'eventAction': sideInfo.mapName, # 'eventLabel': sideInfo.scenario, # 'eventValue': val # }) # --------------------------------------------------------------- # --------------------------------------------------------------- # UI actions # --------------------------------------------------------------- centreMap: (repeatedlyFor)-> debug 'AppView.centreMap' repeatedlyFor = 500 unless repeatedlyFor recentre = ()=> @map.invalidateSize(false) @resizeThings() setTimeout( recentre, later ) for later in [0..repeatedlyFor] by 25 # --------------------------------------------------------------- toggleForms: ()-> debug 'AppView.toggleForms' @$el.toggleClass 'showforms' @centreMap() # --------------------------------------------------------------- toggleSplitter: ()-> debug 'AppView.toggleSplitter' @$el.toggleClass 'split' if @$el.hasClass 'split' @activateSplitter() else @deactivateSplitter() @centreMap() # --------------------------------------------------------------- toggleSync: ()-> debug 'AppView.toggleSync' if @$('#sync')[0].checked # .. checked now, so was unchecked before @$('.rightmapspp').prop 'disabled', true @copySppToRightSide() else @$('.rightmapspp').prop 'disabled', false # --------------------------------------------------------------- # --------------------------------------------------------------- # form creation # --------------------------------------------------------------- buildForm: (side)-> debug 'AppView.buildForm' $mapspp = @$ "##{side}mapspp" $mapspp.autocomplete { delay: 200 close: => @$el.trigger "#{side}mapupdate" source: (req, response)=> $.ajax { url: '/api/mapsearch/' data: { term: req.term } success: (answer)=> # answer is a list of completions, eg: # { "PI:NAME:<NAME>END_PIiraffe (Giraffa camelopardalis)": { # "type": "species", # "mapId": "Giraffa camelopardalis", # "path": "..." # }, ... } selectable = [] for nice, info of answer # add each nice name to the completion list selectable.push nice # put the data into our local caches @mapList[info.mapId] = info @nameIndex[nice] = info.mapId console.log answer console.log selectable # finally, give the nice names to the autocomplete response selectable } } # --------------------------------------------------------------- # --------------------------------------------------------------- # splitter handling # --------------------------------------------------------------- startSplitterTracking: ()-> debug 'AppView.startSplitterTracking' @trackSplitter = true @splitLine.addClass 'dragging' @locateSplitter() # --------------------------------------------------------------- locateSplitter: ()-> debug 'AppView.locateSplitter' if @trackSplitter @resizeThings() # decrement remaining track count, unless it's true if @trackSplitter == 0 @trackSplitter = false else if @trackSplitter != true @trackSplitter -= 1 setTimeout @locateSplitter, @trackPeriod # --------------------------------------------------------------- resizeThings: ()-> debug 'AppView.resizeThings' if @leftLayer leftMap = $ @leftLayer.getContainer() if @rightLayer rightMap = $ @rightLayer.getContainer() if @$el.hasClass 'split' # we're still in split mode newLeftWidth = @splitThumb.position().left + (@splitThumb.width() / 2.0) mapBox = @map.getContainer() $mapBox = $ mapBox mapBounds = mapBox.getBoundingClientRect() topLeft = @map.containerPointToLayerPoint [0,0] splitPoint = @map.containerPointToLayerPoint [newLeftWidth, 0] bottomRight = @map.containerPointToLayerPoint [$mapBox.width(), $mapBox.height()] layerTop = topLeft.y layerBottom = bottomRight.y splitX = splitPoint.x - mapBounds.left leftLeft = topLeft.x - mapBounds.left rightRight = bottomRight.x @splitLine.css 'left', newLeftWidth ##### have to use attr to set style, for this to work in frickin IE8. # @leftTag.css 'clip', "rect(0, #{newLeftWidth}px, auto, 0)" @leftTag.attr 'style', "clip: rect(0, #{newLeftWidth}px, auto, 0)" ##### have to use attr to set style, for this to work in IE8. # leftMap.css 'clip', "rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer # rightMap.css 'clip', "rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer leftMap.attr 'style', "clip: rect(#{layerTop}px, #{splitX}px, #{layerBottom}px, #{leftLeft}px)" if @leftLayer rightMap.attr 'style', "clip: rect(#{layerTop}px, #{rightRight}px, #{layerBottom}px, #{splitX}px)" if @rightLayer else # we're not in split mode (this is probably the last # resizeThings call before exiting split mode), so go # full left side only. ##### have to set style attr for IE8 to work. # @leftTag.css 'clip', 'inherit' # leftMap.css 'clip', 'inherit' if @leftLayer # rightMap.css 'clip', 'rect(0,0,0,0)' if @rightLayer @leftTag.attr 'style', 'clip: inherit' leftMap.attr 'style', 'clip: inherit' if @leftLayer rightMap.attr 'style', 'clip: rect(0,0,0,0)' if @rightLayer # --------------------------------------------------------------- stopSplitterTracking: ()-> debug 'AppView.stopSplitterTracking' @splitLine.removeClass 'dragging' @trackSplitter = 5 # five more resizings, then stop # --------------------------------------------------------------- activateSplitter: ()-> debug 'AppView.activateSplitter' @splitThumb.draggable { containment: $ '#mapwrapper' scroll: false start: @startSplitterTracking drag: @resizeThings stop: @stopSplitterTracking } @resizeThings() # --------------------------------------------------------------- deactivateSplitter: ()-> debug 'AppView.deactivateSplitter' @splitThumb.draggable 'destroy' @resizeThings() # --------------------------------------------------------------- },{ templates: { # ================================================== # templates here # --------------------------------------------------------------- layout: _.template """ <div clas="ui-front"></div> <div class="splitline">&nbsp;</div> <div class="splitthumb"><span>&#x276e; &#x276f;</span></div> <div class="left tag"><%= leftTag %></div> <div class="right tag"><%= rightTag %></div> <div class="left side form"><%= leftForm %></div> <div class="right side form"><%= rightForm %></div> <div class="left loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div class="right loader"><img src="/static/images/spinner.loadinfo.net.gif" /></div> <div id="mapwrapper"><div id="map"></div></div> """ # --------------------------------------------------------------- leftTag: _.template """ <div class="show"> <span class="leftlayername">plain map</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="left syncbox"></label> <input id="leftmapspp" class="left" type="text" name="leftmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- rightTag: _.template """ <div class="show"> <span class="rightlayername">(no distribution)</span> <br> <button class="btn-change">settings</button> <button class="btn-compare">show/hide comparison map</button> </div> <div class="edit"> <label class="right syncbox"><input id="sync" type="checkbox" value="sync" checked="checked" /> same as left side</label> <input id="rightmapspp" type="text" class="right" name="rightmapspp" placeholder="&hellip; species or group &hellip;" /> </div> """ # --------------------------------------------------------------- leftForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="left" id="leftmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="leftmaprange" class="left" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="leftmaprange" class="left" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="left" id="leftmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy right-valid-map">copy right map &laquo;</button> <a id="leftmapdl" class="download left-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- rightForm: _.template """ <fieldset> <legend>temperature change</legend> <select class="right" id="rightmapdegs"> <option value="baseline">baseline</option> <option value="1.5">1.5 &deg;C</option> <option value="2">2.0 &deg;C</option> <option value="2.7">2.7 &deg;C</option> <option value="3.2">3.2 &deg;C</option> <option value="4.5">4.5 &deg;C</option> <optgroup label="High sensitivity climate"> <option value="6">6.0 &deg;C</option> </optgroup> </select> </fieldset> <fieldset> <legend>adaptation via range shift</legend> <label><!-- span>none</span --> <input name="rightmaprange" class="right" type="radio" value="no.disp" checked="checked"> species cannot shift ranges</label> <label><!-- span>allow</span --> <input name="rightmaprange" class="right" type="radio" value="real.disp"> allow range adaptation</label> </fieldset> <fieldset> <legend>model summary</legend> <select class="right" id="rightmapconfidence"> <option value="10">10th percentile</option> <!-- option value="33">33rd percentile</option --> <option value="50" selected="selected">50th percentile</option> <!-- option value="66">66th percentile</option --> <option value="90">90th percentile</option> </select> </fieldset> <fieldset class="blank"> <button type="button" class="btn-change">hide settings</button> <button type="button" class="btn-compare">hide/show right map</button> <button type="button" class="btn-copy left-valid-map">copy left map &laquo;</button> <a id="rightmapdl" class="download right-valid-map" href="" disabled="disabled">download just this map<br>(<1Mb GeoTIFF)</a> </fieldset> """ # --------------------------------------------------------------- }} module.exports = AppView
[ { "context": "s.data = [\n new User().one().set(id:1, name:'Putin')\n new User().one().set(id:2, name:'Merkel',", "end": 1693, "score": 0.9991922378540039, "start": 1688, "tag": "NAME", "value": "Putin" }, { "context": "e:'Putin')\n new User().one().set(id:2, name:'Mer...
test/resource-collection.test.coffee
kruschid/angular-resource-manager
0
chai.should() describe 'ResourceCollection', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') it 'should fetch many resources', -> backend.expectGET('/users').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().get() backend.flush() user.data.length.should.be.equal(3) it 'should fetch list of related resources', -> backend.expectGET('/users/1/users-groups').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().one(1).rel('users-groups').get() backend.flush() user.data.length.should.be.equal(3) it 'orphan should remove base resource', -> backend.expectGET('/users-groups').respond -> [200, []] user = new User().one(1).rel('users-groups').orphan().get() backend.flush() it 'should be able to handle non array responses', -> backend.expectGET('/users').respond -> [200, undefined] user = new User().get() backend.flush() it 'should store resources in same object over several requests', -> backend.expectGET('/users').respond -> [200, [1,2,3]] users = new User().get() data = users.data backend.flush() data.length.should.be.equal(3) data.push(4) data.push(5) backend.expectGET('/users').respond -> [200, [1,2,3,4]] users.get() data.length.should.be.equal(5) backend.flush() data.length.should.be.equal(4) it 'find() should return resource matches search criteria', -> users = new User() users.data = [ new User().one().set(id:1, name:'Putin') new User().one().set(id:2, name:'Merkel', title:'Dr.') new User().one().set(id:3, name:'Erdogan', age:62) new User().one().set(id:4, name:'Obama') ] result = users.find(id:3, name: 'Erdogan') result.data.id.should.be.equal(3) result.data.name.should.be.equal('Erdogan') result.data.age.should.be.equal(62) result = users.find(name: 'Putin') result.data.id.should.be.equal(1) result.data.name.should.be.equal('Putin') it 'tget() should only called once per request' it 'rel() should return same objects for same subresources' it 'filter should return array of resources matches search criteria'
190316
chai.should() describe 'ResourceCollection', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') it 'should fetch many resources', -> backend.expectGET('/users').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().get() backend.flush() user.data.length.should.be.equal(3) it 'should fetch list of related resources', -> backend.expectGET('/users/1/users-groups').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().one(1).rel('users-groups').get() backend.flush() user.data.length.should.be.equal(3) it 'orphan should remove base resource', -> backend.expectGET('/users-groups').respond -> [200, []] user = new User().one(1).rel('users-groups').orphan().get() backend.flush() it 'should be able to handle non array responses', -> backend.expectGET('/users').respond -> [200, undefined] user = new User().get() backend.flush() it 'should store resources in same object over several requests', -> backend.expectGET('/users').respond -> [200, [1,2,3]] users = new User().get() data = users.data backend.flush() data.length.should.be.equal(3) data.push(4) data.push(5) backend.expectGET('/users').respond -> [200, [1,2,3,4]] users.get() data.length.should.be.equal(5) backend.flush() data.length.should.be.equal(4) it 'find() should return resource matches search criteria', -> users = new User() users.data = [ new User().one().set(id:1, name:'<NAME>') new User().one().set(id:2, name:'<NAME>', title:'Dr.') new User().one().set(id:3, name:'<NAME>', age:62) new User().one().set(id:4, name:'<NAME>') ] result = users.find(id:3, name: '<NAME>') result.data.id.should.be.equal(3) result.data.name.should.be.equal('<NAME>') result.data.age.should.be.equal(62) result = users.find(name: '<NAME>') result.data.id.should.be.equal(1) result.data.name.should.be.equal('<NAME>') it 'tget() should only called once per request' it 'rel() should return same objects for same subresources' it 'filter should return array of resources matches search criteria'
true
chai.should() describe 'ResourceCollection', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') it 'should fetch many resources', -> backend.expectGET('/users').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().get() backend.flush() user.data.length.should.be.equal(3) it 'should fetch list of related resources', -> backend.expectGET('/users/1/users-groups').respond -> [200, [{id:1},{id:2},{id:3}]] user = new User().one(1).rel('users-groups').get() backend.flush() user.data.length.should.be.equal(3) it 'orphan should remove base resource', -> backend.expectGET('/users-groups').respond -> [200, []] user = new User().one(1).rel('users-groups').orphan().get() backend.flush() it 'should be able to handle non array responses', -> backend.expectGET('/users').respond -> [200, undefined] user = new User().get() backend.flush() it 'should store resources in same object over several requests', -> backend.expectGET('/users').respond -> [200, [1,2,3]] users = new User().get() data = users.data backend.flush() data.length.should.be.equal(3) data.push(4) data.push(5) backend.expectGET('/users').respond -> [200, [1,2,3,4]] users.get() data.length.should.be.equal(5) backend.flush() data.length.should.be.equal(4) it 'find() should return resource matches search criteria', -> users = new User() users.data = [ new User().one().set(id:1, name:'PI:NAME:<NAME>END_PI') new User().one().set(id:2, name:'PI:NAME:<NAME>END_PI', title:'Dr.') new User().one().set(id:3, name:'PI:NAME:<NAME>END_PI', age:62) new User().one().set(id:4, name:'PI:NAME:<NAME>END_PI') ] result = users.find(id:3, name: 'PI:NAME:<NAME>END_PI') result.data.id.should.be.equal(3) result.data.name.should.be.equal('PI:NAME:<NAME>END_PI') result.data.age.should.be.equal(62) result = users.find(name: 'PI:NAME:<NAME>END_PI') result.data.id.should.be.equal(1) result.data.name.should.be.equal('PI:NAME:<NAME>END_PI') it 'tget() should only called once per request' it 'rel() should return same objects for same subresources' it 'filter should return array of resources matches search criteria'
[ { "context": "# Copyright Vladimir Andreev\n\n# Exported objects\n\nexports.Service = require('.", "end": 28, "score": 0.9998620748519897, "start": 12, "tag": "NAME", "value": "Vladimir Andreev" } ]
src/index.coffee
tucan/smsaero
0
# Copyright Vladimir Andreev # Exported objects exports.Service = require('./service') exports.Client = require('./client')
75113
# Copyright <NAME> # Exported objects exports.Service = require('./service') exports.Client = require('./client')
true
# Copyright PI:NAME:<NAME>END_PI # Exported objects exports.Service = require('./service') exports.Client = require('./client')
[ { "context": "r\n img_server = null\n\n\n# 生成加密密码\n# @param password 密码\n# @param token check_qq_verify 参数1 !UGX\n# @par", "end": 2308, "score": 0.9980831146240234, "start": 2306, "tag": "PASSWORD", "value": "密码" }, { "context": "sword = (password , token , bits) ->\n\n password ...
src/qqauth.coffee
lsc20051426/qqbot
2
https = require "https" http = require 'http' crypto = require 'crypto' querystring = require 'querystring' Url = require('url') all_cookies = [] int = (v) -> parseInt v Path = require 'path' Log = require 'log' log = new Log('debug'); md5 = (str) -> md5sum = crypto.createHash 'md5' md5sum.update(str.toString()).digest('hex') exports.cookies = (cookies)-> all_cookies = cookies if cookies all_cookies # 是否需要 验证码 # @param qq # @param callback -> [是否需要验证码 , token , bits ] exports.check_qq_verify = (qq, callback) -> # TODO: random -> r options = host: 'ssl.ptlogin2.qq.com' path: "/check?uin=#{qq}&appid=1003903&js_ver=10062&js_type=0&r=0.6569391019121522" headers: 'Cookie' : "chkuin=#{qq}" body = ''; https .get options , (resp) -> all_cookies = resp.headers['set-cookie'] resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> # log body ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) # log ret callback( ret ) .on "error", (e) -> log.error e # 获取验证码 # 记得call finish_verify_code exports.get_verify_code = (qq , host, port, callback) -> url = "http://captcha.qq.com/getimage?aid=1003903&r=0.2509327069195215&uin=#{qq}" body = '' http.get url , (resp) -> # log "verify code: #{resp.statusCode}" # log resp.headers all_cookies = all_cookies.concat resp.headers['set-cookie'] resp.setEncoding 'binary' resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> create_img_server(host,port,body,resp.headers) callback() .on "error", (e) -> log.error e callback(e) exports.finish_verify_code = -> stop_img_server() # 验证码图片服务 img_server = null create_img_server = (host, port, body ,origin_headers) -> return if img_server fs = require 'fs' file_path = Path.join __dirname, "..", "tmp", "verifycode.jpg" fs.writeFileSync file_path , body , 'binary' img_server = http.createServer (req, res) -> res.writeHead 200 , origin_headers res.end body, 'binary' img_server.listen port stop_img_server = -> img_server.close() if img_server img_server = null # 生成加密密码 # @param password 密码 # @param token check_qq_verify 参数1 !UGX # @param bits check_qq_verify 参数2 \x00\x11\x00\x11 exports.encode_password = (password , token , bits) -> password = md5(password) bits = bits.replace(/\\x/g,'') hex2ascii = (hexstr) -> hexstr.match(/\w{2}/g) .map (byte_str) -> String.fromCharCode parseInt(byte_str,16) .join('') ret = md5( hex2ascii(password) + hex2ascii(bits) ).toUpperCase() + token.toUpperCase() ret = md5( ret ).toUpperCase() return ret # 登录 帐号密码验证码 校验 exports.login_step1 = (qq, encode_password, verifycode , callback) -> path = "/login?u=#{qq}&p=#{encode_password}&verifycode=#{verifycode}&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=3-15-72115&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10062&login_sig=qBpuWCs9dlR9awKKmzdRhV8TZ8MfupdXF6zyHmnGUaEzun0bobwOhMh6m7FQjvWA" options = host: 'ssl.ptlogin2.qq.com' path: path headers: 'Cookie' : all_cookies body = ''; https .get options , (resp) -> # log "response: #{resp.statusCode}" # log all_cookies all_cookies = all_cookies.concat resp.headers['set-cookie'] # log all_cookies resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) callback( ret ) .on "error", (e) -> log.error e # 验证成功后继续获取cookie exports.login_step2 = (url, callback) -> url = Url.parse(url) options = host: url.host path: url.path headers: 'Cookie' : all_cookies body = ''; http .get options , (resp) -> log.debug "response: #{resp.statusCode}" all_cookies = all_cookies.concat resp.headers['set-cookie'] callback( true ) # 只需要获取cookie .on "error", (e) -> log.error e # "http://d.web2.qq.com/channel/login2" # client_id : int # callback( ret , client_id , ptwebqq) exports.login_token = (client_id=null,psessionid=null,callback) -> # client 是长度8的随机数字 client_id ||= parseInt(Math.random()* 89999999) + 10000000 client_id = parseInt client_id ptwebqq = all_cookies.filter( (item)->item.match /ptwebqq/ ) .pop() .replace /ptwebqq\=(.*?);.*/ , '$1' # log all_cookies r = status: "online", ptwebqq: ptwebqq, passwd_sig: "", clientid: "#{client_id}", psessionid: psessionid r = JSON.stringify(r) data = querystring.stringify { clientid: client_id, # psessionid: 'null', psessionid: psessionid, r: r } # log data body = '' options = host: 'd.web2.qq.com', path: '/channel/login2' method: 'POST', headers: 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:27.0) Gecko/20100101 Firefox/27.0', 'Referer': 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=3', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Length': Buffer.byteLength(data), 'Cookie' : all_cookies req = http.request options, (resp) -> log.debug "login token response: #{resp.statusCode}" resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = JSON.parse(body) callback( ret , client_id ,ptwebqq) req.write(data) req.end() ### 全局登录函数,如果有验证码会建立一个 http-server ,同时写入 tmp/*.jpg (osx + open. 操作) http-server 的端口和显示地址可配置 @param options {account,password,port,host} @callback( cookies , auth_options ) if login success ### exports.login = (options, callback) -> [auth,opt] = [exports,options] [qq,pass] = [opt.account,opt.password] log.info '登录 step0 验证码检测' auth.check_qq_verify qq , (result) -> # log.debug "验证帐号:", result [need_verify,verify_code,bits] = result if int need_verify log.info "登录 step0.5 获取验证码" auth.get_verify_code qq, opt.host, opt.port, (error) -> # open image folder require('child_process').exec 'open tmp' if process.platform is 'darwin' log.notice "打开该地址->", "http://#{opt.host}:#{opt.port}" auth.prompt "输入验证码:" , (code) -> auth.finish_verify_code() verify_code = code log.notice '验证码:' , verify_code pass_encrypted = auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) else log.info "- 无需验证码" pass_encrypted= auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) # login 函数的步骤2 # TODO:各种回调的 error 处理 login_next = (account , pass_encrypted , verify_code , callback)-> auth = exports log.info "登录 step1 密码校验" auth.login_step1 account, pass_encrypted , verify_code , (ret)-> if not ret[2].match /^http/ log.error "登录 step1 failed", ret return log.info "登录 step2 cookie获取" auth.login_step2 ret[2] , (ret) -> log.info "登录 step3 token 获取" auth.login_token null,null,(ret,client_id,ptwebqq) -> if ret.retcode == 0 log.info '登录成功',account auth_options = psessionid: ret.result.psessionid clientid : client_id ptwebqq : ptwebqq uin : ret.result.uin vfwebqq : ret.result.vfwebqq callback( all_cookies, auth_options) else log.info "登录失败" log.error ret # prompt user to input something # and also listen for process event data # @params title : prompt title # @callback(content) exports.prompt = (title, callback) -> process.stdin.resume() process.stdout.write(title) process.on "data" , (data) -> if data callback data process.stdin.pause() process.stdin.on "data", (data) -> data = data.toString().trim() # 过滤无效内容 if data callback data process.stdin.pause() # control + d to end process.stdin.on 'end', -> process.stdout.write('end') callback()
168124
https = require "https" http = require 'http' crypto = require 'crypto' querystring = require 'querystring' Url = require('url') all_cookies = [] int = (v) -> parseInt v Path = require 'path' Log = require 'log' log = new Log('debug'); md5 = (str) -> md5sum = crypto.createHash 'md5' md5sum.update(str.toString()).digest('hex') exports.cookies = (cookies)-> all_cookies = cookies if cookies all_cookies # 是否需要 验证码 # @param qq # @param callback -> [是否需要验证码 , token , bits ] exports.check_qq_verify = (qq, callback) -> # TODO: random -> r options = host: 'ssl.ptlogin2.qq.com' path: "/check?uin=#{qq}&appid=1003903&js_ver=10062&js_type=0&r=0.6569391019121522" headers: 'Cookie' : "chkuin=#{qq}" body = ''; https .get options , (resp) -> all_cookies = resp.headers['set-cookie'] resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> # log body ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) # log ret callback( ret ) .on "error", (e) -> log.error e # 获取验证码 # 记得call finish_verify_code exports.get_verify_code = (qq , host, port, callback) -> url = "http://captcha.qq.com/getimage?aid=1003903&r=0.2509327069195215&uin=#{qq}" body = '' http.get url , (resp) -> # log "verify code: #{resp.statusCode}" # log resp.headers all_cookies = all_cookies.concat resp.headers['set-cookie'] resp.setEncoding 'binary' resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> create_img_server(host,port,body,resp.headers) callback() .on "error", (e) -> log.error e callback(e) exports.finish_verify_code = -> stop_img_server() # 验证码图片服务 img_server = null create_img_server = (host, port, body ,origin_headers) -> return if img_server fs = require 'fs' file_path = Path.join __dirname, "..", "tmp", "verifycode.jpg" fs.writeFileSync file_path , body , 'binary' img_server = http.createServer (req, res) -> res.writeHead 200 , origin_headers res.end body, 'binary' img_server.listen port stop_img_server = -> img_server.close() if img_server img_server = null # 生成加密密码 # @param password <PASSWORD> # @param token check_qq_verify 参数1 !UGX # @param bits check_qq_verify 参数2 \x00\x11\x00\x11 exports.encode_password = (password , token , bits) -> password = <PASSWORD>(<PASSWORD>) bits = bits.replace(/\\x/g,'') hex2ascii = (hexstr) -> hexstr.match(/\w{2}/g) .map (byte_str) -> String.fromCharCode parseInt(byte_str,16) .join('') ret = md5( hex2ascii(password) + hex2ascii(bits) ).toUpperCase() + token.toUpperCase() ret = md5( ret ).toUpperCase() return ret # 登录 帐号密码验证码 校验 exports.login_step1 = (qq, encode_password, verifycode , callback) -> path = "/login?u=#{qq}&p=#{encode_password}&verifycode=#{verifycode}&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=3-15-72115&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10062&login_sig=qBpuWCs9dlR9awKKmzdRhV8TZ8MfupdXF6zyHmnGUaEzun0bobwOhMh6m7FQjvWA" options = host: 'ssl.ptlogin2.qq.com' path: path headers: 'Cookie' : all_cookies body = ''; https .get options , (resp) -> # log "response: #{resp.statusCode}" # log all_cookies all_cookies = all_cookies.concat resp.headers['set-cookie'] # log all_cookies resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) callback( ret ) .on "error", (e) -> log.error e # 验证成功后继续获取cookie exports.login_step2 = (url, callback) -> url = Url.parse(url) options = host: url.host path: url.path headers: 'Cookie' : all_cookies body = ''; http .get options , (resp) -> log.debug "response: #{resp.statusCode}" all_cookies = all_cookies.concat resp.headers['set-cookie'] callback( true ) # 只需要获取cookie .on "error", (e) -> log.error e # "http://d.web2.qq.com/channel/login2" # client_id : int # callback( ret , client_id , ptwebqq) exports.login_token = (client_id=null,psessionid=null,callback) -> # client 是长度8的随机数字 client_id ||= parseInt(Math.random()* 89999999) + 10000000 client_id = parseInt client_id ptwebqq = all_cookies.filter( (item)->item.match /ptwebqq/ ) .pop() .replace /ptwebqq\=(.*?);.*/ , '$1' # log all_cookies r = status: "online", ptwebqq: ptwebqq, passwd_sig: "", clientid: "#{client_id}", psessionid: psessionid r = JSON.stringify(r) data = querystring.stringify { clientid: client_id, # psessionid: 'null', psessionid: psessionid, r: r } # log data body = '' options = host: 'd.web2.qq.com', path: '/channel/login2' method: 'POST', headers: 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:27.0) Gecko/20100101 Firefox/27.0', 'Referer': 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=3', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Length': Buffer.byteLength(data), 'Cookie' : all_cookies req = http.request options, (resp) -> log.debug "login token response: #{resp.statusCode}" resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = JSON.parse(body) callback( ret , client_id ,ptwebqq) req.write(data) req.end() ### 全局登录函数,如果有验证码会建立一个 http-server ,同时写入 tmp/*.jpg (osx + open. 操作) http-server 的端口和显示地址可配置 @param options {account,password,port,host} @callback( cookies , auth_options ) if login success ### exports.login = (options, callback) -> [auth,opt] = [exports,options] [qq,pass] = [opt.account,opt.password] log.info '登录 step0 验证码检测' auth.check_qq_verify qq , (result) -> # log.debug "验证帐号:", result [need_verify,verify_code,bits] = result if int need_verify log.info "登录 step0.5 获取验证码" auth.get_verify_code qq, opt.host, opt.port, (error) -> # open image folder require('child_process').exec 'open tmp' if process.platform is 'darwin' log.notice "打开该地址->", "http://#{opt.host}:#{opt.port}" auth.prompt "输入验证码:" , (code) -> auth.finish_verify_code() verify_code = code log.notice '验证码:' , verify_code pass_encrypted = auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) else log.info "- 无需验证码" pass_encrypted= auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) # login 函数的步骤2 # TODO:各种回调的 error 处理 login_next = (account , pass_encrypted , verify_code , callback)-> auth = exports log.info "登录 step1 密码校验" auth.login_step1 account, pass_encrypted , verify_code , (ret)-> if not ret[2].match /^http/ log.error "登录 step1 failed", ret return log.info "登录 step2 cookie获取" auth.login_step2 ret[2] , (ret) -> log.info "登录 step3 token 获取" auth.login_token null,null,(ret,client_id,ptwebqq) -> if ret.retcode == 0 log.info '登录成功',account auth_options = psessionid: ret.result.psessionid clientid : client_id ptwebqq : ptwebqq uin : ret.result.uin vfwebqq : ret.result.vfwebqq callback( all_cookies, auth_options) else log.info "登录失败" log.error ret # prompt user to input something # and also listen for process event data # @params title : prompt title # @callback(content) exports.prompt = (title, callback) -> process.stdin.resume() process.stdout.write(title) process.on "data" , (data) -> if data callback data process.stdin.pause() process.stdin.on "data", (data) -> data = data.toString().trim() # 过滤无效内容 if data callback data process.stdin.pause() # control + d to end process.stdin.on 'end', -> process.stdout.write('end') callback()
true
https = require "https" http = require 'http' crypto = require 'crypto' querystring = require 'querystring' Url = require('url') all_cookies = [] int = (v) -> parseInt v Path = require 'path' Log = require 'log' log = new Log('debug'); md5 = (str) -> md5sum = crypto.createHash 'md5' md5sum.update(str.toString()).digest('hex') exports.cookies = (cookies)-> all_cookies = cookies if cookies all_cookies # 是否需要 验证码 # @param qq # @param callback -> [是否需要验证码 , token , bits ] exports.check_qq_verify = (qq, callback) -> # TODO: random -> r options = host: 'ssl.ptlogin2.qq.com' path: "/check?uin=#{qq}&appid=1003903&js_ver=10062&js_type=0&r=0.6569391019121522" headers: 'Cookie' : "chkuin=#{qq}" body = ''; https .get options , (resp) -> all_cookies = resp.headers['set-cookie'] resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> # log body ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) # log ret callback( ret ) .on "error", (e) -> log.error e # 获取验证码 # 记得call finish_verify_code exports.get_verify_code = (qq , host, port, callback) -> url = "http://captcha.qq.com/getimage?aid=1003903&r=0.2509327069195215&uin=#{qq}" body = '' http.get url , (resp) -> # log "verify code: #{resp.statusCode}" # log resp.headers all_cookies = all_cookies.concat resp.headers['set-cookie'] resp.setEncoding 'binary' resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> create_img_server(host,port,body,resp.headers) callback() .on "error", (e) -> log.error e callback(e) exports.finish_verify_code = -> stop_img_server() # 验证码图片服务 img_server = null create_img_server = (host, port, body ,origin_headers) -> return if img_server fs = require 'fs' file_path = Path.join __dirname, "..", "tmp", "verifycode.jpg" fs.writeFileSync file_path , body , 'binary' img_server = http.createServer (req, res) -> res.writeHead 200 , origin_headers res.end body, 'binary' img_server.listen port stop_img_server = -> img_server.close() if img_server img_server = null # 生成加密密码 # @param password PI:PASSWORD:<PASSWORD>END_PI # @param token check_qq_verify 参数1 !UGX # @param bits check_qq_verify 参数2 \x00\x11\x00\x11 exports.encode_password = (password , token , bits) -> password = PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI) bits = bits.replace(/\\x/g,'') hex2ascii = (hexstr) -> hexstr.match(/\w{2}/g) .map (byte_str) -> String.fromCharCode parseInt(byte_str,16) .join('') ret = md5( hex2ascii(password) + hex2ascii(bits) ).toUpperCase() + token.toUpperCase() ret = md5( ret ).toUpperCase() return ret # 登录 帐号密码验证码 校验 exports.login_step1 = (qq, encode_password, verifycode , callback) -> path = "/login?u=#{qq}&p=#{encode_password}&verifycode=#{verifycode}&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=3-15-72115&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10062&login_sig=qBpuWCs9dlR9awKKmzdRhV8TZ8MfupdXF6zyHmnGUaEzun0bobwOhMh6m7FQjvWA" options = host: 'ssl.ptlogin2.qq.com' path: path headers: 'Cookie' : all_cookies body = ''; https .get options , (resp) -> # log "response: #{resp.statusCode}" # log all_cookies all_cookies = all_cookies.concat resp.headers['set-cookie'] # log all_cookies resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = body.match(/\'(.*?)\'/g).map (i)-> last = i.length - 2 i.substr(1 ,last) callback( ret ) .on "error", (e) -> log.error e # 验证成功后继续获取cookie exports.login_step2 = (url, callback) -> url = Url.parse(url) options = host: url.host path: url.path headers: 'Cookie' : all_cookies body = ''; http .get options , (resp) -> log.debug "response: #{resp.statusCode}" all_cookies = all_cookies.concat resp.headers['set-cookie'] callback( true ) # 只需要获取cookie .on "error", (e) -> log.error e # "http://d.web2.qq.com/channel/login2" # client_id : int # callback( ret , client_id , ptwebqq) exports.login_token = (client_id=null,psessionid=null,callback) -> # client 是长度8的随机数字 client_id ||= parseInt(Math.random()* 89999999) + 10000000 client_id = parseInt client_id ptwebqq = all_cookies.filter( (item)->item.match /ptwebqq/ ) .pop() .replace /ptwebqq\=(.*?);.*/ , '$1' # log all_cookies r = status: "online", ptwebqq: ptwebqq, passwd_sig: "", clientid: "#{client_id}", psessionid: psessionid r = JSON.stringify(r) data = querystring.stringify { clientid: client_id, # psessionid: 'null', psessionid: psessionid, r: r } # log data body = '' options = host: 'd.web2.qq.com', path: '/channel/login2' method: 'POST', headers: 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:27.0) Gecko/20100101 Firefox/27.0', 'Referer': 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=3', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Length': Buffer.byteLength(data), 'Cookie' : all_cookies req = http.request options, (resp) -> log.debug "login token response: #{resp.statusCode}" resp.on 'data', (chunk) -> body += chunk resp.on 'end', -> ret = JSON.parse(body) callback( ret , client_id ,ptwebqq) req.write(data) req.end() ### 全局登录函数,如果有验证码会建立一个 http-server ,同时写入 tmp/*.jpg (osx + open. 操作) http-server 的端口和显示地址可配置 @param options {account,password,port,host} @callback( cookies , auth_options ) if login success ### exports.login = (options, callback) -> [auth,opt] = [exports,options] [qq,pass] = [opt.account,opt.password] log.info '登录 step0 验证码检测' auth.check_qq_verify qq , (result) -> # log.debug "验证帐号:", result [need_verify,verify_code,bits] = result if int need_verify log.info "登录 step0.5 获取验证码" auth.get_verify_code qq, opt.host, opt.port, (error) -> # open image folder require('child_process').exec 'open tmp' if process.platform is 'darwin' log.notice "打开该地址->", "http://#{opt.host}:#{opt.port}" auth.prompt "输入验证码:" , (code) -> auth.finish_verify_code() verify_code = code log.notice '验证码:' , verify_code pass_encrypted = auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) else log.info "- 无需验证码" pass_encrypted= auth.encode_password(pass, verify_code , bits) login_next( qq , pass_encrypted , verify_code , callback) # login 函数的步骤2 # TODO:各种回调的 error 处理 login_next = (account , pass_encrypted , verify_code , callback)-> auth = exports log.info "登录 step1 密码校验" auth.login_step1 account, pass_encrypted , verify_code , (ret)-> if not ret[2].match /^http/ log.error "登录 step1 failed", ret return log.info "登录 step2 cookie获取" auth.login_step2 ret[2] , (ret) -> log.info "登录 step3 token 获取" auth.login_token null,null,(ret,client_id,ptwebqq) -> if ret.retcode == 0 log.info '登录成功',account auth_options = psessionid: ret.result.psessionid clientid : client_id ptwebqq : ptwebqq uin : ret.result.uin vfwebqq : ret.result.vfwebqq callback( all_cookies, auth_options) else log.info "登录失败" log.error ret # prompt user to input something # and also listen for process event data # @params title : prompt title # @callback(content) exports.prompt = (title, callback) -> process.stdin.resume() process.stdout.write(title) process.on "data" , (data) -> if data callback data process.stdin.pause() process.stdin.on "data", (data) -> data = data.toString().trim() # 过滤无效内容 if data callback data process.stdin.pause() # control + d to end process.stdin.on 'end', -> process.stdout.write('end') callback()
[ { "context": "erms of the MIT license.\nCopyright 2012 - 2018 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nfs = requir", "end": 109, "score": 0.9998974800109863, "start": 94, "tag": "NAME", "value": "Markus Kohlhase" }, { "context": "cense.\nCopyright 2012 - 2018 (c) ...
src/cli.coffee
toastal/sloc-1
0
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2018 (c) Markus Kohlhase <mail@markus-kohlhase.de> ### fs = require 'fs' path = require 'path' async = require 'async' programm = require 'commander' readdirp = require 'readdirp' sloc = require './sloc' helpers = require './helpers' pkg = require '../package.json' fmts = require './formatters' list = (val) -> val.split ',' keyvalue = (val) -> val.split '=' object = (val) -> result = {} for split in list(val).map(keyvalue) [custom, original] = split result[custom] = original result exts = ("*.#{k}" for k in sloc.extensions) collect = (val, memo) -> memo.push val memo colorRegex = /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g parseFile = (f, cb=->) -> res = { path: f, stats: {}, badFile: no } fs.readFile f, "utf8", (err, code) -> if err res.badFile = yes return cb err, res ext = path.extname(f)[1...] res.stats = sloc code, options.alias[ext] or ext cb null, res print = (result, opts, fmtOpts) -> f = programm.format or 'simple' unless (fmt = fmts[f])? return console.error "Error: format #{f} is not supported" out = fmt result, opts, fmtOpts out = out.replace colorRegex, '' if programm.stripColors console.log out if typeof out is "string" filterFiles = (files) -> res = if programm.exclude exclude = new RegExp programm.exclude files.filter (x) -> not exclude.test x.path else files (r.path for r in res) options = {} fmtOpts = [] programm .version pkg.version .usage '[option] <file> | <directory>' .option '-e, --exclude <regex>', 'regular expression to exclude files and folders' .option '-f, --format <format>', 'format output:' + (" #{k}" for k of fmts).join ',' .option '--format-option [value]', 'add formatter option', collect, fmtOpts .option '--strip-colors', 'remove all color characters' .option '-k, --keys <keys>', 'report only numbers of the given keys', list .option '-d, --details', 'report stats of each analyzed file' .option '-a, --alias <custom ext>=<standard ext>', 'alias custom ext to act like standard ext', object programm.parse process.argv options.keys = programm.keys options.details = programm.details options.alias = programm.alias for k of options.alias exts.push "*.#{k}" return programm.help() if programm.args.length < 1 groupByExt = (data) -> map = {} for f in data.files ext = (path.extname f.path)[1...] m = map[ext] ?= { files: [] } m.files.push f for ext, d of map d.summary = helpers.summarize d.files.map (x) -> x.stats map readSingleFile = (f, done) -> parseFile f, (err, res) -> done err, [res] readDir = (dir, done) -> processFile = (f, next) -> parseFile (path.join dir, f), next readdirp { root: dir, fileFilter: exts }, (err, res) -> return done(err) if err async.mapLimit (filterFiles res.files), 1000, processFile, done readSource = (p, done) -> fs.lstat p, (err, stats) -> if err console.error "Error: invalid path argument #{p}" return done(err) if stats.isDirectory() then return readDir p, done else if stats.isFile() then return readSingleFile p, done async.map programm.args, readSource, (err, parsed) -> return console.error "Error: #{err}" if err result = files: [] parsed.forEach (files) -> files.forEach (f) -> if f.badFile then result.brokenFiles++ result.files.push f result.summary = helpers.summarize result.files.map (x) -> x.stats result.byExt = groupByExt result print result, options, fmtOpts
112114
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2018 (c) <NAME> <<EMAIL>> ### fs = require 'fs' path = require 'path' async = require 'async' programm = require 'commander' readdirp = require 'readdirp' sloc = require './sloc' helpers = require './helpers' pkg = require '../package.json' fmts = require './formatters' list = (val) -> val.split ',' keyvalue = (val) -> val.split '=' object = (val) -> result = {} for split in list(val).map(keyvalue) [custom, original] = split result[custom] = original result exts = ("*.#{k}" for k in sloc.extensions) collect = (val, memo) -> memo.push val memo colorRegex = /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g parseFile = (f, cb=->) -> res = { path: f, stats: {}, badFile: no } fs.readFile f, "utf8", (err, code) -> if err res.badFile = yes return cb err, res ext = path.extname(f)[1...] res.stats = sloc code, options.alias[ext] or ext cb null, res print = (result, opts, fmtOpts) -> f = programm.format or 'simple' unless (fmt = fmts[f])? return console.error "Error: format #{f} is not supported" out = fmt result, opts, fmtOpts out = out.replace colorRegex, '' if programm.stripColors console.log out if typeof out is "string" filterFiles = (files) -> res = if programm.exclude exclude = new RegExp programm.exclude files.filter (x) -> not exclude.test x.path else files (r.path for r in res) options = {} fmtOpts = [] programm .version pkg.version .usage '[option] <file> | <directory>' .option '-e, --exclude <regex>', 'regular expression to exclude files and folders' .option '-f, --format <format>', 'format output:' + (" #{k}" for k of fmts).join ',' .option '--format-option [value]', 'add formatter option', collect, fmtOpts .option '--strip-colors', 'remove all color characters' .option '-k, --keys <keys>', 'report only numbers of the given keys', list .option '-d, --details', 'report stats of each analyzed file' .option '-a, --alias <custom ext>=<standard ext>', 'alias custom ext to act like standard ext', object programm.parse process.argv options.keys = programm.keys options.details = programm.details options.alias = programm.alias for k of options.alias exts.push "*.#{k}" return programm.help() if programm.args.length < 1 groupByExt = (data) -> map = {} for f in data.files ext = (path.extname f.path)[1...] m = map[ext] ?= { files: [] } m.files.push f for ext, d of map d.summary = helpers.summarize d.files.map (x) -> x.stats map readSingleFile = (f, done) -> parseFile f, (err, res) -> done err, [res] readDir = (dir, done) -> processFile = (f, next) -> parseFile (path.join dir, f), next readdirp { root: dir, fileFilter: exts }, (err, res) -> return done(err) if err async.mapLimit (filterFiles res.files), 1000, processFile, done readSource = (p, done) -> fs.lstat p, (err, stats) -> if err console.error "Error: invalid path argument #{p}" return done(err) if stats.isDirectory() then return readDir p, done else if stats.isFile() then return readSingleFile p, done async.map programm.args, readSource, (err, parsed) -> return console.error "Error: #{err}" if err result = files: [] parsed.forEach (files) -> files.forEach (f) -> if f.badFile then result.brokenFiles++ result.files.push f result.summary = helpers.summarize result.files.map (x) -> x.stats result.byExt = groupByExt result print result, options, fmtOpts
true
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2018 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### fs = require 'fs' path = require 'path' async = require 'async' programm = require 'commander' readdirp = require 'readdirp' sloc = require './sloc' helpers = require './helpers' pkg = require '../package.json' fmts = require './formatters' list = (val) -> val.split ',' keyvalue = (val) -> val.split '=' object = (val) -> result = {} for split in list(val).map(keyvalue) [custom, original] = split result[custom] = original result exts = ("*.#{k}" for k in sloc.extensions) collect = (val, memo) -> memo.push val memo colorRegex = /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g parseFile = (f, cb=->) -> res = { path: f, stats: {}, badFile: no } fs.readFile f, "utf8", (err, code) -> if err res.badFile = yes return cb err, res ext = path.extname(f)[1...] res.stats = sloc code, options.alias[ext] or ext cb null, res print = (result, opts, fmtOpts) -> f = programm.format or 'simple' unless (fmt = fmts[f])? return console.error "Error: format #{f} is not supported" out = fmt result, opts, fmtOpts out = out.replace colorRegex, '' if programm.stripColors console.log out if typeof out is "string" filterFiles = (files) -> res = if programm.exclude exclude = new RegExp programm.exclude files.filter (x) -> not exclude.test x.path else files (r.path for r in res) options = {} fmtOpts = [] programm .version pkg.version .usage '[option] <file> | <directory>' .option '-e, --exclude <regex>', 'regular expression to exclude files and folders' .option '-f, --format <format>', 'format output:' + (" #{k}" for k of fmts).join ',' .option '--format-option [value]', 'add formatter option', collect, fmtOpts .option '--strip-colors', 'remove all color characters' .option '-k, --keys <keys>', 'report only numbers of the given keys', list .option '-d, --details', 'report stats of each analyzed file' .option '-a, --alias <custom ext>=<standard ext>', 'alias custom ext to act like standard ext', object programm.parse process.argv options.keys = programm.keys options.details = programm.details options.alias = programm.alias for k of options.alias exts.push "*.#{k}" return programm.help() if programm.args.length < 1 groupByExt = (data) -> map = {} for f in data.files ext = (path.extname f.path)[1...] m = map[ext] ?= { files: [] } m.files.push f for ext, d of map d.summary = helpers.summarize d.files.map (x) -> x.stats map readSingleFile = (f, done) -> parseFile f, (err, res) -> done err, [res] readDir = (dir, done) -> processFile = (f, next) -> parseFile (path.join dir, f), next readdirp { root: dir, fileFilter: exts }, (err, res) -> return done(err) if err async.mapLimit (filterFiles res.files), 1000, processFile, done readSource = (p, done) -> fs.lstat p, (err, stats) -> if err console.error "Error: invalid path argument #{p}" return done(err) if stats.isDirectory() then return readDir p, done else if stats.isFile() then return readSingleFile p, done async.map programm.args, readSource, (err, parsed) -> return console.error "Error: #{err}" if err result = files: [] parsed.forEach (files) -> files.forEach (f) -> if f.badFile then result.brokenFiles++ result.files.push f result.summary = helpers.summarize result.files.map (x) -> x.stats result.byExt = groupByExt result print result, options, fmtOpts
[ { "context": "> tag', ->\n\t\t\tmarkup = \"\"\"\n\t\t\t<syntax>\n\t\t\tname = 'Cary'\n\t\t\t</syntax>\n\t\t\t\"\"\"\n\n\t\t\telement = @$compile(m", "end": 240, "score": 0.9997739791870117, "start": 236, "tag": "NAME", "value": "Cary" } ]
src/components/syntax/test/syntax-directive.spec.coffee
webmaster89898/CaryLandholt-fatarrow
0
describe 'syntax', -> describe 'syntax directive', -> beforeEach module 'app' beforeEach inject (@$compile, $rootScope) -> @scope = $rootScope.$new() it 'starts with the <pre> tag', -> markup = """ <syntax> name = 'Cary' </syntax> """ element = @$compile(markup)(@scope) controller = element.controller() html = element.html() expect html.indexOf '<pre' .toEqual 0
27052
describe 'syntax', -> describe 'syntax directive', -> beforeEach module 'app' beforeEach inject (@$compile, $rootScope) -> @scope = $rootScope.$new() it 'starts with the <pre> tag', -> markup = """ <syntax> name = '<NAME>' </syntax> """ element = @$compile(markup)(@scope) controller = element.controller() html = element.html() expect html.indexOf '<pre' .toEqual 0
true
describe 'syntax', -> describe 'syntax directive', -> beforeEach module 'app' beforeEach inject (@$compile, $rootScope) -> @scope = $rootScope.$new() it 'starts with the <pre> tag', -> markup = """ <syntax> name = 'PI:NAME:<NAME>END_PI' </syntax> """ element = @$compile(markup)(@scope) controller = element.controller() html = element.html() expect html.indexOf '<pre' .toEqual 0
[ { "context": "')\n\n# Keeps track of an ingredient model\n# @author Torstein Thune\n# @copyright 2016 Microbrew.it\nmbit.directive('mb", "end": 99, "score": 0.9998766779899597, "start": 85, "tag": "NAME", "value": "Torstein Thune" }, { "context": "al of model\n\t\t\t\t\tconsole.log k...
app/ingredient/IngredientDirective.coffee
Microbrewit/microbrewit-recipe-calculator
0
mbit = angular.module('Microbrewit') # Keeps track of an ingredient model # @author Torstein Thune # @copyright 2016 Microbrew.it mbit.directive('mbIngredient', [ 'mbit/services/RecipeUtilityService' '$rootScope' (Utils, $rootScope) -> link = (scope, element, attrs, controller, transcludeFn) -> mergeIngredient = (oldIngredient, model) -> console.log model ingredient = amount: oldIngredient.amount ingredient.amount ?= 0 for key, val of model console.log key if key is '$$hashKey' #do nothing # else if key is 'dataType' # ingredient.type = val # else if key is 'type' # ingredient.subType = val else ingredient[key] = val return ingredient setIngredient = (ingredient) -> newIngredient = mergeIngredient(scope.ingredient, ingredient) for key, val of newIngredient scope.ingredient[key] = val scope.openIngredientPicker = -> console.log 'openIngredientPicker' $rootScope.$broadcast 'openIngredientPicker', setIngredient refreshValues = (ingredient) -> switch ingredient.type when 'fermentable' ingredient.calculated = Utils.calcFermentableValues(ingredient, scope.recipe) scope.refresh ['srm', 'og', 'fg', 'abv'] console.log 'fermentable', ingredient when 'hop' ingredient.calculated = Utils.calcHopValues(ingredient, scope.step, scope.recipe) scope.refresh ['ibu'] console.log 'hop', ingredient scope.$watch 'ingredient', (newValue, oldValue) -> console.log 'ingredient changed' refreshValues(newValue) scope.$watch 'ingredient.amount', () -> refreshValues(scope.ingredient) scope.$watch 'ingredient.aaValue', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.efficiency', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.volume', () -> refreshValues(scope.ingredient) return { scope: 'ingredient': '=' 'remove': '=' 'recipe': '=' 'step': '=' 'refresh': '=' 'settings': '=' replace: true templateUrl: 'recipe/build/ingredient/ingredient.html' link: link } ])
77561
mbit = angular.module('Microbrewit') # Keeps track of an ingredient model # @author <NAME> # @copyright 2016 Microbrew.it mbit.directive('mbIngredient', [ 'mbit/services/RecipeUtilityService' '$rootScope' (Utils, $rootScope) -> link = (scope, element, attrs, controller, transcludeFn) -> mergeIngredient = (oldIngredient, model) -> console.log model ingredient = amount: oldIngredient.amount ingredient.amount ?= 0 for key, val of model console.log key if key is '<KEY>' #do nothing # else if key is '<KEY>' # ingredient.type = val # else if key is 'type' # ingredient.subType = val else ingredient[key] = val return ingredient setIngredient = (ingredient) -> newIngredient = mergeIngredient(scope.ingredient, ingredient) for key, val of newIngredient scope.ingredient[key] = val scope.openIngredientPicker = -> console.log 'openIngredientPicker' $rootScope.$broadcast 'openIngredientPicker', setIngredient refreshValues = (ingredient) -> switch ingredient.type when 'fermentable' ingredient.calculated = Utils.calcFermentableValues(ingredient, scope.recipe) scope.refresh ['srm', 'og', 'fg', 'abv'] console.log 'fermentable', ingredient when 'hop' ingredient.calculated = Utils.calcHopValues(ingredient, scope.step, scope.recipe) scope.refresh ['ibu'] console.log 'hop', ingredient scope.$watch 'ingredient', (newValue, oldValue) -> console.log 'ingredient changed' refreshValues(newValue) scope.$watch 'ingredient.amount', () -> refreshValues(scope.ingredient) scope.$watch 'ingredient.aaValue', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.efficiency', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.volume', () -> refreshValues(scope.ingredient) return { scope: 'ingredient': '=' 'remove': '=' 'recipe': '=' 'step': '=' 'refresh': '=' 'settings': '=' replace: true templateUrl: 'recipe/build/ingredient/ingredient.html' link: link } ])
true
mbit = angular.module('Microbrewit') # Keeps track of an ingredient model # @author PI:NAME:<NAME>END_PI # @copyright 2016 Microbrew.it mbit.directive('mbIngredient', [ 'mbit/services/RecipeUtilityService' '$rootScope' (Utils, $rootScope) -> link = (scope, element, attrs, controller, transcludeFn) -> mergeIngredient = (oldIngredient, model) -> console.log model ingredient = amount: oldIngredient.amount ingredient.amount ?= 0 for key, val of model console.log key if key is 'PI:KEY:<KEY>END_PI' #do nothing # else if key is 'PI:KEY:<KEY>END_PI' # ingredient.type = val # else if key is 'type' # ingredient.subType = val else ingredient[key] = val return ingredient setIngredient = (ingredient) -> newIngredient = mergeIngredient(scope.ingredient, ingredient) for key, val of newIngredient scope.ingredient[key] = val scope.openIngredientPicker = -> console.log 'openIngredientPicker' $rootScope.$broadcast 'openIngredientPicker', setIngredient refreshValues = (ingredient) -> switch ingredient.type when 'fermentable' ingredient.calculated = Utils.calcFermentableValues(ingredient, scope.recipe) scope.refresh ['srm', 'og', 'fg', 'abv'] console.log 'fermentable', ingredient when 'hop' ingredient.calculated = Utils.calcHopValues(ingredient, scope.step, scope.recipe) scope.refresh ['ibu'] console.log 'hop', ingredient scope.$watch 'ingredient', (newValue, oldValue) -> console.log 'ingredient changed' refreshValues(newValue) scope.$watch 'ingredient.amount', () -> refreshValues(scope.ingredient) scope.$watch 'ingredient.aaValue', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.efficiency', () -> refreshValues(scope.ingredient) scope.$watch 'recipe.volume', () -> refreshValues(scope.ingredient) return { scope: 'ingredient': '=' 'remove': '=' 'recipe': '=' 'step': '=' 'refresh': '=' 'settings': '=' replace: true templateUrl: 'recipe/build/ingredient/ingredient.html' link: link } ])
[ { "context": " href\n title\n author {\n name\n }\n }\n artists(size: 16) {\n ", "end": 686, "score": 0.9635403156280518, "start": 682, "tag": "NAME", "value": "name" } ]
desktop/apps/artwork/components/artists/query.coffee
dblock/force
1
module.exports = """ fragment artists on Artwork { artists { bio name href blurb(format: HTML) biography_blurb(format: HTML, partner_bio: true) { text credit partner_id } exhibition_highlights(size: 20) { kind name start_at href partner { ... on ExternalPartner { name } ... on Partner { name } } city } articles { thumbnail_image { cropped(width: 100, height: 100) { url } } href title author { name } } artists(size: 16) { ... artistCell } } } #{require '../../../../components/artist_cell/query.coffee'} """
42422
module.exports = """ fragment artists on Artwork { artists { bio name href blurb(format: HTML) biography_blurb(format: HTML, partner_bio: true) { text credit partner_id } exhibition_highlights(size: 20) { kind name start_at href partner { ... on ExternalPartner { name } ... on Partner { name } } city } articles { thumbnail_image { cropped(width: 100, height: 100) { url } } href title author { <NAME> } } artists(size: 16) { ... artistCell } } } #{require '../../../../components/artist_cell/query.coffee'} """
true
module.exports = """ fragment artists on Artwork { artists { bio name href blurb(format: HTML) biography_blurb(format: HTML, partner_bio: true) { text credit partner_id } exhibition_highlights(size: 20) { kind name start_at href partner { ... on ExternalPartner { name } ... on Partner { name } } city } articles { thumbnail_image { cropped(width: 100, height: 100) { url } } href title author { PI:NAME:<NAME>END_PI } } artists(size: 16) { ... artistCell } } } #{require '../../../../components/artist_cell/query.coffee'} """
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992429614067078, "start": 12, "tag": "NAME", "value": "Joyent" } ]
lib/_stream_readable.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. ReadableState = (options, stream) -> options = options or {} # object stream flag. Used to make read(n) ignore n and to # make all the buffer merging and length checks go away @objectMode = !!options.objectMode @objectMode = @objectMode or !!options.readableObjectMode if stream instanceof Stream.Duplex # the point at which it stops calling _read() to fill the buffer # Note: 0 is a valid value, means "don't call _read preemptively ever" hwm = options.highWaterMark defaultHwm = (if @objectMode then 16 else 16 * 1024) @highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm) # cast to ints. @highWaterMark = ~~@highWaterMark @buffer = [] @length = 0 @pipes = null @pipesCount = 0 @flowing = null @ended = false @endEmitted = false @reading = false # a flag to be able to tell if the onwrite cb is called immediately, # or on a later tick. We set this to true at first, because any # actions that shouldn't happen until "later" should generally also # not happen before the first write call. @sync = true # whenever we return null, then we set a flag to say # that we're awaiting a 'readable' event emission. @needReadable = false @emittedReadable = false @readableListening = false # Crypto is kind of old and crusty. Historically, its default string # encoding is 'binary' so we have to make this configurable. # Everything else in the universe uses 'utf8', though. @defaultEncoding = options.defaultEncoding or "utf8" # when piping, we only care about 'readable' events that happen # after read()ing all the bytes and not getting any pushback. @ranOut = false # the number of writers that are awaiting a drain event in .pipe()s @awaitDrain = 0 # if true, a maybeReadMore has been scheduled @readingMore = false @decoder = null @encoding = null if options.encoding StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @decoder = new StringDecoder(options.encoding) @encoding = options.encoding return Readable = (options) -> return new Readable(options) unless this instanceof Readable @_readableState = new ReadableState(options, this) # legacy @readable = true Stream.call this return # Manually shove something into the read() buffer. # This returns true if the highWaterMark has not been hit yet, # similar to how Writable.write() returns true if you should # write() some more. # Unshift should *always* be something directly out of read() readableAddChunk = (stream, state, chunk, encoding, addToFront) -> er = chunkInvalid(state, chunk) if er stream.emit "error", er else if chunk is null state.reading = false onEofChunk stream, state unless state.ended else if state.objectMode or chunk and chunk.length > 0 if state.ended and not addToFront e = new Error("stream.push() after EOF") stream.emit "error", e else if state.endEmitted and addToFront e = new Error("stream.unshift() after end event") stream.emit "error", e else chunk = state.decoder.write(chunk) if state.decoder and not addToFront and not encoding state.reading = false unless addToFront # if we want the data now, just emit it. if state.flowing and state.length is 0 and not state.sync stream.emit "data", chunk stream.read 0 else # update the buffer info. state.length += (if state.objectMode then 1 else chunk.length) if addToFront state.buffer.unshift chunk else state.buffer.push chunk emitReadable stream if state.needReadable maybeReadMore stream, state else state.reading = false unless addToFront needMoreData state # if it's past the high water mark, we can push in some more. # Also, if we have no data yet, we can stand some # more bytes. This is to work around cases where hwm=0, # such as the repl. Also, if the push() triggered a # readable event, and the user called read(largeNumber) such that # needReadable was set, then we ought to push more, so that another # 'readable' event will be triggered. needMoreData = (state) -> not state.ended and (state.needReadable or state.length < state.highWaterMark or state.length is 0) # backwards compatibility. # Don't raise the hwm > 128MB roundUpToNextPowerOf2 = (n) -> if n >= MAX_HWM n = MAX_HWM else # Get the next highest power of 2 n-- p = 1 while p < 32 n |= n >> p p <<= 1 n++ n howMuchToRead = (n, state) -> return 0 if state.length is 0 and state.ended return (if n is 0 then 0 else 1) if state.objectMode if util.isNull(n) or isNaN(n) # only flow one buffer at a time if state.flowing and state.buffer.length return state.buffer[0].length else return state.length return 0 if n <= 0 # If we're asking for more than the target buffer level, # then raise the water mark. Bump up to the next highest # power of 2, to prevent increasing it excessively in tiny # amounts. state.highWaterMark = roundUpToNextPowerOf2(n) if n > state.highWaterMark # don't have that much. return null, unless we've ended. if n > state.length unless state.ended state.needReadable = true return 0 else return state.length n # you can override either this method, or the async _read(n) below. # if we're doing read(0) to trigger a readable event, but we # already have a bunch of data in the buffer, then just trigger # the 'readable' event and move on. # if we've ended, and we're now clear, then finish it up. # All the actual chunk generation logic needs to be # *below* the call to _read. The reason is that in certain # synthetic stream cases, such as passthrough streams, _read # may be a completely synchronous operation which may change # the state of the read buffer, providing enough data when # before there was *not* enough. # # So, the steps are: # 1. Figure out what the state of things will be after we do # a read from the buffer. # # 2. If that resulting state will trigger a _read, then call _read. # Note that this may be asynchronous, or synchronous. Yes, it is # deeply ugly to write APIs this way, but that still doesn't mean # that the Readable class should behave improperly, as streams are # designed to be sync/async agnostic. # Take note if the _read call is sync or async (ie, if the read call # has returned yet), so that we know whether or not it's safe to emit # 'readable' etc. # # 3. Actually pull the requested chunks out of the buffer and return. # if we need a readable event, then we need to do some reading. # if we currently have less than the highWaterMark, then also read some # however, if we've ended, then there's no point, and if we're already # reading, then it's unnecessary. # if the length is currently zero, then we *need* a readable event. # call internal read method # If _read pushed data synchronously, then `reading` will be false, # and we need to re-evaluate how much data we can return to the user. # If we have nothing in the buffer, then we want to know # as soon as we *do* get something into the buffer. # If we tried to read() past the EOF, then emit end on the next tick. chunkInvalid = (state, chunk) -> er = null er = new TypeError("Invalid non-string/buffer chunk") if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode er onEofChunk = (stream, state) -> if state.decoder and not state.ended chunk = state.decoder.end() if chunk and chunk.length state.buffer.push chunk state.length += (if state.objectMode then 1 else chunk.length) state.ended = true # emit 'readable' now to make sure it gets picked up. emitReadable stream return # Don't emit readable right away in sync mode, because this can trigger # another read() call => stack overflow. This way, it might trigger # a nextTick recursion warning, but that's not so bad. emitReadable = (stream) -> state = stream._readableState state.needReadable = false unless state.emittedReadable debug "emitReadable", state.flowing state.emittedReadable = true if state.sync process.nextTick -> emitReadable_ stream return else emitReadable_ stream return emitReadable_ = (stream) -> debug "emit readable" stream.emit "readable" flow stream return # at this point, the user has presumably seen the 'readable' event, # and called read() to consume some data. that may have triggered # in turn another _read(n) call, in which case reading = true if # it's in progress. # However, if we're not ended, or reading, and the length < hwm, # then go ahead and try to read some more preemptively. maybeReadMore = (stream, state) -> unless state.readingMore state.readingMore = true process.nextTick -> maybeReadMore_ stream, state return return maybeReadMore_ = (stream, state) -> len = state.length while not state.reading and not state.flowing and not state.ended and state.length < state.highWaterMark debug "maybeReadMore read 0" stream.read 0 if len is state.length # didn't get any data, stop spinning. break else len = state.length state.readingMore = false return # abstract method. to be overridden in specific implementation classes. # call cb(er, data) where data is <= n in length. # for virtual (non-string, non-buffer) streams, "length" is somewhat # arbitrary, and perhaps not very meaningful. # when the dest drains, it reduces the awaitDrain counter # on the source. This would be more elegant with a .once() # handler in flow(), but adding and removing repeatedly is # too slow. # cleanup event handlers once the pipe is broken # if the reader is waiting for a drain event from this # specific writer, then it would cause it to never start # flowing again. # So, if this is awaiting a drain, then we just call it now. # If we don't know, then assume that we are waiting for one. # if the dest has an error, then stop piping into it. # however, don't suppress the throwing behavior for this. # This is a brutally ugly hack to make sure that our error handler # is attached before any userland ones. NEVER DO THIS. # Both close and finish should trigger unpipe, but only once. # tell the dest that it's being piped to # start the flow if it hasn't been started already. pipeOnDrain = (src) -> -> state = src._readableState debug "pipeOnDrain", state.awaitDrain state.awaitDrain-- if state.awaitDrain if state.awaitDrain is 0 and EE.listenerCount(src, "data") state.flowing = true flow src return # if we're not piping anywhere, then do nothing. # just one destination. most common case. # passed in one, but it's not the right one. # got a match. # slow case. multiple pipe destinations. # remove all. # try to find the right one. # set up data events if they are asked for # Ensure readable listeners eventually get something # If listening to data, and it has not explicitly been paused, # then call resume to start the flow of data on the next tick. # pause() and resume() are remnants of the legacy readable stream API # If the user uses them, then switch into old mode. resume = (stream, state) -> unless state.resumeScheduled state.resumeScheduled = true process.nextTick -> resume_ stream, state return return resume_ = (stream, state) -> unless state.reading debug "resume read 0" stream.read 0 state.resumeScheduled = false stream.emit "resume" flow stream stream.read 0 if state.flowing and not state.reading return flow = (stream) -> state = stream._readableState debug "flow", state.flowing if state.flowing loop chunk = stream.read() break unless null isnt chunk and state.flowing return # wrap an old-style stream as the async data source. # This is *not* part of the readable stream interface. # It is an ugly unfortunate mess of history. # don't skip over falsy values in objectMode #if (state.objectMode && util.isNullOrUndefined(chunk)) # proxy all the other methods. # important when wrapping filters and duplexes. # proxy certain important events. # when we try to consume some more bytes, simply unpause the # underlying stream. # exposed for testing purposes only. # Pluck off n bytes from an array of buffers. # Length is the combined lengths of all the buffers in the list. fromList = (n, state) -> list = state.buffer length = state.length stringMode = !!state.decoder objectMode = !!state.objectMode ret = undefined # nothing in the list, definitely empty. return null if list.length is 0 if length is 0 ret = null else if objectMode ret = list.shift() else if not n or n >= length # read it all, truncate the array. if stringMode ret = list.join("") else ret = Buffer.concat(list, length) list.length = 0 else # read just some of it. if n < list[0].length # just take a part of the first list item. # slice is the same for buffers and strings. buf = list[0] ret = buf.slice(0, n) list[0] = buf.slice(n) else if n is list[0].length # first list is a perfect match ret = list.shift() else # complex case. # we have enough to cover it, but it spans past the first buffer. if stringMode ret = "" else ret = new Buffer(n) c = 0 i = 0 l = list.length while i < l and c < n buf = list[0] cpy = Math.min(n - c, buf.length) if stringMode ret += buf.slice(0, cpy) else buf.copy ret, c, 0, cpy if cpy < buf.length list[0] = buf.slice(cpy) else list.shift() c += cpy i++ ret endReadable = (stream) -> state = stream._readableState # If we get here before consuming all the bytes, then that is a # bug in node. Should never happen. throw new Error("endReadable called on non-empty stream") if state.length > 0 unless state.endEmitted state.ended = true process.nextTick -> # Check that we didn't get one last unshift. if not state.endEmitted and state.length is 0 state.endEmitted = true stream.readable = false stream.emit "end" return return "use strict" module.exports = Readable Readable.ReadableState = ReadableState EE = require("events").EventEmitter Stream = require("stream") util = require("util") StringDecoder = undefined debug = util.debuglog("stream") util.inherits Readable, Stream Readable::push = (chunk, encoding) -> state = @_readableState if util.isString(chunk) and not state.objectMode encoding = encoding or state.defaultEncoding if encoding isnt state.encoding chunk = new Buffer(chunk, encoding) encoding = "" readableAddChunk this, state, chunk, encoding, false Readable::unshift = (chunk) -> state = @_readableState readableAddChunk this, state, chunk, "", true Readable::isPaused = -> @_readableState.flowing is false Readable::setEncoding = (enc) -> StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @_readableState.decoder = new StringDecoder(enc) @_readableState.encoding = enc this MAX_HWM = 0x800000 Readable::read = (n) -> debug "read", n state = @_readableState nOrig = n state.emittedReadable = false if not util.isNumber(n) or n > 0 if n is 0 and state.needReadable and (state.length >= state.highWaterMark or state.ended) debug "read: emitReadable", state.length, state.ended if state.length is 0 and state.ended endReadable this else emitReadable this return null n = howMuchToRead(n, state) if n is 0 and state.ended endReadable this if state.length is 0 return null doRead = state.needReadable debug "need readable", doRead if state.length is 0 or state.length - n < state.highWaterMark doRead = true debug "length less than watermark", doRead if state.ended or state.reading doRead = false debug "reading or ended", doRead if doRead debug "do read" state.reading = true state.sync = true state.needReadable = true if state.length is 0 @_read state.highWaterMark state.sync = false n = howMuchToRead(nOrig, state) if doRead and not state.reading ret = undefined if n > 0 ret = fromList(n, state) else ret = null if util.isNull(ret) state.needReadable = true n = 0 state.length -= n state.needReadable = true if state.length is 0 and not state.ended endReadable this if nOrig isnt n and state.ended and state.length is 0 @emit "data", ret unless util.isNull(ret) ret Readable::_read = (n) -> @emit "error", new Error("not implemented") return Readable::pipe = (dest, pipeOpts) -> onunpipe = (readable) -> debug "onunpipe" cleanup() if readable is src return onend = -> debug "onend" dest.end() return cleanup = -> debug "cleanup" dest.removeListener "close", onclose dest.removeListener "finish", onfinish dest.removeListener "drain", ondrain dest.removeListener "error", onerror dest.removeListener "unpipe", onunpipe src.removeListener "end", onend src.removeListener "end", cleanup src.removeListener "data", ondata ondrain() if state.awaitDrain and (not dest._writableState or dest._writableState.needDrain) return ondata = (chunk) -> debug "ondata" ret = dest.write(chunk) if false is ret debug "false write response, pause", src._readableState.awaitDrain src._readableState.awaitDrain++ src.pause() return onerror = (er) -> debug "onerror", er unpipe() dest.removeListener "error", onerror dest.emit "error", er if EE.listenerCount(dest, "error") is 0 return onclose = -> dest.removeListener "finish", onfinish unpipe() return onfinish = -> debug "onfinish" dest.removeListener "close", onclose unpipe() return unpipe = -> debug "unpipe" src.unpipe dest return src = this state = @_readableState switch state.pipesCount when 0 state.pipes = dest when 1 state.pipes = [ state.pipes dest ] else state.pipes.push dest state.pipesCount += 1 debug "pipe count=%d opts=%j", state.pipesCount, pipeOpts doEnd = (not pipeOpts or pipeOpts.end isnt false) and dest isnt process.stdout and dest isnt process.stderr endFn = (if doEnd then onend else cleanup) if state.endEmitted process.nextTick endFn else src.once "end", endFn dest.on "unpipe", onunpipe ondrain = pipeOnDrain(src) dest.on "drain", ondrain src.on "data", ondata if not dest._events or not dest._events.error dest.on "error", onerror else if Array.isArray(dest._events.error) dest._events.error.unshift onerror else dest._events.error = [ onerror dest._events.error ] dest.once "close", onclose dest.once "finish", onfinish dest.emit "pipe", src unless state.flowing debug "pipe resume" src.resume() dest Readable::unpipe = (dest) -> state = @_readableState return this if state.pipesCount is 0 if state.pipesCount is 1 return this if dest and dest isnt state.pipes dest = state.pipes unless dest state.pipes = null state.pipesCount = 0 state.flowing = false dest.emit "unpipe", this if dest return this unless dest dests = state.pipes len = state.pipesCount state.pipes = null state.pipesCount = 0 state.flowing = false i = 0 while i < len dests[i].emit "unpipe", this i++ return this i = state.pipes.indexOf(dest) return this if i is -1 state.pipes.splice i, 1 state.pipesCount -= 1 state.pipes = state.pipes[0] if state.pipesCount is 1 dest.emit "unpipe", this this Readable::on = (ev, fn) -> res = Stream::on.call(this, ev, fn) @resume() if ev is "data" and false isnt @_readableState.flowing if ev is "readable" and @readable state = @_readableState unless state.readableListening state.readableListening = true state.emittedReadable = false state.needReadable = true unless state.reading self = this process.nextTick -> debug "readable nexttick read 0" self.read 0 return else emitReadable this, state if state.length res Readable::addListener = Readable::on Readable::resume = -> state = @_readableState unless state.flowing debug "resume" state.flowing = true resume this, state this Readable::pause = -> debug "call pause flowing=%j", @_readableState.flowing if false isnt @_readableState.flowing debug "pause" @_readableState.flowing = false @emit "pause" this Readable::wrap = (stream) -> state = @_readableState paused = false self = this stream.on "end", -> debug "wrapped end" if state.decoder and not state.ended chunk = state.decoder.end() self.push chunk if chunk and chunk.length self.push null return stream.on "data", (chunk) -> debug "wrapped data" chunk = state.decoder.write(chunk) if state.decoder if state.objectMode and (chunk is null or chunk is `undefined`) return else return if not state.objectMode and (not chunk or not chunk.length) ret = self.push(chunk) unless ret paused = true stream.pause() return for i of stream if util.isFunction(stream[i]) and util.isUndefined(this[i]) this[i] = (method) -> -> stream[method].apply stream, arguments (i) events = [ "error" "close" "destroy" "pause" "resume" ] events.forEach (ev) -> stream.on ev, self.emit.bind(self, ev) return self._read = (n) -> debug "wrapped _read", n if paused paused = false stream.resume() return self Readable._fromList = fromList
197096
# 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. ReadableState = (options, stream) -> options = options or {} # object stream flag. Used to make read(n) ignore n and to # make all the buffer merging and length checks go away @objectMode = !!options.objectMode @objectMode = @objectMode or !!options.readableObjectMode if stream instanceof Stream.Duplex # the point at which it stops calling _read() to fill the buffer # Note: 0 is a valid value, means "don't call _read preemptively ever" hwm = options.highWaterMark defaultHwm = (if @objectMode then 16 else 16 * 1024) @highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm) # cast to ints. @highWaterMark = ~~@highWaterMark @buffer = [] @length = 0 @pipes = null @pipesCount = 0 @flowing = null @ended = false @endEmitted = false @reading = false # a flag to be able to tell if the onwrite cb is called immediately, # or on a later tick. We set this to true at first, because any # actions that shouldn't happen until "later" should generally also # not happen before the first write call. @sync = true # whenever we return null, then we set a flag to say # that we're awaiting a 'readable' event emission. @needReadable = false @emittedReadable = false @readableListening = false # Crypto is kind of old and crusty. Historically, its default string # encoding is 'binary' so we have to make this configurable. # Everything else in the universe uses 'utf8', though. @defaultEncoding = options.defaultEncoding or "utf8" # when piping, we only care about 'readable' events that happen # after read()ing all the bytes and not getting any pushback. @ranOut = false # the number of writers that are awaiting a drain event in .pipe()s @awaitDrain = 0 # if true, a maybeReadMore has been scheduled @readingMore = false @decoder = null @encoding = null if options.encoding StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @decoder = new StringDecoder(options.encoding) @encoding = options.encoding return Readable = (options) -> return new Readable(options) unless this instanceof Readable @_readableState = new ReadableState(options, this) # legacy @readable = true Stream.call this return # Manually shove something into the read() buffer. # This returns true if the highWaterMark has not been hit yet, # similar to how Writable.write() returns true if you should # write() some more. # Unshift should *always* be something directly out of read() readableAddChunk = (stream, state, chunk, encoding, addToFront) -> er = chunkInvalid(state, chunk) if er stream.emit "error", er else if chunk is null state.reading = false onEofChunk stream, state unless state.ended else if state.objectMode or chunk and chunk.length > 0 if state.ended and not addToFront e = new Error("stream.push() after EOF") stream.emit "error", e else if state.endEmitted and addToFront e = new Error("stream.unshift() after end event") stream.emit "error", e else chunk = state.decoder.write(chunk) if state.decoder and not addToFront and not encoding state.reading = false unless addToFront # if we want the data now, just emit it. if state.flowing and state.length is 0 and not state.sync stream.emit "data", chunk stream.read 0 else # update the buffer info. state.length += (if state.objectMode then 1 else chunk.length) if addToFront state.buffer.unshift chunk else state.buffer.push chunk emitReadable stream if state.needReadable maybeReadMore stream, state else state.reading = false unless addToFront needMoreData state # if it's past the high water mark, we can push in some more. # Also, if we have no data yet, we can stand some # more bytes. This is to work around cases where hwm=0, # such as the repl. Also, if the push() triggered a # readable event, and the user called read(largeNumber) such that # needReadable was set, then we ought to push more, so that another # 'readable' event will be triggered. needMoreData = (state) -> not state.ended and (state.needReadable or state.length < state.highWaterMark or state.length is 0) # backwards compatibility. # Don't raise the hwm > 128MB roundUpToNextPowerOf2 = (n) -> if n >= MAX_HWM n = MAX_HWM else # Get the next highest power of 2 n-- p = 1 while p < 32 n |= n >> p p <<= 1 n++ n howMuchToRead = (n, state) -> return 0 if state.length is 0 and state.ended return (if n is 0 then 0 else 1) if state.objectMode if util.isNull(n) or isNaN(n) # only flow one buffer at a time if state.flowing and state.buffer.length return state.buffer[0].length else return state.length return 0 if n <= 0 # If we're asking for more than the target buffer level, # then raise the water mark. Bump up to the next highest # power of 2, to prevent increasing it excessively in tiny # amounts. state.highWaterMark = roundUpToNextPowerOf2(n) if n > state.highWaterMark # don't have that much. return null, unless we've ended. if n > state.length unless state.ended state.needReadable = true return 0 else return state.length n # you can override either this method, or the async _read(n) below. # if we're doing read(0) to trigger a readable event, but we # already have a bunch of data in the buffer, then just trigger # the 'readable' event and move on. # if we've ended, and we're now clear, then finish it up. # All the actual chunk generation logic needs to be # *below* the call to _read. The reason is that in certain # synthetic stream cases, such as passthrough streams, _read # may be a completely synchronous operation which may change # the state of the read buffer, providing enough data when # before there was *not* enough. # # So, the steps are: # 1. Figure out what the state of things will be after we do # a read from the buffer. # # 2. If that resulting state will trigger a _read, then call _read. # Note that this may be asynchronous, or synchronous. Yes, it is # deeply ugly to write APIs this way, but that still doesn't mean # that the Readable class should behave improperly, as streams are # designed to be sync/async agnostic. # Take note if the _read call is sync or async (ie, if the read call # has returned yet), so that we know whether or not it's safe to emit # 'readable' etc. # # 3. Actually pull the requested chunks out of the buffer and return. # if we need a readable event, then we need to do some reading. # if we currently have less than the highWaterMark, then also read some # however, if we've ended, then there's no point, and if we're already # reading, then it's unnecessary. # if the length is currently zero, then we *need* a readable event. # call internal read method # If _read pushed data synchronously, then `reading` will be false, # and we need to re-evaluate how much data we can return to the user. # If we have nothing in the buffer, then we want to know # as soon as we *do* get something into the buffer. # If we tried to read() past the EOF, then emit end on the next tick. chunkInvalid = (state, chunk) -> er = null er = new TypeError("Invalid non-string/buffer chunk") if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode er onEofChunk = (stream, state) -> if state.decoder and not state.ended chunk = state.decoder.end() if chunk and chunk.length state.buffer.push chunk state.length += (if state.objectMode then 1 else chunk.length) state.ended = true # emit 'readable' now to make sure it gets picked up. emitReadable stream return # Don't emit readable right away in sync mode, because this can trigger # another read() call => stack overflow. This way, it might trigger # a nextTick recursion warning, but that's not so bad. emitReadable = (stream) -> state = stream._readableState state.needReadable = false unless state.emittedReadable debug "emitReadable", state.flowing state.emittedReadable = true if state.sync process.nextTick -> emitReadable_ stream return else emitReadable_ stream return emitReadable_ = (stream) -> debug "emit readable" stream.emit "readable" flow stream return # at this point, the user has presumably seen the 'readable' event, # and called read() to consume some data. that may have triggered # in turn another _read(n) call, in which case reading = true if # it's in progress. # However, if we're not ended, or reading, and the length < hwm, # then go ahead and try to read some more preemptively. maybeReadMore = (stream, state) -> unless state.readingMore state.readingMore = true process.nextTick -> maybeReadMore_ stream, state return return maybeReadMore_ = (stream, state) -> len = state.length while not state.reading and not state.flowing and not state.ended and state.length < state.highWaterMark debug "maybeReadMore read 0" stream.read 0 if len is state.length # didn't get any data, stop spinning. break else len = state.length state.readingMore = false return # abstract method. to be overridden in specific implementation classes. # call cb(er, data) where data is <= n in length. # for virtual (non-string, non-buffer) streams, "length" is somewhat # arbitrary, and perhaps not very meaningful. # when the dest drains, it reduces the awaitDrain counter # on the source. This would be more elegant with a .once() # handler in flow(), but adding and removing repeatedly is # too slow. # cleanup event handlers once the pipe is broken # if the reader is waiting for a drain event from this # specific writer, then it would cause it to never start # flowing again. # So, if this is awaiting a drain, then we just call it now. # If we don't know, then assume that we are waiting for one. # if the dest has an error, then stop piping into it. # however, don't suppress the throwing behavior for this. # This is a brutally ugly hack to make sure that our error handler # is attached before any userland ones. NEVER DO THIS. # Both close and finish should trigger unpipe, but only once. # tell the dest that it's being piped to # start the flow if it hasn't been started already. pipeOnDrain = (src) -> -> state = src._readableState debug "pipeOnDrain", state.awaitDrain state.awaitDrain-- if state.awaitDrain if state.awaitDrain is 0 and EE.listenerCount(src, "data") state.flowing = true flow src return # if we're not piping anywhere, then do nothing. # just one destination. most common case. # passed in one, but it's not the right one. # got a match. # slow case. multiple pipe destinations. # remove all. # try to find the right one. # set up data events if they are asked for # Ensure readable listeners eventually get something # If listening to data, and it has not explicitly been paused, # then call resume to start the flow of data on the next tick. # pause() and resume() are remnants of the legacy readable stream API # If the user uses them, then switch into old mode. resume = (stream, state) -> unless state.resumeScheduled state.resumeScheduled = true process.nextTick -> resume_ stream, state return return resume_ = (stream, state) -> unless state.reading debug "resume read 0" stream.read 0 state.resumeScheduled = false stream.emit "resume" flow stream stream.read 0 if state.flowing and not state.reading return flow = (stream) -> state = stream._readableState debug "flow", state.flowing if state.flowing loop chunk = stream.read() break unless null isnt chunk and state.flowing return # wrap an old-style stream as the async data source. # This is *not* part of the readable stream interface. # It is an ugly unfortunate mess of history. # don't skip over falsy values in objectMode #if (state.objectMode && util.isNullOrUndefined(chunk)) # proxy all the other methods. # important when wrapping filters and duplexes. # proxy certain important events. # when we try to consume some more bytes, simply unpause the # underlying stream. # exposed for testing purposes only. # Pluck off n bytes from an array of buffers. # Length is the combined lengths of all the buffers in the list. fromList = (n, state) -> list = state.buffer length = state.length stringMode = !!state.decoder objectMode = !!state.objectMode ret = undefined # nothing in the list, definitely empty. return null if list.length is 0 if length is 0 ret = null else if objectMode ret = list.shift() else if not n or n >= length # read it all, truncate the array. if stringMode ret = list.join("") else ret = Buffer.concat(list, length) list.length = 0 else # read just some of it. if n < list[0].length # just take a part of the first list item. # slice is the same for buffers and strings. buf = list[0] ret = buf.slice(0, n) list[0] = buf.slice(n) else if n is list[0].length # first list is a perfect match ret = list.shift() else # complex case. # we have enough to cover it, but it spans past the first buffer. if stringMode ret = "" else ret = new Buffer(n) c = 0 i = 0 l = list.length while i < l and c < n buf = list[0] cpy = Math.min(n - c, buf.length) if stringMode ret += buf.slice(0, cpy) else buf.copy ret, c, 0, cpy if cpy < buf.length list[0] = buf.slice(cpy) else list.shift() c += cpy i++ ret endReadable = (stream) -> state = stream._readableState # If we get here before consuming all the bytes, then that is a # bug in node. Should never happen. throw new Error("endReadable called on non-empty stream") if state.length > 0 unless state.endEmitted state.ended = true process.nextTick -> # Check that we didn't get one last unshift. if not state.endEmitted and state.length is 0 state.endEmitted = true stream.readable = false stream.emit "end" return return "use strict" module.exports = Readable Readable.ReadableState = ReadableState EE = require("events").EventEmitter Stream = require("stream") util = require("util") StringDecoder = undefined debug = util.debuglog("stream") util.inherits Readable, Stream Readable::push = (chunk, encoding) -> state = @_readableState if util.isString(chunk) and not state.objectMode encoding = encoding or state.defaultEncoding if encoding isnt state.encoding chunk = new Buffer(chunk, encoding) encoding = "" readableAddChunk this, state, chunk, encoding, false Readable::unshift = (chunk) -> state = @_readableState readableAddChunk this, state, chunk, "", true Readable::isPaused = -> @_readableState.flowing is false Readable::setEncoding = (enc) -> StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @_readableState.decoder = new StringDecoder(enc) @_readableState.encoding = enc this MAX_HWM = 0x800000 Readable::read = (n) -> debug "read", n state = @_readableState nOrig = n state.emittedReadable = false if not util.isNumber(n) or n > 0 if n is 0 and state.needReadable and (state.length >= state.highWaterMark or state.ended) debug "read: emitReadable", state.length, state.ended if state.length is 0 and state.ended endReadable this else emitReadable this return null n = howMuchToRead(n, state) if n is 0 and state.ended endReadable this if state.length is 0 return null doRead = state.needReadable debug "need readable", doRead if state.length is 0 or state.length - n < state.highWaterMark doRead = true debug "length less than watermark", doRead if state.ended or state.reading doRead = false debug "reading or ended", doRead if doRead debug "do read" state.reading = true state.sync = true state.needReadable = true if state.length is 0 @_read state.highWaterMark state.sync = false n = howMuchToRead(nOrig, state) if doRead and not state.reading ret = undefined if n > 0 ret = fromList(n, state) else ret = null if util.isNull(ret) state.needReadable = true n = 0 state.length -= n state.needReadable = true if state.length is 0 and not state.ended endReadable this if nOrig isnt n and state.ended and state.length is 0 @emit "data", ret unless util.isNull(ret) ret Readable::_read = (n) -> @emit "error", new Error("not implemented") return Readable::pipe = (dest, pipeOpts) -> onunpipe = (readable) -> debug "onunpipe" cleanup() if readable is src return onend = -> debug "onend" dest.end() return cleanup = -> debug "cleanup" dest.removeListener "close", onclose dest.removeListener "finish", onfinish dest.removeListener "drain", ondrain dest.removeListener "error", onerror dest.removeListener "unpipe", onunpipe src.removeListener "end", onend src.removeListener "end", cleanup src.removeListener "data", ondata ondrain() if state.awaitDrain and (not dest._writableState or dest._writableState.needDrain) return ondata = (chunk) -> debug "ondata" ret = dest.write(chunk) if false is ret debug "false write response, pause", src._readableState.awaitDrain src._readableState.awaitDrain++ src.pause() return onerror = (er) -> debug "onerror", er unpipe() dest.removeListener "error", onerror dest.emit "error", er if EE.listenerCount(dest, "error") is 0 return onclose = -> dest.removeListener "finish", onfinish unpipe() return onfinish = -> debug "onfinish" dest.removeListener "close", onclose unpipe() return unpipe = -> debug "unpipe" src.unpipe dest return src = this state = @_readableState switch state.pipesCount when 0 state.pipes = dest when 1 state.pipes = [ state.pipes dest ] else state.pipes.push dest state.pipesCount += 1 debug "pipe count=%d opts=%j", state.pipesCount, pipeOpts doEnd = (not pipeOpts or pipeOpts.end isnt false) and dest isnt process.stdout and dest isnt process.stderr endFn = (if doEnd then onend else cleanup) if state.endEmitted process.nextTick endFn else src.once "end", endFn dest.on "unpipe", onunpipe ondrain = pipeOnDrain(src) dest.on "drain", ondrain src.on "data", ondata if not dest._events or not dest._events.error dest.on "error", onerror else if Array.isArray(dest._events.error) dest._events.error.unshift onerror else dest._events.error = [ onerror dest._events.error ] dest.once "close", onclose dest.once "finish", onfinish dest.emit "pipe", src unless state.flowing debug "pipe resume" src.resume() dest Readable::unpipe = (dest) -> state = @_readableState return this if state.pipesCount is 0 if state.pipesCount is 1 return this if dest and dest isnt state.pipes dest = state.pipes unless dest state.pipes = null state.pipesCount = 0 state.flowing = false dest.emit "unpipe", this if dest return this unless dest dests = state.pipes len = state.pipesCount state.pipes = null state.pipesCount = 0 state.flowing = false i = 0 while i < len dests[i].emit "unpipe", this i++ return this i = state.pipes.indexOf(dest) return this if i is -1 state.pipes.splice i, 1 state.pipesCount -= 1 state.pipes = state.pipes[0] if state.pipesCount is 1 dest.emit "unpipe", this this Readable::on = (ev, fn) -> res = Stream::on.call(this, ev, fn) @resume() if ev is "data" and false isnt @_readableState.flowing if ev is "readable" and @readable state = @_readableState unless state.readableListening state.readableListening = true state.emittedReadable = false state.needReadable = true unless state.reading self = this process.nextTick -> debug "readable nexttick read 0" self.read 0 return else emitReadable this, state if state.length res Readable::addListener = Readable::on Readable::resume = -> state = @_readableState unless state.flowing debug "resume" state.flowing = true resume this, state this Readable::pause = -> debug "call pause flowing=%j", @_readableState.flowing if false isnt @_readableState.flowing debug "pause" @_readableState.flowing = false @emit "pause" this Readable::wrap = (stream) -> state = @_readableState paused = false self = this stream.on "end", -> debug "wrapped end" if state.decoder and not state.ended chunk = state.decoder.end() self.push chunk if chunk and chunk.length self.push null return stream.on "data", (chunk) -> debug "wrapped data" chunk = state.decoder.write(chunk) if state.decoder if state.objectMode and (chunk is null or chunk is `undefined`) return else return if not state.objectMode and (not chunk or not chunk.length) ret = self.push(chunk) unless ret paused = true stream.pause() return for i of stream if util.isFunction(stream[i]) and util.isUndefined(this[i]) this[i] = (method) -> -> stream[method].apply stream, arguments (i) events = [ "error" "close" "destroy" "pause" "resume" ] events.forEach (ev) -> stream.on ev, self.emit.bind(self, ev) return self._read = (n) -> debug "wrapped _read", n if paused paused = false stream.resume() return self Readable._fromList = fromList
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. ReadableState = (options, stream) -> options = options or {} # object stream flag. Used to make read(n) ignore n and to # make all the buffer merging and length checks go away @objectMode = !!options.objectMode @objectMode = @objectMode or !!options.readableObjectMode if stream instanceof Stream.Duplex # the point at which it stops calling _read() to fill the buffer # Note: 0 is a valid value, means "don't call _read preemptively ever" hwm = options.highWaterMark defaultHwm = (if @objectMode then 16 else 16 * 1024) @highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm) # cast to ints. @highWaterMark = ~~@highWaterMark @buffer = [] @length = 0 @pipes = null @pipesCount = 0 @flowing = null @ended = false @endEmitted = false @reading = false # a flag to be able to tell if the onwrite cb is called immediately, # or on a later tick. We set this to true at first, because any # actions that shouldn't happen until "later" should generally also # not happen before the first write call. @sync = true # whenever we return null, then we set a flag to say # that we're awaiting a 'readable' event emission. @needReadable = false @emittedReadable = false @readableListening = false # Crypto is kind of old and crusty. Historically, its default string # encoding is 'binary' so we have to make this configurable. # Everything else in the universe uses 'utf8', though. @defaultEncoding = options.defaultEncoding or "utf8" # when piping, we only care about 'readable' events that happen # after read()ing all the bytes and not getting any pushback. @ranOut = false # the number of writers that are awaiting a drain event in .pipe()s @awaitDrain = 0 # if true, a maybeReadMore has been scheduled @readingMore = false @decoder = null @encoding = null if options.encoding StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @decoder = new StringDecoder(options.encoding) @encoding = options.encoding return Readable = (options) -> return new Readable(options) unless this instanceof Readable @_readableState = new ReadableState(options, this) # legacy @readable = true Stream.call this return # Manually shove something into the read() buffer. # This returns true if the highWaterMark has not been hit yet, # similar to how Writable.write() returns true if you should # write() some more. # Unshift should *always* be something directly out of read() readableAddChunk = (stream, state, chunk, encoding, addToFront) -> er = chunkInvalid(state, chunk) if er stream.emit "error", er else if chunk is null state.reading = false onEofChunk stream, state unless state.ended else if state.objectMode or chunk and chunk.length > 0 if state.ended and not addToFront e = new Error("stream.push() after EOF") stream.emit "error", e else if state.endEmitted and addToFront e = new Error("stream.unshift() after end event") stream.emit "error", e else chunk = state.decoder.write(chunk) if state.decoder and not addToFront and not encoding state.reading = false unless addToFront # if we want the data now, just emit it. if state.flowing and state.length is 0 and not state.sync stream.emit "data", chunk stream.read 0 else # update the buffer info. state.length += (if state.objectMode then 1 else chunk.length) if addToFront state.buffer.unshift chunk else state.buffer.push chunk emitReadable stream if state.needReadable maybeReadMore stream, state else state.reading = false unless addToFront needMoreData state # if it's past the high water mark, we can push in some more. # Also, if we have no data yet, we can stand some # more bytes. This is to work around cases where hwm=0, # such as the repl. Also, if the push() triggered a # readable event, and the user called read(largeNumber) such that # needReadable was set, then we ought to push more, so that another # 'readable' event will be triggered. needMoreData = (state) -> not state.ended and (state.needReadable or state.length < state.highWaterMark or state.length is 0) # backwards compatibility. # Don't raise the hwm > 128MB roundUpToNextPowerOf2 = (n) -> if n >= MAX_HWM n = MAX_HWM else # Get the next highest power of 2 n-- p = 1 while p < 32 n |= n >> p p <<= 1 n++ n howMuchToRead = (n, state) -> return 0 if state.length is 0 and state.ended return (if n is 0 then 0 else 1) if state.objectMode if util.isNull(n) or isNaN(n) # only flow one buffer at a time if state.flowing and state.buffer.length return state.buffer[0].length else return state.length return 0 if n <= 0 # If we're asking for more than the target buffer level, # then raise the water mark. Bump up to the next highest # power of 2, to prevent increasing it excessively in tiny # amounts. state.highWaterMark = roundUpToNextPowerOf2(n) if n > state.highWaterMark # don't have that much. return null, unless we've ended. if n > state.length unless state.ended state.needReadable = true return 0 else return state.length n # you can override either this method, or the async _read(n) below. # if we're doing read(0) to trigger a readable event, but we # already have a bunch of data in the buffer, then just trigger # the 'readable' event and move on. # if we've ended, and we're now clear, then finish it up. # All the actual chunk generation logic needs to be # *below* the call to _read. The reason is that in certain # synthetic stream cases, such as passthrough streams, _read # may be a completely synchronous operation which may change # the state of the read buffer, providing enough data when # before there was *not* enough. # # So, the steps are: # 1. Figure out what the state of things will be after we do # a read from the buffer. # # 2. If that resulting state will trigger a _read, then call _read. # Note that this may be asynchronous, or synchronous. Yes, it is # deeply ugly to write APIs this way, but that still doesn't mean # that the Readable class should behave improperly, as streams are # designed to be sync/async agnostic. # Take note if the _read call is sync or async (ie, if the read call # has returned yet), so that we know whether or not it's safe to emit # 'readable' etc. # # 3. Actually pull the requested chunks out of the buffer and return. # if we need a readable event, then we need to do some reading. # if we currently have less than the highWaterMark, then also read some # however, if we've ended, then there's no point, and if we're already # reading, then it's unnecessary. # if the length is currently zero, then we *need* a readable event. # call internal read method # If _read pushed data synchronously, then `reading` will be false, # and we need to re-evaluate how much data we can return to the user. # If we have nothing in the buffer, then we want to know # as soon as we *do* get something into the buffer. # If we tried to read() past the EOF, then emit end on the next tick. chunkInvalid = (state, chunk) -> er = null er = new TypeError("Invalid non-string/buffer chunk") if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode er onEofChunk = (stream, state) -> if state.decoder and not state.ended chunk = state.decoder.end() if chunk and chunk.length state.buffer.push chunk state.length += (if state.objectMode then 1 else chunk.length) state.ended = true # emit 'readable' now to make sure it gets picked up. emitReadable stream return # Don't emit readable right away in sync mode, because this can trigger # another read() call => stack overflow. This way, it might trigger # a nextTick recursion warning, but that's not so bad. emitReadable = (stream) -> state = stream._readableState state.needReadable = false unless state.emittedReadable debug "emitReadable", state.flowing state.emittedReadable = true if state.sync process.nextTick -> emitReadable_ stream return else emitReadable_ stream return emitReadable_ = (stream) -> debug "emit readable" stream.emit "readable" flow stream return # at this point, the user has presumably seen the 'readable' event, # and called read() to consume some data. that may have triggered # in turn another _read(n) call, in which case reading = true if # it's in progress. # However, if we're not ended, or reading, and the length < hwm, # then go ahead and try to read some more preemptively. maybeReadMore = (stream, state) -> unless state.readingMore state.readingMore = true process.nextTick -> maybeReadMore_ stream, state return return maybeReadMore_ = (stream, state) -> len = state.length while not state.reading and not state.flowing and not state.ended and state.length < state.highWaterMark debug "maybeReadMore read 0" stream.read 0 if len is state.length # didn't get any data, stop spinning. break else len = state.length state.readingMore = false return # abstract method. to be overridden in specific implementation classes. # call cb(er, data) where data is <= n in length. # for virtual (non-string, non-buffer) streams, "length" is somewhat # arbitrary, and perhaps not very meaningful. # when the dest drains, it reduces the awaitDrain counter # on the source. This would be more elegant with a .once() # handler in flow(), but adding and removing repeatedly is # too slow. # cleanup event handlers once the pipe is broken # if the reader is waiting for a drain event from this # specific writer, then it would cause it to never start # flowing again. # So, if this is awaiting a drain, then we just call it now. # If we don't know, then assume that we are waiting for one. # if the dest has an error, then stop piping into it. # however, don't suppress the throwing behavior for this. # This is a brutally ugly hack to make sure that our error handler # is attached before any userland ones. NEVER DO THIS. # Both close and finish should trigger unpipe, but only once. # tell the dest that it's being piped to # start the flow if it hasn't been started already. pipeOnDrain = (src) -> -> state = src._readableState debug "pipeOnDrain", state.awaitDrain state.awaitDrain-- if state.awaitDrain if state.awaitDrain is 0 and EE.listenerCount(src, "data") state.flowing = true flow src return # if we're not piping anywhere, then do nothing. # just one destination. most common case. # passed in one, but it's not the right one. # got a match. # slow case. multiple pipe destinations. # remove all. # try to find the right one. # set up data events if they are asked for # Ensure readable listeners eventually get something # If listening to data, and it has not explicitly been paused, # then call resume to start the flow of data on the next tick. # pause() and resume() are remnants of the legacy readable stream API # If the user uses them, then switch into old mode. resume = (stream, state) -> unless state.resumeScheduled state.resumeScheduled = true process.nextTick -> resume_ stream, state return return resume_ = (stream, state) -> unless state.reading debug "resume read 0" stream.read 0 state.resumeScheduled = false stream.emit "resume" flow stream stream.read 0 if state.flowing and not state.reading return flow = (stream) -> state = stream._readableState debug "flow", state.flowing if state.flowing loop chunk = stream.read() break unless null isnt chunk and state.flowing return # wrap an old-style stream as the async data source. # This is *not* part of the readable stream interface. # It is an ugly unfortunate mess of history. # don't skip over falsy values in objectMode #if (state.objectMode && util.isNullOrUndefined(chunk)) # proxy all the other methods. # important when wrapping filters and duplexes. # proxy certain important events. # when we try to consume some more bytes, simply unpause the # underlying stream. # exposed for testing purposes only. # Pluck off n bytes from an array of buffers. # Length is the combined lengths of all the buffers in the list. fromList = (n, state) -> list = state.buffer length = state.length stringMode = !!state.decoder objectMode = !!state.objectMode ret = undefined # nothing in the list, definitely empty. return null if list.length is 0 if length is 0 ret = null else if objectMode ret = list.shift() else if not n or n >= length # read it all, truncate the array. if stringMode ret = list.join("") else ret = Buffer.concat(list, length) list.length = 0 else # read just some of it. if n < list[0].length # just take a part of the first list item. # slice is the same for buffers and strings. buf = list[0] ret = buf.slice(0, n) list[0] = buf.slice(n) else if n is list[0].length # first list is a perfect match ret = list.shift() else # complex case. # we have enough to cover it, but it spans past the first buffer. if stringMode ret = "" else ret = new Buffer(n) c = 0 i = 0 l = list.length while i < l and c < n buf = list[0] cpy = Math.min(n - c, buf.length) if stringMode ret += buf.slice(0, cpy) else buf.copy ret, c, 0, cpy if cpy < buf.length list[0] = buf.slice(cpy) else list.shift() c += cpy i++ ret endReadable = (stream) -> state = stream._readableState # If we get here before consuming all the bytes, then that is a # bug in node. Should never happen. throw new Error("endReadable called on non-empty stream") if state.length > 0 unless state.endEmitted state.ended = true process.nextTick -> # Check that we didn't get one last unshift. if not state.endEmitted and state.length is 0 state.endEmitted = true stream.readable = false stream.emit "end" return return "use strict" module.exports = Readable Readable.ReadableState = ReadableState EE = require("events").EventEmitter Stream = require("stream") util = require("util") StringDecoder = undefined debug = util.debuglog("stream") util.inherits Readable, Stream Readable::push = (chunk, encoding) -> state = @_readableState if util.isString(chunk) and not state.objectMode encoding = encoding or state.defaultEncoding if encoding isnt state.encoding chunk = new Buffer(chunk, encoding) encoding = "" readableAddChunk this, state, chunk, encoding, false Readable::unshift = (chunk) -> state = @_readableState readableAddChunk this, state, chunk, "", true Readable::isPaused = -> @_readableState.flowing is false Readable::setEncoding = (enc) -> StringDecoder = require("string_decoder").StringDecoder unless StringDecoder @_readableState.decoder = new StringDecoder(enc) @_readableState.encoding = enc this MAX_HWM = 0x800000 Readable::read = (n) -> debug "read", n state = @_readableState nOrig = n state.emittedReadable = false if not util.isNumber(n) or n > 0 if n is 0 and state.needReadable and (state.length >= state.highWaterMark or state.ended) debug "read: emitReadable", state.length, state.ended if state.length is 0 and state.ended endReadable this else emitReadable this return null n = howMuchToRead(n, state) if n is 0 and state.ended endReadable this if state.length is 0 return null doRead = state.needReadable debug "need readable", doRead if state.length is 0 or state.length - n < state.highWaterMark doRead = true debug "length less than watermark", doRead if state.ended or state.reading doRead = false debug "reading or ended", doRead if doRead debug "do read" state.reading = true state.sync = true state.needReadable = true if state.length is 0 @_read state.highWaterMark state.sync = false n = howMuchToRead(nOrig, state) if doRead and not state.reading ret = undefined if n > 0 ret = fromList(n, state) else ret = null if util.isNull(ret) state.needReadable = true n = 0 state.length -= n state.needReadable = true if state.length is 0 and not state.ended endReadable this if nOrig isnt n and state.ended and state.length is 0 @emit "data", ret unless util.isNull(ret) ret Readable::_read = (n) -> @emit "error", new Error("not implemented") return Readable::pipe = (dest, pipeOpts) -> onunpipe = (readable) -> debug "onunpipe" cleanup() if readable is src return onend = -> debug "onend" dest.end() return cleanup = -> debug "cleanup" dest.removeListener "close", onclose dest.removeListener "finish", onfinish dest.removeListener "drain", ondrain dest.removeListener "error", onerror dest.removeListener "unpipe", onunpipe src.removeListener "end", onend src.removeListener "end", cleanup src.removeListener "data", ondata ondrain() if state.awaitDrain and (not dest._writableState or dest._writableState.needDrain) return ondata = (chunk) -> debug "ondata" ret = dest.write(chunk) if false is ret debug "false write response, pause", src._readableState.awaitDrain src._readableState.awaitDrain++ src.pause() return onerror = (er) -> debug "onerror", er unpipe() dest.removeListener "error", onerror dest.emit "error", er if EE.listenerCount(dest, "error") is 0 return onclose = -> dest.removeListener "finish", onfinish unpipe() return onfinish = -> debug "onfinish" dest.removeListener "close", onclose unpipe() return unpipe = -> debug "unpipe" src.unpipe dest return src = this state = @_readableState switch state.pipesCount when 0 state.pipes = dest when 1 state.pipes = [ state.pipes dest ] else state.pipes.push dest state.pipesCount += 1 debug "pipe count=%d opts=%j", state.pipesCount, pipeOpts doEnd = (not pipeOpts or pipeOpts.end isnt false) and dest isnt process.stdout and dest isnt process.stderr endFn = (if doEnd then onend else cleanup) if state.endEmitted process.nextTick endFn else src.once "end", endFn dest.on "unpipe", onunpipe ondrain = pipeOnDrain(src) dest.on "drain", ondrain src.on "data", ondata if not dest._events or not dest._events.error dest.on "error", onerror else if Array.isArray(dest._events.error) dest._events.error.unshift onerror else dest._events.error = [ onerror dest._events.error ] dest.once "close", onclose dest.once "finish", onfinish dest.emit "pipe", src unless state.flowing debug "pipe resume" src.resume() dest Readable::unpipe = (dest) -> state = @_readableState return this if state.pipesCount is 0 if state.pipesCount is 1 return this if dest and dest isnt state.pipes dest = state.pipes unless dest state.pipes = null state.pipesCount = 0 state.flowing = false dest.emit "unpipe", this if dest return this unless dest dests = state.pipes len = state.pipesCount state.pipes = null state.pipesCount = 0 state.flowing = false i = 0 while i < len dests[i].emit "unpipe", this i++ return this i = state.pipes.indexOf(dest) return this if i is -1 state.pipes.splice i, 1 state.pipesCount -= 1 state.pipes = state.pipes[0] if state.pipesCount is 1 dest.emit "unpipe", this this Readable::on = (ev, fn) -> res = Stream::on.call(this, ev, fn) @resume() if ev is "data" and false isnt @_readableState.flowing if ev is "readable" and @readable state = @_readableState unless state.readableListening state.readableListening = true state.emittedReadable = false state.needReadable = true unless state.reading self = this process.nextTick -> debug "readable nexttick read 0" self.read 0 return else emitReadable this, state if state.length res Readable::addListener = Readable::on Readable::resume = -> state = @_readableState unless state.flowing debug "resume" state.flowing = true resume this, state this Readable::pause = -> debug "call pause flowing=%j", @_readableState.flowing if false isnt @_readableState.flowing debug "pause" @_readableState.flowing = false @emit "pause" this Readable::wrap = (stream) -> state = @_readableState paused = false self = this stream.on "end", -> debug "wrapped end" if state.decoder and not state.ended chunk = state.decoder.end() self.push chunk if chunk and chunk.length self.push null return stream.on "data", (chunk) -> debug "wrapped data" chunk = state.decoder.write(chunk) if state.decoder if state.objectMode and (chunk is null or chunk is `undefined`) return else return if not state.objectMode and (not chunk or not chunk.length) ret = self.push(chunk) unless ret paused = true stream.pause() return for i of stream if util.isFunction(stream[i]) and util.isUndefined(this[i]) this[i] = (method) -> -> stream[method].apply stream, arguments (i) events = [ "error" "close" "destroy" "pause" "resume" ] events.forEach (ev) -> stream.on ev, self.emit.bind(self, ev) return self._read = (n) -> debug "wrapped _read", n if paused paused = false stream.resume() return self Readable._fromList = fromList
[ { "context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\nnew BackgroundLa", "end": 146, "score": 0.9987629652023315, "start": 142, "tag": "NAME", "value": "Tony" } ]
50sprites.framer/app.coffee
gremjua-forks/100daysofframer
26
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "Tony" twitter: "" description: "" new BackgroundLayer backgroundColor: "#211" vidPlayer = new Layer width: 300 height: 200 x: Align.center y: Align.center(-100) backgroundColor: "#efefef" clip: true horse = new Layer width: 2180 * 2.3 height: 89 * 2.3 parent: vidPlayer image: "images/horse.png" slider = new SliderComponent x: Align.center y: Align.center(70) min: 1 max: 16 slider.onValueChange -> value = Math.floor(slider.value) horse.x = 0 - horse.width / 16 * value
224291
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "<NAME>" twitter: "" description: "" new BackgroundLayer backgroundColor: "#211" vidPlayer = new Layer width: 300 height: 200 x: Align.center y: Align.center(-100) backgroundColor: "#efefef" clip: true horse = new Layer width: 2180 * 2.3 height: 89 * 2.3 parent: vidPlayer image: "images/horse.png" slider = new SliderComponent x: Align.center y: Align.center(70) min: 1 max: 16 slider.onValueChange -> value = Math.floor(slider.value) horse.x = 0 - horse.width / 16 * value
true
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "PI:NAME:<NAME>END_PI" twitter: "" description: "" new BackgroundLayer backgroundColor: "#211" vidPlayer = new Layer width: 300 height: 200 x: Align.center y: Align.center(-100) backgroundColor: "#efefef" clip: true horse = new Layer width: 2180 * 2.3 height: 89 * 2.3 parent: vidPlayer image: "images/horse.png" slider = new SliderComponent x: Align.center y: Align.center(70) min: 1 max: 16 slider.onValueChange -> value = Math.floor(slider.value) horse.x = 0 - horse.width / 16 * value
[ { "context": "ttp-monitor')\n\netcdPeers = (env.ETCDCTL_PEERS || \"127.0.0.1:2379\").split(',')\nserviceDiscoveryPath = \"/dit4c/", "end": 261, "score": 0.9997374415397644, "start": 252, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " alive: {}\n writeHipacheRecord = ()...
highcommand.coffee
dit4c/dit4c-cluster-manager
0
'use strict'; env = process.env url = require('url') etcdjs = require('etcdjs') liveCollection = require('etcd-live-collection') newNano = require('nano') _ = require("underscore") monitor = require('http-monitor') etcdPeers = (env.ETCDCTL_PEERS || "127.0.0.1:2379").split(',') serviceDiscoveryPath = "/dit4c/containers/dit4c_highcommand" domain = env.DIT4C_DOMAIN || 'resbaz.cloud.edu.au' etcd = etcdjs(etcdPeers) collection = liveCollection(etcd, serviceDiscoveryPath) loggerFor = (name) -> (msg) -> console.log("["+name+"] "+msg) serverName = (key) -> key.split('/').pop() restartMonitoring = do () -> data = monitors: [] alive: {} writeHipacheRecord = () -> key = "/dit4c/hipache/frontend:"+domain servers = (ip for ip, isUp of data.alive when isUp) record = [ domain ].concat("http://"+ip+":9000" for ip in servers) etcd.set key, JSON.stringify(record), (err) -> if (!err) # Log success console.log "Servers now: "+servers.join(', ') else # Retry write setTimeout(writeHipacheRecord, 5000) markAsAlive = (serverIP) -> data.alive[serverIP] = true loggerFor(serverIP)("UP") writeHipacheRecord() markAsDead = (serverIP) -> data.alive[serverIP] = false loggerFor(serverIP)("DOWN") writeHipacheRecord() startMonitor = (serverIP) -> m = monitor 'http://'+serverIP+':9000/health', retries: 1 interval: 5000 timeout: 15000 m.on 'error', (err) -> markAsDead(serverIP) m.on 'recovery', () -> markAsAlive(serverIP) markAsAlive(serverIP) stopMonitors = () -> # Destroy all monitors for monitor in data.monitors monitor.destroy() data.monitors = [] # Clear health status lookup data.alive = {} (serverIPs) -> stopMonitors() startMonitor(ip) for ip in serverIPs updateMonitoring = () -> servers = _.object([serverName(k), v] for k, v of collection.values()) console.log("Known servers: ") for name, addr of servers console.log(name+" → "+addr) restartMonitoring(addr for name, addr of servers) collection.on(event, updateMonitoring) for event in ['ready', 'action']
69968
'use strict'; env = process.env url = require('url') etcdjs = require('etcdjs') liveCollection = require('etcd-live-collection') newNano = require('nano') _ = require("underscore") monitor = require('http-monitor') etcdPeers = (env.ETCDCTL_PEERS || "127.0.0.1:2379").split(',') serviceDiscoveryPath = "/dit4c/containers/dit4c_highcommand" domain = env.DIT4C_DOMAIN || 'resbaz.cloud.edu.au' etcd = etcdjs(etcdPeers) collection = liveCollection(etcd, serviceDiscoveryPath) loggerFor = (name) -> (msg) -> console.log("["+name+"] "+msg) serverName = (key) -> key.split('/').pop() restartMonitoring = do () -> data = monitors: [] alive: {} writeHipacheRecord = () -> key = <KEY>:"+domain servers = (ip for ip, isUp of data.alive when isUp) record = [ domain ].concat("http://"+ip+":9000" for ip in servers) etcd.set key, JSON.stringify(record), (err) -> if (!err) # Log success console.log "Servers now: "+servers.join(', ') else # Retry write setTimeout(writeHipacheRecord, 5000) markAsAlive = (serverIP) -> data.alive[serverIP] = true loggerFor(serverIP)("UP") writeHipacheRecord() markAsDead = (serverIP) -> data.alive[serverIP] = false loggerFor(serverIP)("DOWN") writeHipacheRecord() startMonitor = (serverIP) -> m = monitor 'http://'+serverIP+':9000/health', retries: 1 interval: 5000 timeout: 15000 m.on 'error', (err) -> markAsDead(serverIP) m.on 'recovery', () -> markAsAlive(serverIP) markAsAlive(serverIP) stopMonitors = () -> # Destroy all monitors for monitor in data.monitors monitor.destroy() data.monitors = [] # Clear health status lookup data.alive = {} (serverIPs) -> stopMonitors() startMonitor(ip) for ip in serverIPs updateMonitoring = () -> servers = _.object([serverName(k), v] for k, v of collection.values()) console.log("Known servers: ") for name, addr of servers console.log(name+" → "+addr) restartMonitoring(addr for name, addr of servers) collection.on(event, updateMonitoring) for event in ['ready', 'action']
true
'use strict'; env = process.env url = require('url') etcdjs = require('etcdjs') liveCollection = require('etcd-live-collection') newNano = require('nano') _ = require("underscore") monitor = require('http-monitor') etcdPeers = (env.ETCDCTL_PEERS || "127.0.0.1:2379").split(',') serviceDiscoveryPath = "/dit4c/containers/dit4c_highcommand" domain = env.DIT4C_DOMAIN || 'resbaz.cloud.edu.au' etcd = etcdjs(etcdPeers) collection = liveCollection(etcd, serviceDiscoveryPath) loggerFor = (name) -> (msg) -> console.log("["+name+"] "+msg) serverName = (key) -> key.split('/').pop() restartMonitoring = do () -> data = monitors: [] alive: {} writeHipacheRecord = () -> key = PI:KEY:<KEY>END_PI:"+domain servers = (ip for ip, isUp of data.alive when isUp) record = [ domain ].concat("http://"+ip+":9000" for ip in servers) etcd.set key, JSON.stringify(record), (err) -> if (!err) # Log success console.log "Servers now: "+servers.join(', ') else # Retry write setTimeout(writeHipacheRecord, 5000) markAsAlive = (serverIP) -> data.alive[serverIP] = true loggerFor(serverIP)("UP") writeHipacheRecord() markAsDead = (serverIP) -> data.alive[serverIP] = false loggerFor(serverIP)("DOWN") writeHipacheRecord() startMonitor = (serverIP) -> m = monitor 'http://'+serverIP+':9000/health', retries: 1 interval: 5000 timeout: 15000 m.on 'error', (err) -> markAsDead(serverIP) m.on 'recovery', () -> markAsAlive(serverIP) markAsAlive(serverIP) stopMonitors = () -> # Destroy all monitors for monitor in data.monitors monitor.destroy() data.monitors = [] # Clear health status lookup data.alive = {} (serverIPs) -> stopMonitors() startMonitor(ip) for ip in serverIPs updateMonitoring = () -> servers = _.object([serverName(k), v] for k, v of collection.values()) console.log("Known servers: ") for name, addr of servers console.log(name+" → "+addr) restartMonitoring(addr for name, addr of servers) collection.on(event, updateMonitoring) for event in ['ready', 'action']
[ { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.", "end": 17, "score": 0.9373302459716797, "start": 16, "tag": "EMAIL", "value": "j" }, { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Per", "end": 25, ...
src/api/v0.1.coffee
yadutaf/Weathermap-archive
1
### # Copyright jtlebi.fr <admin@jtlebi.fr> and other 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. ### ### API: * GET /wm-api/group => get a list a groups for which we have archives * GET /wm-api/:groupname/maps => get a list of available maps for this group * GET /wm-api/:groupname/:mapname/dates => get list of archived days * GET /wm-api/:groupname/:mapname/:date/times => get list of archived times + their meta informations * GET /wm-api/*.png => get a given static PNG map * GET /wm/ => static app files ### Restify = require 'restify' Fs = require 'fs' version = '0.1.0b.1' module.exports = (Server, config) -> createStaticServer = require('../lib/staticServer') Server #actual controllers api = { getGroups: (req, res, next) -> Fs.parsedir config.weathermapsDir, (err, files) => if not files.directories res.send new Restify.ResourceNotFoundError("No groups were found") else res.send 200, files.directories next() getMaps: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No maps were found for group "+req.params.groupname) else res.send 200, files.directories next() getDates: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No dates were found for group "+req.params.groupname) else res.send 200, files.directories next() getTimes: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date, (err, files) => if files and files.files ret = {} files.files.forEach (file) => return if not file.endsWith ".png" time = file.slice 0, -4 ret[time] = { type: 'image' url: "/wm-api/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date+"/"+time+".png" } if ret != {} res.send 200, ret return next() res.send new Restify.ResourceNotFoundError("No times were found for group "+req.params.groupname+" at date "+req.params.date) next() getDefault: (req, res, next) -> res.statusCode = 301 res.setHeader 'Location', '/wm/index.html' res.end 'Redirecting to /wm/index.html' return } #server definition Server.get {path: '/', version: version}, api.getDefault Server.get {path: '/wm-api/groups', version: version}, api.getGroups Server.get {path: '/wm-api/:groupname/maps', version: version}, api.getMaps Server.get {path: '/wm-api/:groupname/:mapname/dates', version: version}, api.getDates Server.get {path: '/wm-api/:groupname/:mapname/:date/times', version: version}, api.getTimes #static files createStaticServer "application file", config.staticFilesDir, "wm", '', version createStaticServer "map", config.weathermapsDir, "wm-api", "png", version
20629
### # Copyright <EMAIL>tlebi.fr <<EMAIL>> and other 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. ### ### API: * GET /wm-api/group => get a list a groups for which we have archives * GET /wm-api/:groupname/maps => get a list of available maps for this group * GET /wm-api/:groupname/:mapname/dates => get list of archived days * GET /wm-api/:groupname/:mapname/:date/times => get list of archived times + their meta informations * GET /wm-api/*.png => get a given static PNG map * GET /wm/ => static app files ### Restify = require 'restify' Fs = require 'fs' version = '0.1.0b.1' module.exports = (Server, config) -> createStaticServer = require('../lib/staticServer') Server #actual controllers api = { getGroups: (req, res, next) -> Fs.parsedir config.weathermapsDir, (err, files) => if not files.directories res.send new Restify.ResourceNotFoundError("No groups were found") else res.send 200, files.directories next() getMaps: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No maps were found for group "+req.params.groupname) else res.send 200, files.directories next() getDates: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No dates were found for group "+req.params.groupname) else res.send 200, files.directories next() getTimes: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date, (err, files) => if files and files.files ret = {} files.files.forEach (file) => return if not file.endsWith ".png" time = file.slice 0, -4 ret[time] = { type: 'image' url: "/wm-api/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date+"/"+time+".png" } if ret != {} res.send 200, ret return next() res.send new Restify.ResourceNotFoundError("No times were found for group "+req.params.groupname+" at date "+req.params.date) next() getDefault: (req, res, next) -> res.statusCode = 301 res.setHeader 'Location', '/wm/index.html' res.end 'Redirecting to /wm/index.html' return } #server definition Server.get {path: '/', version: version}, api.getDefault Server.get {path: '/wm-api/groups', version: version}, api.getGroups Server.get {path: '/wm-api/:groupname/maps', version: version}, api.getMaps Server.get {path: '/wm-api/:groupname/:mapname/dates', version: version}, api.getDates Server.get {path: '/wm-api/:groupname/:mapname/:date/times', version: version}, api.getTimes #static files createStaticServer "application file", config.staticFilesDir, "wm", '', version createStaticServer "map", config.weathermapsDir, "wm-api", "png", version
true
### # Copyright PI:EMAIL:<EMAIL>END_PItlebi.fr <PI:EMAIL:<EMAIL>END_PI> and other 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. ### ### API: * GET /wm-api/group => get a list a groups for which we have archives * GET /wm-api/:groupname/maps => get a list of available maps for this group * GET /wm-api/:groupname/:mapname/dates => get list of archived days * GET /wm-api/:groupname/:mapname/:date/times => get list of archived times + their meta informations * GET /wm-api/*.png => get a given static PNG map * GET /wm/ => static app files ### Restify = require 'restify' Fs = require 'fs' version = '0.1.0b.1' module.exports = (Server, config) -> createStaticServer = require('../lib/staticServer') Server #actual controllers api = { getGroups: (req, res, next) -> Fs.parsedir config.weathermapsDir, (err, files) => if not files.directories res.send new Restify.ResourceNotFoundError("No groups were found") else res.send 200, files.directories next() getMaps: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No maps were found for group "+req.params.groupname) else res.send 200, files.directories next() getDates: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname, (err, files) => if not files or not files.directories res.send new Restify.ResourceNotFoundError("No dates were found for group "+req.params.groupname) else res.send 200, files.directories next() getTimes: (req, res, next) -> Fs.parsedir config.weathermapsDir+"/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date, (err, files) => if files and files.files ret = {} files.files.forEach (file) => return if not file.endsWith ".png" time = file.slice 0, -4 ret[time] = { type: 'image' url: "/wm-api/"+req.params.groupname+"/"+req.params.mapname+"/"+req.params.date+"/"+time+".png" } if ret != {} res.send 200, ret return next() res.send new Restify.ResourceNotFoundError("No times were found for group "+req.params.groupname+" at date "+req.params.date) next() getDefault: (req, res, next) -> res.statusCode = 301 res.setHeader 'Location', '/wm/index.html' res.end 'Redirecting to /wm/index.html' return } #server definition Server.get {path: '/', version: version}, api.getDefault Server.get {path: '/wm-api/groups', version: version}, api.getGroups Server.get {path: '/wm-api/:groupname/maps', version: version}, api.getMaps Server.get {path: '/wm-api/:groupname/:mapname/dates', version: version}, api.getDates Server.get {path: '/wm-api/:groupname/:mapname/:date/times', version: version}, api.getTimes #static files createStaticServer "application file", config.staticFilesDir, "wm", '', version createStaticServer "map", config.weathermapsDir, "wm-api", "png", version
[ { "context": "er = if currentUser\n currentUser.password = undefined\n currentUser\n else\n null\n res", "end": 234, "score": 0.997094988822937, "start": 225, "tag": "PASSWORD", "value": "undefined" } ]
routes/authRouter.coffee
jastribl/stir-server
0
express = require('express') passport = require('passport') module.exports = express.Router() .post '/getUserStatus', (req, res, next) -> currentUser = req.user user = if currentUser currentUser.password = undefined currentUser else null res.json({ loggedIn: req.isAuthenticated() user: user }) .post '/login', (req, res, next) -> passport.authenticate('login', (error, user, message) -> if error? res.sendStatus(500).json({ error: error }) else if not user res.sendStatus(403).json({ error: message }) else req.logIn user, (error) -> if error? res.sendStatus(500).json({ error: error }) else res.sendStatus(200) )(req, res, next) .post '/register', (req, res, next) -> passport.authenticate('register', (error, userCreated, message) -> if error? res.sendStatus(500).json({ error: error }) else if not userCreated res.sendStatus(409).json({ error: message }) else res.sendStatus(200).json({}) )(req, res, next) .get '/logout', (req, res) -> req.logout() res.sendStatus(200).json({})
56400
express = require('express') passport = require('passport') module.exports = express.Router() .post '/getUserStatus', (req, res, next) -> currentUser = req.user user = if currentUser currentUser.password = <PASSWORD> currentUser else null res.json({ loggedIn: req.isAuthenticated() user: user }) .post '/login', (req, res, next) -> passport.authenticate('login', (error, user, message) -> if error? res.sendStatus(500).json({ error: error }) else if not user res.sendStatus(403).json({ error: message }) else req.logIn user, (error) -> if error? res.sendStatus(500).json({ error: error }) else res.sendStatus(200) )(req, res, next) .post '/register', (req, res, next) -> passport.authenticate('register', (error, userCreated, message) -> if error? res.sendStatus(500).json({ error: error }) else if not userCreated res.sendStatus(409).json({ error: message }) else res.sendStatus(200).json({}) )(req, res, next) .get '/logout', (req, res) -> req.logout() res.sendStatus(200).json({})
true
express = require('express') passport = require('passport') module.exports = express.Router() .post '/getUserStatus', (req, res, next) -> currentUser = req.user user = if currentUser currentUser.password = PI:PASSWORD:<PASSWORD>END_PI currentUser else null res.json({ loggedIn: req.isAuthenticated() user: user }) .post '/login', (req, res, next) -> passport.authenticate('login', (error, user, message) -> if error? res.sendStatus(500).json({ error: error }) else if not user res.sendStatus(403).json({ error: message }) else req.logIn user, (error) -> if error? res.sendStatus(500).json({ error: error }) else res.sendStatus(200) )(req, res, next) .post '/register', (req, res, next) -> passport.authenticate('register', (error, userCreated, message) -> if error? res.sendStatus(500).json({ error: error }) else if not userCreated res.sendStatus(409).json({ error: message }) else res.sendStatus(200).json({}) )(req, res, next) .get '/logout', (req, res) -> req.logout() res.sendStatus(200).json({})
[ { "context": "\n modelKey: 'clientId'\n jsonKey: 'client_id'\n 'serverId': Attributes.ServerId\n querya", "end": 2401, "score": 0.9052734971046448, "start": 2399, "tag": "KEY", "value": "id" }, { "context": " modelKey: 'serverId'\n jsonKey: 'server_id'\n ...
packages/client-app/spec/fixtures/db-test-model.coffee
cnheider/nylas-mail
24,369
Model = require '../../src/flux/models/model' Category = require('../../src/flux/models/category').default Attributes = require('../../src/flux/attributes').default class TestModel extends Model @attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureBasic = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureWithAllAttributes = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'datetime': Attributes.DateTime queryable: true modelKey: 'datetime' 'string': Attributes.String queryable: true modelKey: 'string' jsonKey: 'string-json-key' 'boolean': Attributes.Boolean queryable: true modelKey: 'boolean' 'number': Attributes.Number queryable: true modelKey: 'number' 'other': Attributes.String modelKey: 'other' TestModel.configureWithCollectionAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' 'other': Attributes.String queryable: true, modelKey: 'other' 'categories': Attributes.Collection queryable: true, modelKey: 'categories' itemClass: Category, joinOnField: 'id', joinQueryableBy: ['other'], TestModel.configureWithJoinedDataAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.configureWithAdditionalSQLiteConfig = -> TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.additionalSQLiteConfig = setup: -> ['CREATE INDEX IF NOT EXISTS ThreadListIndex ON Thread(last_message_received_timestamp DESC, account_id, id)'] module.exports = TestModel
103612
Model = require '../../src/flux/models/model' Category = require('../../src/flux/models/category').default Attributes = require('../../src/flux/attributes').default class TestModel extends Model @attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureBasic = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureWithAllAttributes = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'datetime': Attributes.DateTime queryable: true modelKey: 'datetime' 'string': Attributes.String queryable: true modelKey: 'string' jsonKey: 'string-json-key' 'boolean': Attributes.Boolean queryable: true modelKey: 'boolean' 'number': Attributes.Number queryable: true modelKey: 'number' 'other': Attributes.String modelKey: 'other' TestModel.configureWithCollectionAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' 'other': Attributes.String queryable: true, modelKey: 'other' 'categories': Attributes.Collection queryable: true, modelKey: 'categories' itemClass: Category, joinOnField: 'id', joinQueryableBy: ['other'], TestModel.configureWithJoinedDataAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_<KEY>' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_<KEY>' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.configureWithAdditionalSQLiteConfig = -> TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.additionalSQLiteConfig = setup: -> ['CREATE INDEX IF NOT EXISTS ThreadListIndex ON Thread(last_message_received_timestamp DESC, account_id, id)'] module.exports = TestModel
true
Model = require '../../src/flux/models/model' Category = require('../../src/flux/models/category').default Attributes = require('../../src/flux/attributes').default class TestModel extends Model @attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureBasic = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' TestModel.configureWithAllAttributes = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'datetime': Attributes.DateTime queryable: true modelKey: 'datetime' 'string': Attributes.String queryable: true modelKey: 'string' jsonKey: 'string-json-key' 'boolean': Attributes.Boolean queryable: true modelKey: 'boolean' 'number': Attributes.Number queryable: true modelKey: 'number' 'other': Attributes.String modelKey: 'other' TestModel.configureWithCollectionAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_id' 'other': Attributes.String queryable: true, modelKey: 'other' 'categories': Attributes.Collection queryable: true, modelKey: 'categories' itemClass: Category, joinOnField: 'id', joinQueryableBy: ['other'], TestModel.configureWithJoinedDataAttribute = -> TestModel.additionalSQLiteConfig = undefined TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_PI:KEY:<KEY>END_PI' 'serverId': Attributes.ServerId queryable: true modelKey: 'serverId' jsonKey: 'server_PI:KEY:<KEY>END_PI' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.configureWithAdditionalSQLiteConfig = -> TestModel.attributes = 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'body': Attributes.JoinedData modelTable: 'TestModelBody' modelKey: 'body' TestModel.additionalSQLiteConfig = setup: -> ['CREATE INDEX IF NOT EXISTS ThreadListIndex ON Thread(last_message_received_timestamp DESC, account_id, id)'] module.exports = TestModel
[ { "context": "###\n Vibrant.js\n by Jari Zwarts\n\n Color algorithm class that finds variations on", "end": 33, "score": 0.9998916387557983, "start": 22, "tag": "NAME", "value": "Jari Zwarts" }, { "context": "ons on colors in an image.\n\n Credits\n --------\n Lokesh Dhakar (ht...
src/Vibrant.coffee
isabella232/vibrant.js
4
### Vibrant.js by Jari Zwarts Color algorithm class that finds variations on colors in an image. Credits -------- Lokesh Dhakar (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### window.Swatch = class Swatch hsl: undefined rgb: undefined population: 1 @yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = Vibrant.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> "#" + ((1 << 24) + (@rgb[0] << 16) + (@rgb[1] << 8) + @rgb[2]).toString(16).slice(1, 7); getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000 window.Vibrant = class Vibrant quantize: require('quantize') _swatches: [] TARGET_DARK_LUMA: 0.26 MAX_DARK_LUMA: 0.45 MIN_LIGHT_LUMA: 0.55 TARGET_LIGHT_LUMA: 0.74 MIN_NORMAL_LUMA: 0.3 TARGET_NORMAL_LUMA: 0.5 MAX_NORMAL_LUMA: 0.7 TARGET_MUTED_SATURATION: 0.3 MAX_MUTED_SATURATION: 0.4 TARGET_VIBRANT_SATURATION: 1 MIN_VIBRANT_SATURATION: 0.35 WEIGHT_SATURATION: 3 WEIGHT_LUMA: 6 WEIGHT_POPULATION: 1 VibrantSwatch: undefined MutedSwatch: undefined DarkVibrantSwatch: undefined DarkMutedSwatch: undefined LightVibrantSwatch: undefined LightMutedSwatch: undefined HighestPopulation: 0 constructor: (sourceImage, colorCount, quality) -> if typeof colorCount == 'undefined' colorCount = 64 if typeof quality == 'undefined' quality = 5 try image = new CanvasImage(sourceImage) imageData = image.getImageData() pixels = imageData.data pixelCount = image.getPixelCount() allPixels = [] i = 0 while i < pixelCount offset = i * 4 r = pixels[offset + 0] g = pixels[offset + 1] b = pixels[offset + 2] a = pixels[offset + 3] # If pixel is mostly opaque and not white if a >= 125 if not (r > 250 and g > 250 and b > 250) allPixels.push [r, g, b] i = i + quality cmap = @quantize allPixels, colorCount @_swatches = cmap.vboxes.map (vbox) => new Swatch vbox.color, vbox.vbox.count() @maxPopulation = @findMaxPopulation @generateVarationColors() @generateEmptySwatches() # Clean up finally if image image.removeCanvas() generateVarationColors: -> @VibrantSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @LightVibrantSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @DarkVibrantSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @MutedSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @LightMutedSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @DarkMutedSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); generateEmptySwatches: -> if @VibrantSwatch is undefined # If we do not have a vibrant color... if @DarkVibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @DarkVibrantSwatch.getHsl() hsl[2] = @TARGET_NORMAL_LUMA @VibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 if @DarkVibrantSwatch is undefined # If we do not have a vibrant color... if @VibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @VibrantSwatch.getHsl() hsl[2] = @TARGET_DARK_LUMA @DarkVibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 findMaxPopulation: -> population = 0 population = Math.max(population, swatch.getPopulation()) for swatch in @_swatches population findColorVariation: (targetLuma, minLuma, maxLuma, targetSaturation, minSaturation, maxSaturation) -> max = undefined maxValue = 0 for swatch in @_swatches sat = swatch.getHsl()[1]; luma = swatch.getHsl()[2] if sat >= minSaturation and sat <= maxSaturation and luma >= minLuma and luma <= maxLuma and not @isAlreadySelected(swatch) value = @createComparisonValue sat, targetSaturation, luma, targetLuma, swatch.getPopulation(), @HighestPopulation if max is undefined or value > maxValue max = swatch maxValue = value max createComparisonValue: (saturation, targetSaturation, luma, targetLuma, population, maxPopulation) -> @weightedMean( @invertDiff(saturation, targetSaturation), @WEIGHT_SATURATION, @invertDiff(luma, targetLuma), @WEIGHT_LUMA, population / maxPopulation, @WEIGHT_POPULATION ) invertDiff: (value, targetValue) -> 1 - Math.abs value - targetValue weightedMean: (values...) -> sum = 0 sumWeight = 0 i = 0 while i < values.length value = values[i] weight = values[i + 1] sum += value * weight sumWeight += weight i += 2 sum / sumWeight swatches: => Vibrant: @VibrantSwatch Muted: @MutedSwatch DarkVibrant: @DarkVibrantSwatch DarkMuted: @DarkMutedSwatch LightVibrant: @LightVibrantSwatch LightMuted: @LightMuted isAlreadySelected: (swatch) -> @VibrantSwatch is swatch or @DarkVibrantSwatch is swatch or @LightVibrantSwatch is swatch or @MutedSwatch is swatch or @DarkMutedSwatch is swatch or @LightMutedSwatch is swatch @rgbToHsl: (r, g, b) -> r /= 255 g /= 255 b /= 255 max = Math.max(r, g, b) min = Math.min(r, g, b) h = undefined s = undefined l = (max + min) / 2 if max == min h = s = 0 # achromatic else d = max - min s = if l > 0.5 then d / (2 - max - min) else d / (max + min) switch max when r h = (g - b) / d + (if g < b then 6 else 0) when g h = (b - r) / d + 2 when b h = (r - g) / d + 4 h /= 6 [h, s, l] @hslToRgb: (h, s, l) -> r = undefined g = undefined b = undefined hue2rgb = (p, q, t) -> if t < 0 t += 1 if t > 1 t -= 1 if t < 1 / 6 return p + (q - p) * 6 * t if t < 1 / 2 return q if t < 2 / 3 return p + (q - p) * (2 / 3 - t) * 6 p if s == 0 r = g = b = l # achromatic else q = if l < 0.5 then l * (1 + s) else l + s - (l * s) p = 2 * l - q r = hue2rgb(p, q, h + 1 / 3) g = hue2rgb(p, q, h) b = hue2rgb(p, q, h - (1 / 3)) [ r * 255 g * 255 b * 255 ] ### CanvasImage Class Class that wraps the html image element and canvas. It also simplifies some of the canvas context manipulation with a set of helper functions. Stolen from https://github.com/lokesh/color-thief ### window.CanvasImage = class CanvasImage constructor: (image) -> @canvas = document.createElement('canvas') @context = @canvas.getContext('2d') document.body.appendChild @canvas @width = @canvas.width = image.width @height = @canvas.height = image.height @context.drawImage image, 0, 0, @width, @height clear: -> @context.clearRect 0, 0, @width, @height update: (imageData) -> @context.putImageData imageData, 0, 0 getPixelCount: -> @width * @height getImageData: -> @context.getImageData 0, 0, @width, @height removeCanvas: -> @canvas.parentNode.removeChild @canvas
81288
### Vibrant.js by <NAME> Color algorithm class that finds variations on colors in an image. Credits -------- <NAME> (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### window.Swatch = class Swatch hsl: undefined rgb: undefined population: 1 @yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = Vibrant.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> "#" + ((1 << 24) + (@rgb[0] << 16) + (@rgb[1] << 8) + @rgb[2]).toString(16).slice(1, 7); getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000 window.Vibrant = class Vibrant quantize: require('quantize') _swatches: [] TARGET_DARK_LUMA: 0.26 MAX_DARK_LUMA: 0.45 MIN_LIGHT_LUMA: 0.55 TARGET_LIGHT_LUMA: 0.74 MIN_NORMAL_LUMA: 0.3 TARGET_NORMAL_LUMA: 0.5 MAX_NORMAL_LUMA: 0.7 TARGET_MUTED_SATURATION: 0.3 MAX_MUTED_SATURATION: 0.4 TARGET_VIBRANT_SATURATION: 1 MIN_VIBRANT_SATURATION: 0.35 WEIGHT_SATURATION: 3 WEIGHT_LUMA: 6 WEIGHT_POPULATION: 1 VibrantSwatch: undefined MutedSwatch: undefined DarkVibrantSwatch: undefined DarkMutedSwatch: undefined LightVibrantSwatch: undefined LightMutedSwatch: undefined HighestPopulation: 0 constructor: (sourceImage, colorCount, quality) -> if typeof colorCount == 'undefined' colorCount = 64 if typeof quality == 'undefined' quality = 5 try image = new CanvasImage(sourceImage) imageData = image.getImageData() pixels = imageData.data pixelCount = image.getPixelCount() allPixels = [] i = 0 while i < pixelCount offset = i * 4 r = pixels[offset + 0] g = pixels[offset + 1] b = pixels[offset + 2] a = pixels[offset + 3] # If pixel is mostly opaque and not white if a >= 125 if not (r > 250 and g > 250 and b > 250) allPixels.push [r, g, b] i = i + quality cmap = @quantize allPixels, colorCount @_swatches = cmap.vboxes.map (vbox) => new Swatch vbox.color, vbox.vbox.count() @maxPopulation = @findMaxPopulation @generateVarationColors() @generateEmptySwatches() # Clean up finally if image image.removeCanvas() generateVarationColors: -> @VibrantSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @LightVibrantSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @DarkVibrantSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @MutedSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @LightMutedSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @DarkMutedSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); generateEmptySwatches: -> if @VibrantSwatch is undefined # If we do not have a vibrant color... if @DarkVibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @DarkVibrantSwatch.getHsl() hsl[2] = @TARGET_NORMAL_LUMA @VibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 if @DarkVibrantSwatch is undefined # If we do not have a vibrant color... if @VibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @VibrantSwatch.getHsl() hsl[2] = @TARGET_DARK_LUMA @DarkVibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 findMaxPopulation: -> population = 0 population = Math.max(population, swatch.getPopulation()) for swatch in @_swatches population findColorVariation: (targetLuma, minLuma, maxLuma, targetSaturation, minSaturation, maxSaturation) -> max = undefined maxValue = 0 for swatch in @_swatches sat = swatch.getHsl()[1]; luma = swatch.getHsl()[2] if sat >= minSaturation and sat <= maxSaturation and luma >= minLuma and luma <= maxLuma and not @isAlreadySelected(swatch) value = @createComparisonValue sat, targetSaturation, luma, targetLuma, swatch.getPopulation(), @HighestPopulation if max is undefined or value > maxValue max = swatch maxValue = value max createComparisonValue: (saturation, targetSaturation, luma, targetLuma, population, maxPopulation) -> @weightedMean( @invertDiff(saturation, targetSaturation), @WEIGHT_SATURATION, @invertDiff(luma, targetLuma), @WEIGHT_LUMA, population / maxPopulation, @WEIGHT_POPULATION ) invertDiff: (value, targetValue) -> 1 - Math.abs value - targetValue weightedMean: (values...) -> sum = 0 sumWeight = 0 i = 0 while i < values.length value = values[i] weight = values[i + 1] sum += value * weight sumWeight += weight i += 2 sum / sumWeight swatches: => Vibrant: @VibrantSwatch Muted: @MutedSwatch DarkVibrant: @DarkVibrantSwatch DarkMuted: @DarkMutedSwatch LightVibrant: @LightVibrantSwatch LightMuted: @LightMuted isAlreadySelected: (swatch) -> @VibrantSwatch is swatch or @DarkVibrantSwatch is swatch or @LightVibrantSwatch is swatch or @MutedSwatch is swatch or @DarkMutedSwatch is swatch or @LightMutedSwatch is swatch @rgbToHsl: (r, g, b) -> r /= 255 g /= 255 b /= 255 max = Math.max(r, g, b) min = Math.min(r, g, b) h = undefined s = undefined l = (max + min) / 2 if max == min h = s = 0 # achromatic else d = max - min s = if l > 0.5 then d / (2 - max - min) else d / (max + min) switch max when r h = (g - b) / d + (if g < b then 6 else 0) when g h = (b - r) / d + 2 when b h = (r - g) / d + 4 h /= 6 [h, s, l] @hslToRgb: (h, s, l) -> r = undefined g = undefined b = undefined hue2rgb = (p, q, t) -> if t < 0 t += 1 if t > 1 t -= 1 if t < 1 / 6 return p + (q - p) * 6 * t if t < 1 / 2 return q if t < 2 / 3 return p + (q - p) * (2 / 3 - t) * 6 p if s == 0 r = g = b = l # achromatic else q = if l < 0.5 then l * (1 + s) else l + s - (l * s) p = 2 * l - q r = hue2rgb(p, q, h + 1 / 3) g = hue2rgb(p, q, h) b = hue2rgb(p, q, h - (1 / 3)) [ r * 255 g * 255 b * 255 ] ### CanvasImage Class Class that wraps the html image element and canvas. It also simplifies some of the canvas context manipulation with a set of helper functions. Stolen from https://github.com/lokesh/color-thief ### window.CanvasImage = class CanvasImage constructor: (image) -> @canvas = document.createElement('canvas') @context = @canvas.getContext('2d') document.body.appendChild @canvas @width = @canvas.width = image.width @height = @canvas.height = image.height @context.drawImage image, 0, 0, @width, @height clear: -> @context.clearRect 0, 0, @width, @height update: (imageData) -> @context.putImageData imageData, 0, 0 getPixelCount: -> @width * @height getImageData: -> @context.getImageData 0, 0, @width, @height removeCanvas: -> @canvas.parentNode.removeChild @canvas
true
### Vibrant.js by PI:NAME:<NAME>END_PI Color algorithm class that finds variations on colors in an image. Credits -------- PI:NAME:<NAME>END_PI (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### window.Swatch = class Swatch hsl: undefined rgb: undefined population: 1 @yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = Vibrant.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> "#" + ((1 << 24) + (@rgb[0] << 16) + (@rgb[1] << 8) + @rgb[2]).toString(16).slice(1, 7); getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000 window.Vibrant = class Vibrant quantize: require('quantize') _swatches: [] TARGET_DARK_LUMA: 0.26 MAX_DARK_LUMA: 0.45 MIN_LIGHT_LUMA: 0.55 TARGET_LIGHT_LUMA: 0.74 MIN_NORMAL_LUMA: 0.3 TARGET_NORMAL_LUMA: 0.5 MAX_NORMAL_LUMA: 0.7 TARGET_MUTED_SATURATION: 0.3 MAX_MUTED_SATURATION: 0.4 TARGET_VIBRANT_SATURATION: 1 MIN_VIBRANT_SATURATION: 0.35 WEIGHT_SATURATION: 3 WEIGHT_LUMA: 6 WEIGHT_POPULATION: 1 VibrantSwatch: undefined MutedSwatch: undefined DarkVibrantSwatch: undefined DarkMutedSwatch: undefined LightVibrantSwatch: undefined LightMutedSwatch: undefined HighestPopulation: 0 constructor: (sourceImage, colorCount, quality) -> if typeof colorCount == 'undefined' colorCount = 64 if typeof quality == 'undefined' quality = 5 try image = new CanvasImage(sourceImage) imageData = image.getImageData() pixels = imageData.data pixelCount = image.getPixelCount() allPixels = [] i = 0 while i < pixelCount offset = i * 4 r = pixels[offset + 0] g = pixels[offset + 1] b = pixels[offset + 2] a = pixels[offset + 3] # If pixel is mostly opaque and not white if a >= 125 if not (r > 250 and g > 250 and b > 250) allPixels.push [r, g, b] i = i + quality cmap = @quantize allPixels, colorCount @_swatches = cmap.vboxes.map (vbox) => new Swatch vbox.color, vbox.vbox.count() @maxPopulation = @findMaxPopulation @generateVarationColors() @generateEmptySwatches() # Clean up finally if image image.removeCanvas() generateVarationColors: -> @VibrantSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @LightVibrantSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @DarkVibrantSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_VIBRANT_SATURATION, @MIN_VIBRANT_SATURATION, 1); @MutedSwatch = @findColorVariation(@TARGET_NORMAL_LUMA, @MIN_NORMAL_LUMA, @MAX_NORMAL_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @LightMutedSwatch = @findColorVariation(@TARGET_LIGHT_LUMA, @MIN_LIGHT_LUMA, 1, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); @DarkMutedSwatch = @findColorVariation(@TARGET_DARK_LUMA, 0, @MAX_DARK_LUMA, @TARGET_MUTED_SATURATION, 0, @MAX_MUTED_SATURATION); generateEmptySwatches: -> if @VibrantSwatch is undefined # If we do not have a vibrant color... if @DarkVibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @DarkVibrantSwatch.getHsl() hsl[2] = @TARGET_NORMAL_LUMA @VibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 if @DarkVibrantSwatch is undefined # If we do not have a vibrant color... if @VibrantSwatch isnt undefined # ...but we do have a dark vibrant, generate the value by modifying the luma hsl = @VibrantSwatch.getHsl() hsl[2] = @TARGET_DARK_LUMA @DarkVibrantSwatch = new Swatch Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0 findMaxPopulation: -> population = 0 population = Math.max(population, swatch.getPopulation()) for swatch in @_swatches population findColorVariation: (targetLuma, minLuma, maxLuma, targetSaturation, minSaturation, maxSaturation) -> max = undefined maxValue = 0 for swatch in @_swatches sat = swatch.getHsl()[1]; luma = swatch.getHsl()[2] if sat >= minSaturation and sat <= maxSaturation and luma >= minLuma and luma <= maxLuma and not @isAlreadySelected(swatch) value = @createComparisonValue sat, targetSaturation, luma, targetLuma, swatch.getPopulation(), @HighestPopulation if max is undefined or value > maxValue max = swatch maxValue = value max createComparisonValue: (saturation, targetSaturation, luma, targetLuma, population, maxPopulation) -> @weightedMean( @invertDiff(saturation, targetSaturation), @WEIGHT_SATURATION, @invertDiff(luma, targetLuma), @WEIGHT_LUMA, population / maxPopulation, @WEIGHT_POPULATION ) invertDiff: (value, targetValue) -> 1 - Math.abs value - targetValue weightedMean: (values...) -> sum = 0 sumWeight = 0 i = 0 while i < values.length value = values[i] weight = values[i + 1] sum += value * weight sumWeight += weight i += 2 sum / sumWeight swatches: => Vibrant: @VibrantSwatch Muted: @MutedSwatch DarkVibrant: @DarkVibrantSwatch DarkMuted: @DarkMutedSwatch LightVibrant: @LightVibrantSwatch LightMuted: @LightMuted isAlreadySelected: (swatch) -> @VibrantSwatch is swatch or @DarkVibrantSwatch is swatch or @LightVibrantSwatch is swatch or @MutedSwatch is swatch or @DarkMutedSwatch is swatch or @LightMutedSwatch is swatch @rgbToHsl: (r, g, b) -> r /= 255 g /= 255 b /= 255 max = Math.max(r, g, b) min = Math.min(r, g, b) h = undefined s = undefined l = (max + min) / 2 if max == min h = s = 0 # achromatic else d = max - min s = if l > 0.5 then d / (2 - max - min) else d / (max + min) switch max when r h = (g - b) / d + (if g < b then 6 else 0) when g h = (b - r) / d + 2 when b h = (r - g) / d + 4 h /= 6 [h, s, l] @hslToRgb: (h, s, l) -> r = undefined g = undefined b = undefined hue2rgb = (p, q, t) -> if t < 0 t += 1 if t > 1 t -= 1 if t < 1 / 6 return p + (q - p) * 6 * t if t < 1 / 2 return q if t < 2 / 3 return p + (q - p) * (2 / 3 - t) * 6 p if s == 0 r = g = b = l # achromatic else q = if l < 0.5 then l * (1 + s) else l + s - (l * s) p = 2 * l - q r = hue2rgb(p, q, h + 1 / 3) g = hue2rgb(p, q, h) b = hue2rgb(p, q, h - (1 / 3)) [ r * 255 g * 255 b * 255 ] ### CanvasImage Class Class that wraps the html image element and canvas. It also simplifies some of the canvas context manipulation with a set of helper functions. Stolen from https://github.com/lokesh/color-thief ### window.CanvasImage = class CanvasImage constructor: (image) -> @canvas = document.createElement('canvas') @context = @canvas.getContext('2d') document.body.appendChild @canvas @width = @canvas.width = image.width @height = @canvas.height = image.height @context.drawImage image, 0, 0, @width, @height clear: -> @context.clearRect 0, 0, @width, @height update: (imageData) -> @context.putImageData imageData, 0, 0 getPixelCount: -> @width * @height getImageData: -> @context.getImageData 0, 0, @width, @height removeCanvas: -> @canvas.parentNode.removeChild @canvas
[ { "context": " return {\n time: new Date\n author: author\n content: content\n }\n\nexport newSystemL", "end": 172, "score": 0.48265957832336426, "start": 166, "tag": "NAME", "value": "author" }, { "context": "ne 'welcome to the chat'\nchat.append newChatLin...
js/views/chat.coffee
foxbot/watchr
0
import m from 'mithril' import { Commands } from '../commands.coffee' export newChatLine = (author, content) -> return { time: new Date author: author content: content } export newSystemLine = (content) -> return { system: true content: content } export chatView = (vnode) -> vnode.state.api.onChat = chat.append commands = new Commands vnode.state.api, chat commands.onChat = chat.append chatbox.api = vnode.state.api chatbox.commands = commands m '.pane-chat', [ m chat m chatbox m about ] chat = lines: [] scroll: true append: (line) -> chat.lines.push line m.redraw() view: -> # todo: perf, is this rerendering everything all the time? m '.chat.scroller', chat.lines.map (line) -> formatLine line onupdate: (vnode) -> if chat.scroll vnode.dom.scrollTop = vnode.dom.scrollHeight formatLine = (line) -> l = if line.system? then '.line.line-system' else '.line' return m l, [ m 'span.line-time', "#{line.time.getHours()}:#{line.time.getMinutes()}" unless line.system? m 'span.line-author', line.author unless line.system? m 'span.line-content', line.content ] chatbox = api: null commands: null view: -> m 'textarea.chatbox', { onkeypress: chatbox.onkey } onkey: (e) -> return unless e.which == 13 and !e.shiftkey input = e.target.value e.target.value = "" if input.startsWith '/' chatbox.commands.onCommand input else chatbox.api.sendChat input return false about = view: -> m '.about', [ m 'span.about-name', 'watchr' m 'span.about-ver', 'v0' m icons ] iconList = -> return [ m 'i', 't' m 'i', 'gh' m 'i', 'w' ] icons = view: -> m 'span.about-icons', iconList() # testing ### chat.append newSystemLine 'welcome to the chat' chat.append newChatLine 'anon', 'test 1' chat.append newChatLine 'anon2', 'test 2' ###
52355
import m from 'mithril' import { Commands } from '../commands.coffee' export newChatLine = (author, content) -> return { time: new Date author: <NAME> content: content } export newSystemLine = (content) -> return { system: true content: content } export chatView = (vnode) -> vnode.state.api.onChat = chat.append commands = new Commands vnode.state.api, chat commands.onChat = chat.append chatbox.api = vnode.state.api chatbox.commands = commands m '.pane-chat', [ m chat m chatbox m about ] chat = lines: [] scroll: true append: (line) -> chat.lines.push line m.redraw() view: -> # todo: perf, is this rerendering everything all the time? m '.chat.scroller', chat.lines.map (line) -> formatLine line onupdate: (vnode) -> if chat.scroll vnode.dom.scrollTop = vnode.dom.scrollHeight formatLine = (line) -> l = if line.system? then '.line.line-system' else '.line' return m l, [ m 'span.line-time', "#{line.time.getHours()}:#{line.time.getMinutes()}" unless line.system? m 'span.line-author', line.author unless line.system? m 'span.line-content', line.content ] chatbox = api: null commands: null view: -> m 'textarea.chatbox', { onkeypress: chatbox.onkey } onkey: (e) -> return unless e.which == 13 and !e.shiftkey input = e.target.value e.target.value = "" if input.startsWith '/' chatbox.commands.onCommand input else chatbox.api.sendChat input return false about = view: -> m '.about', [ m 'span.about-name', 'watchr' m 'span.about-ver', 'v0' m icons ] iconList = -> return [ m 'i', 't' m 'i', 'gh' m 'i', 'w' ] icons = view: -> m 'span.about-icons', iconList() # testing ### chat.append newSystemLine 'welcome to the chat' chat.append newChatLine 'anon', 'test 1' chat.append newChatLine 'anon2', 'test 2' ###
true
import m from 'mithril' import { Commands } from '../commands.coffee' export newChatLine = (author, content) -> return { time: new Date author: PI:NAME:<NAME>END_PI content: content } export newSystemLine = (content) -> return { system: true content: content } export chatView = (vnode) -> vnode.state.api.onChat = chat.append commands = new Commands vnode.state.api, chat commands.onChat = chat.append chatbox.api = vnode.state.api chatbox.commands = commands m '.pane-chat', [ m chat m chatbox m about ] chat = lines: [] scroll: true append: (line) -> chat.lines.push line m.redraw() view: -> # todo: perf, is this rerendering everything all the time? m '.chat.scroller', chat.lines.map (line) -> formatLine line onupdate: (vnode) -> if chat.scroll vnode.dom.scrollTop = vnode.dom.scrollHeight formatLine = (line) -> l = if line.system? then '.line.line-system' else '.line' return m l, [ m 'span.line-time', "#{line.time.getHours()}:#{line.time.getMinutes()}" unless line.system? m 'span.line-author', line.author unless line.system? m 'span.line-content', line.content ] chatbox = api: null commands: null view: -> m 'textarea.chatbox', { onkeypress: chatbox.onkey } onkey: (e) -> return unless e.which == 13 and !e.shiftkey input = e.target.value e.target.value = "" if input.startsWith '/' chatbox.commands.onCommand input else chatbox.api.sendChat input return false about = view: -> m '.about', [ m 'span.about-name', 'watchr' m 'span.about-ver', 'v0' m icons ] iconList = -> return [ m 'i', 't' m 'i', 'gh' m 'i', 'w' ] icons = view: -> m 'span.about-icons', iconList() # testing ### chat.append newSystemLine 'welcome to the chat' chat.append newChatLine 'anon', 'test 1' chat.append newChatLine 'anon2', 'test 2' ###
[ { "context": "\n\ncustomer1 = undefined\n\nCustomer.create\n name: 'John'\n.then (customer) ->\n Order.create\n customerI", "end": 236, "score": 0.9998298287391663, "start": 232, "tag": "NAME", "value": "John" }, { "context": "er.get true, console.log\n Customer.create name: 'M...
test/test3.coffee
BoLaMN/node-client
0
{ Customer Order Physician Patient Appointment Assembly Part Author Reader Picture } = require './test2' order1 = undefined order2 = undefined order3 = undefined customer1 = undefined Customer.create name: 'John' .then (customer) -> Order.create customerId: customer.id orderDate: new Date items: [ 'Book' ] .then (order) -> order1 = order order.customer.get console.log order.customer.get true, console.log Customer.create name: 'Mary' .then (customer2) -> order1.customer.update customer2 order1.customer.get console.log Order.create orderDate: new Date items: [ 'Phone' ] .then (order) -> order2 = order order.customer.create name: 'Smith' .then (customer2) -> console.log order2, customer2 order.save (err, order) -> order2 = order customer3 = order2.customer.build name: 'Tom' console.log 'Customer 3', customer3 order3 = undefined customer1 = undefined Customer.create name: 'Ray' .then (customer) -> customer1 = customer Order.create customerId: customer.id qty: 3 orderDate: new Date .then (order) -> order3 = order customer1.orders.create orderDate: new Date qty: 4 .then (order) -> customer1.orders.get(where: qty: 4).then (results) -> customer1.orders.findById(order3.id).then (results) -> customer1.orders.destroy order3.id physician1 = undefined physician2 = undefined patient1 = undefined patient2 = undefined patient3 = undefined Physician.create name: 'Dr John' .then (physician) -> physician1 = physician Physician.create name: 'Dr Smith' .then (physician) -> physician2 = physician Patient.create name: 'Mary' .then (patient) -> patient1 = patient Patient.create name: 'Ben' .then (patient) -> patient2 = patient Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient1.id .then (appt1) -> Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient2.id .then (appt2) -> physician1.patients.get { where: name: 'Mary' }, console.log patient1.physicians.get console.log patient3 = patient1.physicians.build(name: 'Dr X') console.log 'Physician 3: ', patient3, patient3.constructor.modelName patient1.physicians.create name: 'Dr X' .then (patient4) -> console.log 'Physician 4: ', patient4, patient4.constructor.modelName assembly1 = undefined Assembly.create name: 'car' .then (assembly) -> assembly1 = assembly Part.create partNumber: 'engine' .then (part) -> console.log assembly1 assembly1.parts.get .then (parts) -> console.log 'Parts: ', parts part3 = assembly1.parts.build(partNumber: 'door') console.log 'Part3: ', part3, part3.constructor.modelName assembly1.parts.create partNumber: 'door' .then (part4) -> console.log 'Part4: ', part4, part4.constructor.modelName Assembly.find include: 'parts' .then (assemblies) -> console.log 'Assemblies: ', assemblies
106763
{ Customer Order Physician Patient Appointment Assembly Part Author Reader Picture } = require './test2' order1 = undefined order2 = undefined order3 = undefined customer1 = undefined Customer.create name: '<NAME>' .then (customer) -> Order.create customerId: customer.id orderDate: new Date items: [ 'Book' ] .then (order) -> order1 = order order.customer.get console.log order.customer.get true, console.log Customer.create name: '<NAME>' .then (customer2) -> order1.customer.update customer2 order1.customer.get console.log Order.create orderDate: new Date items: [ 'Phone' ] .then (order) -> order2 = order order.customer.create name: '<NAME>' .then (customer2) -> console.log order2, customer2 order.save (err, order) -> order2 = order customer3 = order2.customer.build name: '<NAME>' console.log 'Customer 3', customer3 order3 = undefined customer1 = undefined Customer.create name: '<NAME>' .then (customer) -> customer1 = customer Order.create customerId: customer.id qty: 3 orderDate: new Date .then (order) -> order3 = order customer1.orders.create orderDate: new Date qty: 4 .then (order) -> customer1.orders.get(where: qty: 4).then (results) -> customer1.orders.findById(order3.id).then (results) -> customer1.orders.destroy order3.id physician1 = undefined physician2 = undefined patient1 = undefined patient2 = undefined patient3 = undefined Physician.create name: '<NAME> <NAME>' .then (physician) -> physician1 = physician Physician.create name: '<NAME> <NAME>' .then (physician) -> physician2 = physician Patient.create name: '<NAME>' .then (patient) -> patient1 = patient Patient.create name: '<NAME>' .then (patient) -> patient2 = patient Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient1.id .then (appt1) -> Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient2.id .then (appt2) -> physician1.patients.get { where: name: '<NAME>' }, console.log patient1.physicians.get console.log patient3 = patient1.physicians.build(name: 'Dr X') console.log 'Physician 3: ', patient3, patient3.constructor.modelName patient1.physicians.create name: 'Dr X' .then (patient4) -> console.log 'Physician 4: ', patient4, patient4.constructor.modelName assembly1 = undefined Assembly.create name: 'car' .then (assembly) -> assembly1 = assembly Part.create partNumber: 'engine' .then (part) -> console.log assembly1 assembly1.parts.get .then (parts) -> console.log 'Parts: ', parts part3 = assembly1.parts.build(partNumber: 'door') console.log 'Part3: ', part3, part3.constructor.modelName assembly1.parts.create partNumber: 'door' .then (part4) -> console.log 'Part4: ', part4, part4.constructor.modelName Assembly.find include: 'parts' .then (assemblies) -> console.log 'Assemblies: ', assemblies
true
{ Customer Order Physician Patient Appointment Assembly Part Author Reader Picture } = require './test2' order1 = undefined order2 = undefined order3 = undefined customer1 = undefined Customer.create name: 'PI:NAME:<NAME>END_PI' .then (customer) -> Order.create customerId: customer.id orderDate: new Date items: [ 'Book' ] .then (order) -> order1 = order order.customer.get console.log order.customer.get true, console.log Customer.create name: 'PI:NAME:<NAME>END_PI' .then (customer2) -> order1.customer.update customer2 order1.customer.get console.log Order.create orderDate: new Date items: [ 'Phone' ] .then (order) -> order2 = order order.customer.create name: 'PI:NAME:<NAME>END_PI' .then (customer2) -> console.log order2, customer2 order.save (err, order) -> order2 = order customer3 = order2.customer.build name: 'PI:NAME:<NAME>END_PI' console.log 'Customer 3', customer3 order3 = undefined customer1 = undefined Customer.create name: 'PI:NAME:<NAME>END_PI' .then (customer) -> customer1 = customer Order.create customerId: customer.id qty: 3 orderDate: new Date .then (order) -> order3 = order customer1.orders.create orderDate: new Date qty: 4 .then (order) -> customer1.orders.get(where: qty: 4).then (results) -> customer1.orders.findById(order3.id).then (results) -> customer1.orders.destroy order3.id physician1 = undefined physician2 = undefined patient1 = undefined patient2 = undefined patient3 = undefined Physician.create name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' .then (physician) -> physician1 = physician Physician.create name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' .then (physician) -> physician2 = physician Patient.create name: 'PI:NAME:<NAME>END_PI' .then (patient) -> patient1 = patient Patient.create name: 'PI:NAME:<NAME>END_PI' .then (patient) -> patient2 = patient Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient1.id .then (appt1) -> Appointment.create appointmentDate: new Date physicianId: physician1.id patientId: patient2.id .then (appt2) -> physician1.patients.get { where: name: 'PI:NAME:<NAME>END_PI' }, console.log patient1.physicians.get console.log patient3 = patient1.physicians.build(name: 'Dr X') console.log 'Physician 3: ', patient3, patient3.constructor.modelName patient1.physicians.create name: 'Dr X' .then (patient4) -> console.log 'Physician 4: ', patient4, patient4.constructor.modelName assembly1 = undefined Assembly.create name: 'car' .then (assembly) -> assembly1 = assembly Part.create partNumber: 'engine' .then (part) -> console.log assembly1 assembly1.parts.get .then (parts) -> console.log 'Parts: ', parts part3 = assembly1.parts.build(partNumber: 'door') console.log 'Part3: ', part3, part3.constructor.modelName assembly1.parts.create partNumber: 'door' .then (part4) -> console.log 'Part4: ', part4, part4.constructor.modelName Assembly.find include: 'parts' .then (assemblies) -> console.log 'Assemblies: ', assemblies
[ { "context": "Gutter2 = new Gutter(mockGutterContainer, {name: 'second', priority: -100})\n testState = buildTestSta", "end": 8346, "score": 0.8542275428771973, "start": 8340, "tag": "NAME", "value": "second" } ]
spec/gutter-container-component-spec.coffee
modestlearner/atom
0
Gutter = require '../src/gutter' GutterContainerComponent = require '../src/gutter-container-component' DOMElementPool = require '../src/dom-element-pool' describe "GutterContainerComponent", -> [gutterContainerComponent] = [] mockGutterContainer = {} buildTestState = (gutters) -> styles = scrollHeight: 100 scrollTop: 10 backgroundColor: 'black' mockTestState = {gutters: []} for gutter in gutters if gutter.name is 'line-number' content = {maxLineNumberDigits: 10, lineNumbers: {}} else content = {} mockTestState.gutters.push({gutter, styles, content, visible: gutter.visible}) mockTestState beforeEach -> domElementPool = new DOMElementPool mockEditor = {} mockMouseDown = -> gutterContainerComponent = new GutterContainerComponent({editor: mockEditor, onMouseDown: mockMouseDown, domElementPool, views: atom.views}) it "creates a DOM node with no child gutter nodes when it is initialized", -> expect(gutterContainerComponent.getDomNode() instanceof HTMLElement).toBe true expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with state that contains a new line-number gutter", -> it "adds a LineNumberGutterComponent to its children", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedLineNumbersNode = expectedGutterNode.children.item(0) expect(expectedLineNumbersNode.classList.contains('line-numbers')).toBe true expect(gutterContainerComponent.getLineNumberGutterComponent().getDomNode()).toBe expectedGutterNode describe "when updated with state that contains a new custom gutter", -> it "adds a CustomGutterComponent to its children", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedCustomDecorationsNode = expectedGutterNode.children.item(0) expect(expectedCustomDecorationsNode.classList.contains('custom-decorations')).toBe true describe "when updated with state that contains a new gutter that is not visible", -> it "creates the gutter view but hides it, and unhides it when it is later updated to be visible", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom', visible: false}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe 'none' customGutter.show() testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe '' describe "when updated with a gutter that already exists", -> it "reuses the existing gutter view, instead of recreating it", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expect(gutterContainerComponent.getDomNode().children.item(0)).toBe expectedCustomGutterNode it "removes a gutter from the DOM if it does not appear in the latest state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 testState = buildTestState([]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with multiple gutters", -> it "positions (and repositions) the gutters to match the order they appear in each state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) customGutter1 = new Gutter(mockGutterContainer, {name: 'custom', priority: -100}) testState = buildTestState([customGutter1, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 2 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe customGutter1.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(1) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Add a gutter. customGutter2 = new Gutter(mockGutterContainer, {name: 'custom2', priority: -10}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(2) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Hide one gutter, reposition one gutter, remove one gutter; and add a new gutter. customGutter2.hide() customGutter3 = new Gutter(mockGutterContainer, {name: 'custom3', priority: 100}) testState = buildTestState([customGutter2, customGutter1, customGutter3]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expect(expectedCustomGutterNode2.style.display).toBe 'none' expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode3 = gutterContainerComponent.getDomNode().children.item(2) expect(expectedCustomGutterNode3).toBe customGutter3.getElement() it "reorders correctly when prepending multiple gutters at once", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe lineNumberGutter.getElement() # Prepend two gutters at once customGutter1 = new Gutter(mockGutterContainer, {name: 'first', priority: -200}) customGutter2 = new Gutter(mockGutterContainer, {name: 'second', priority: -100}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement()
23953
Gutter = require '../src/gutter' GutterContainerComponent = require '../src/gutter-container-component' DOMElementPool = require '../src/dom-element-pool' describe "GutterContainerComponent", -> [gutterContainerComponent] = [] mockGutterContainer = {} buildTestState = (gutters) -> styles = scrollHeight: 100 scrollTop: 10 backgroundColor: 'black' mockTestState = {gutters: []} for gutter in gutters if gutter.name is 'line-number' content = {maxLineNumberDigits: 10, lineNumbers: {}} else content = {} mockTestState.gutters.push({gutter, styles, content, visible: gutter.visible}) mockTestState beforeEach -> domElementPool = new DOMElementPool mockEditor = {} mockMouseDown = -> gutterContainerComponent = new GutterContainerComponent({editor: mockEditor, onMouseDown: mockMouseDown, domElementPool, views: atom.views}) it "creates a DOM node with no child gutter nodes when it is initialized", -> expect(gutterContainerComponent.getDomNode() instanceof HTMLElement).toBe true expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with state that contains a new line-number gutter", -> it "adds a LineNumberGutterComponent to its children", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedLineNumbersNode = expectedGutterNode.children.item(0) expect(expectedLineNumbersNode.classList.contains('line-numbers')).toBe true expect(gutterContainerComponent.getLineNumberGutterComponent().getDomNode()).toBe expectedGutterNode describe "when updated with state that contains a new custom gutter", -> it "adds a CustomGutterComponent to its children", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedCustomDecorationsNode = expectedGutterNode.children.item(0) expect(expectedCustomDecorationsNode.classList.contains('custom-decorations')).toBe true describe "when updated with state that contains a new gutter that is not visible", -> it "creates the gutter view but hides it, and unhides it when it is later updated to be visible", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom', visible: false}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe 'none' customGutter.show() testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe '' describe "when updated with a gutter that already exists", -> it "reuses the existing gutter view, instead of recreating it", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expect(gutterContainerComponent.getDomNode().children.item(0)).toBe expectedCustomGutterNode it "removes a gutter from the DOM if it does not appear in the latest state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 testState = buildTestState([]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with multiple gutters", -> it "positions (and repositions) the gutters to match the order they appear in each state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) customGutter1 = new Gutter(mockGutterContainer, {name: 'custom', priority: -100}) testState = buildTestState([customGutter1, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 2 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe customGutter1.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(1) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Add a gutter. customGutter2 = new Gutter(mockGutterContainer, {name: 'custom2', priority: -10}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(2) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Hide one gutter, reposition one gutter, remove one gutter; and add a new gutter. customGutter2.hide() customGutter3 = new Gutter(mockGutterContainer, {name: 'custom3', priority: 100}) testState = buildTestState([customGutter2, customGutter1, customGutter3]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expect(expectedCustomGutterNode2.style.display).toBe 'none' expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode3 = gutterContainerComponent.getDomNode().children.item(2) expect(expectedCustomGutterNode3).toBe customGutter3.getElement() it "reorders correctly when prepending multiple gutters at once", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe lineNumberGutter.getElement() # Prepend two gutters at once customGutter1 = new Gutter(mockGutterContainer, {name: 'first', priority: -200}) customGutter2 = new Gutter(mockGutterContainer, {name: '<NAME>', priority: -100}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement()
true
Gutter = require '../src/gutter' GutterContainerComponent = require '../src/gutter-container-component' DOMElementPool = require '../src/dom-element-pool' describe "GutterContainerComponent", -> [gutterContainerComponent] = [] mockGutterContainer = {} buildTestState = (gutters) -> styles = scrollHeight: 100 scrollTop: 10 backgroundColor: 'black' mockTestState = {gutters: []} for gutter in gutters if gutter.name is 'line-number' content = {maxLineNumberDigits: 10, lineNumbers: {}} else content = {} mockTestState.gutters.push({gutter, styles, content, visible: gutter.visible}) mockTestState beforeEach -> domElementPool = new DOMElementPool mockEditor = {} mockMouseDown = -> gutterContainerComponent = new GutterContainerComponent({editor: mockEditor, onMouseDown: mockMouseDown, domElementPool, views: atom.views}) it "creates a DOM node with no child gutter nodes when it is initialized", -> expect(gutterContainerComponent.getDomNode() instanceof HTMLElement).toBe true expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with state that contains a new line-number gutter", -> it "adds a LineNumberGutterComponent to its children", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedLineNumbersNode = expectedGutterNode.children.item(0) expect(expectedLineNumbersNode.classList.contains('line-numbers')).toBe true expect(gutterContainerComponent.getLineNumberGutterComponent().getDomNode()).toBe expectedGutterNode describe "when updated with state that contains a new custom gutter", -> it "adds a CustomGutterComponent to its children", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedGutterNode.classList.contains('gutter')).toBe true expectedCustomDecorationsNode = expectedGutterNode.children.item(0) expect(expectedCustomDecorationsNode.classList.contains('custom-decorations')).toBe true describe "when updated with state that contains a new gutter that is not visible", -> it "creates the gutter view but hides it, and unhides it when it is later updated to be visible", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom', visible: false}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe 'none' customGutter.show() testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode.style.display).toBe '' describe "when updated with a gutter that already exists", -> it "reuses the existing gutter view, instead of recreating it", -> customGutter = new Gutter(mockGutterContainer, {name: 'custom'}) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) testState = buildTestState([customGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expect(gutterContainerComponent.getDomNode().children.item(0)).toBe expectedCustomGutterNode it "removes a gutter from the DOM if it does not appear in the latest state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 testState = buildTestState([]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 0 describe "when updated with multiple gutters", -> it "positions (and repositions) the gutters to match the order they appear in each state update", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) customGutter1 = new Gutter(mockGutterContainer, {name: 'custom', priority: -100}) testState = buildTestState([customGutter1, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 2 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe customGutter1.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(1) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Add a gutter. customGutter2 = new Gutter(mockGutterContainer, {name: 'custom2', priority: -10}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expectedLineNumbersNode = gutterContainerComponent.getDomNode().children.item(2) expect(expectedLineNumbersNode).toBe lineNumberGutter.getElement() # Hide one gutter, reposition one gutter, remove one gutter; and add a new gutter. customGutter2.hide() customGutter3 = new Gutter(mockGutterContainer, {name: 'custom3', priority: 100}) testState = buildTestState([customGutter2, customGutter1, customGutter3]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode2).toBe customGutter2.getElement() expect(expectedCustomGutterNode2.style.display).toBe 'none' expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode3 = gutterContainerComponent.getDomNode().children.item(2) expect(expectedCustomGutterNode3).toBe customGutter3.getElement() it "reorders correctly when prepending multiple gutters at once", -> lineNumberGutter = new Gutter(mockGutterContainer, {name: 'line-number'}) testState = buildTestState([lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 1 expectedCustomGutterNode = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode).toBe lineNumberGutter.getElement() # Prepend two gutters at once customGutter1 = new Gutter(mockGutterContainer, {name: 'first', priority: -200}) customGutter2 = new Gutter(mockGutterContainer, {name: 'PI:NAME:<NAME>END_PI', priority: -100}) testState = buildTestState([customGutter1, customGutter2, lineNumberGutter]) gutterContainerComponent.updateSync(testState) expect(gutterContainerComponent.getDomNode().children.length).toBe 3 expectedCustomGutterNode1 = gutterContainerComponent.getDomNode().children.item(0) expect(expectedCustomGutterNode1).toBe customGutter1.getElement() expectedCustomGutterNode2 = gutterContainerComponent.getDomNode().children.item(1) expect(expectedCustomGutterNode2).toBe customGutter2.getElement()
[ { "context": "quire('../crypto/secure_random')\n\nPROFILES_KEY = \"profiles\"\nCONFIG_KEY = \"config\"\nSALT_KEY = \"salt\"\n\nget = (", "end": 142, "score": 0.9494214057922363, "start": 134, "tag": "KEY", "value": "profiles" }, { "context": "random')\n\nPROFILES_KEY = \"profiles\"\n...
src/js/lib/secure_store/storage.coffee
obi1kenobi/jester
2
logger = require('../util/logging').logger(['lib', 'sstore', 'storage']) random = require('../crypto/secure_random') PROFILES_KEY = "profiles" CONFIG_KEY = "config" SALT_KEY = "salt" get = (key) -> keyString = JSON.stringify({key}) val = localStorage.getItem(keyString) if val?.length > 0 return JSON.parse(val).val else return null set = (key, val) -> keyString = JSON.stringify({key}) valString = JSON.stringify({val}) localStorage.setItem(keyString, valString) Storage = getSalt: () -> salt = get(SALT_KEY) if !salt? salt = random.getRandomSalt() set(SALT_KEY, salt) return salt getProfileNames: () -> profiles = get(PROFILES_KEY) if profiles? return Object.keys(profiles) else return [] getProfile: (profile) -> return get(PROFILES_KEY)?[profile] setProfile: (profile, iv, authTag, publicData, ciphertext) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} profiles[profile] = {iv, authTag, publicData, ciphertext} set(PROFILES_KEY, profiles) removeProfile: (profile) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} if profiles[profile]? delete profiles[profile] set(PROFILES_KEY, profiles) getConfig: () -> return get(CONFIG_KEY) setConfig: (iv, authTag, ciphertext) -> return set(CONFIG_KEY, {iv, authTag, ciphertext}) module.exports = Storage
187748
logger = require('../util/logging').logger(['lib', 'sstore', 'storage']) random = require('../crypto/secure_random') PROFILES_KEY = "<KEY>" CONFIG_KEY = "<KEY>" SALT_KEY = "<KEY>" get = (key) -> keyString = JSON.stringify({key}) val = localStorage.getItem(keyString) if val?.length > 0 return JSON.parse(val).val else return null set = (key, val) -> keyString = JSON.stringify({key}) valString = JSON.stringify({val}) localStorage.setItem(keyString, valString) Storage = getSalt: () -> salt = get(SALT_KEY) if !salt? salt = random.getRandomSalt() set(SALT_KEY, salt) return salt getProfileNames: () -> profiles = get(PROFILES_KEY) if profiles? return Object.keys(profiles) else return [] getProfile: (profile) -> return get(PROFILES_KEY)?[profile] setProfile: (profile, iv, authTag, publicData, ciphertext) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} profiles[profile] = {iv, authTag, publicData, ciphertext} set(PROFILES_KEY, profiles) removeProfile: (profile) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} if profiles[profile]? delete profiles[profile] set(PROFILES_KEY, profiles) getConfig: () -> return get(CONFIG_KEY) setConfig: (iv, authTag, ciphertext) -> return set(CONFIG_KEY, {iv, authTag, ciphertext}) module.exports = Storage
true
logger = require('../util/logging').logger(['lib', 'sstore', 'storage']) random = require('../crypto/secure_random') PROFILES_KEY = "PI:KEY:<KEY>END_PI" CONFIG_KEY = "PI:KEY:<KEY>END_PI" SALT_KEY = "PI:KEY:<KEY>END_PI" get = (key) -> keyString = JSON.stringify({key}) val = localStorage.getItem(keyString) if val?.length > 0 return JSON.parse(val).val else return null set = (key, val) -> keyString = JSON.stringify({key}) valString = JSON.stringify({val}) localStorage.setItem(keyString, valString) Storage = getSalt: () -> salt = get(SALT_KEY) if !salt? salt = random.getRandomSalt() set(SALT_KEY, salt) return salt getProfileNames: () -> profiles = get(PROFILES_KEY) if profiles? return Object.keys(profiles) else return [] getProfile: (profile) -> return get(PROFILES_KEY)?[profile] setProfile: (profile, iv, authTag, publicData, ciphertext) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} profiles[profile] = {iv, authTag, publicData, ciphertext} set(PROFILES_KEY, profiles) removeProfile: (profile) -> profiles = get(PROFILES_KEY) if !profiles? profiles = {} if profiles[profile]? delete profiles[profile] set(PROFILES_KEY, profiles) getConfig: () -> return get(CONFIG_KEY) setConfig: (iv, authTag, ciphertext) -> return set(CONFIG_KEY, {iv, authTag, ciphertext}) module.exports = Storage
[ { "context": "\n properties:\n NAME:\n 'Test'\n on: (obj) ->\n mouseover = obj.mouseover", "end": 640, "score": 0.8976950645446777, "start": 636, "tag": "NAME", "value": "Test" }, { "context": "S06005\"\n LSAD: \"County\"\n NAME: \...
spec/javascripts/jasmine_specs/mapControllerSpec.js.coffee
EdsonGermano/castos-public
0
#= require application #= require jquery #= require jquery_ujs #= require d3 #= require bootstrap-sprockets #= require mapbox.js #= require jasmine-jquery #= require angular #= require angular-resource #= require angular-sanitize #= require angular-mocks describe 'mapController', -> $scope = {} $rootScope = {} controller = {} $httpBackend = {} opacity = 0 fillColor = 'blue' spyEvent = {} mouseover = null mouseout = null click = null layerEl = target: setStyle: (obj) -> opacity = obj.opacity fillColor = obj.fillColor feature: properties: NAME: 'Test' on: (obj) -> mouseover = obj.mouseover mouseout = obj.mouseout click = obj.click beforeEach( -> module 'debtwatch' fixture.set('<div class="container"><div id="map"></div></div>') ) beforeEach inject((_$controller_, $injector, $rootScope) -> $controller = _$controller_ $scope = $injector.get('$rootScope').$new() $rootScope = $injector.get('$rootScope').$new() $httpBackend = $injector.get('$httpBackend') $httpBackend.when('GET', 'https://data.debtwatch.treasurer.ca.gov/api/assets/5F68F702-28B2-45D1-AF0A-D4C455A565F3?ca-counties-20m.geo.json') .respond([[{type: "FeatureCollection", features: [ geometry: { "type": "Point", "coordinates": [ -105.01621, 39.57422 ] } properties: CENSUSAREA: 594.583 COUNTY: "005" GEO_ID: "0500000US06005" LSAD: "County" NAME: "Amador" STATE: "06" ]}], "foo", "bar", "baz"] ); controller = $controller('mapController', $scope: $scope, map: map, $rootScope: $rootScope) ) describe 'init', -> it 'sets appropriate variables', -> expect($scope.activeCounty).toEqual({}) expect($scope.defaultLatLong).toEqual([37.2, -119.7]) expect($scope.defaultZoom).toBe(6) expect($scope.clientDomain).toBe("https://data.debtwatch.treasurer.ca.gov") expect($rootScope.modalFixed).toBeFalsy() expect($rootScope.modalIsDisplayed).toBeFalsy() describe '$scope.createMap', -> it 'disables the scroll wheel', -> expect($scope.map.scrollWheel).toBeFalsy() describe '$scope.highlightFeature', -> it 'calls displaySummaryData if the modal is not fixed', -> $scope.countyHash = {Test: 'foo'} $scope.activeCounty = "bar" $rootScope.modalFixed = false $scope.highlightFeature(layerEl) expect($scope.activeCounty).toBe('foo') describe '$scope.resetHighlight', -> it 'sets opacity and fillColor to the appropriate values', -> $scope.resetHighlight(layerEl) expect(opacity).toBe(1) expect(fillColor).toBe('#4f80b2') describe '$scope.fixModal', -> it 'toggles the value of modalFixed', -> $scope.countyHash = {'Test': 'foo'} $scope.pos = {pageX: '4', pageY: '5'} $rootScope.modalFixed = true $scope.fixModal(layerEl) expect($rootScope.modalFixed).toBeTruthy() describe '$scope.displaySummaryData', -> it 'sets the active county variable to the appropriate value', -> $scope.activeCounty = "Wow" $scope.countyHash = {"Much test": "So county"} $scope.displaySummaryData("Much test") expect($scope.activeCounty).toBe("So county") describe '$scope.onEachFeature', -> it 'sets values for mouseover, mouseout, and click', -> $scope.highlightFeature = "blue" $scope.resetHighlight = "gray" $scope.fixModal = true $scope.onEachFeature('foo', layerEl) expect(mouseover).toBe('blue') expect(mouseout).toBe('gray') expect(click).toBeTruthy() describe '$scope.plotCounties', -> it 'sets countyGeo', -> $scope.clientDomain = 'https://data.debtwatch.treasurer.ca.gov' $scope.plotCounties() $httpBackend.flush() expect($scope.countyGeo[0][0].type).toEqual("FeatureCollection")
154763
#= require application #= require jquery #= require jquery_ujs #= require d3 #= require bootstrap-sprockets #= require mapbox.js #= require jasmine-jquery #= require angular #= require angular-resource #= require angular-sanitize #= require angular-mocks describe 'mapController', -> $scope = {} $rootScope = {} controller = {} $httpBackend = {} opacity = 0 fillColor = 'blue' spyEvent = {} mouseover = null mouseout = null click = null layerEl = target: setStyle: (obj) -> opacity = obj.opacity fillColor = obj.fillColor feature: properties: NAME: '<NAME>' on: (obj) -> mouseover = obj.mouseover mouseout = obj.mouseout click = obj.click beforeEach( -> module 'debtwatch' fixture.set('<div class="container"><div id="map"></div></div>') ) beforeEach inject((_$controller_, $injector, $rootScope) -> $controller = _$controller_ $scope = $injector.get('$rootScope').$new() $rootScope = $injector.get('$rootScope').$new() $httpBackend = $injector.get('$httpBackend') $httpBackend.when('GET', 'https://data.debtwatch.treasurer.ca.gov/api/assets/5F68F702-28B2-45D1-AF0A-D4C455A565F3?ca-counties-20m.geo.json') .respond([[{type: "FeatureCollection", features: [ geometry: { "type": "Point", "coordinates": [ -105.01621, 39.57422 ] } properties: CENSUSAREA: 594.583 COUNTY: "005" GEO_ID: "0500000US06005" LSAD: "County" NAME: "<NAME>" STATE: "06" ]}], "foo", "bar", "baz"] ); controller = $controller('mapController', $scope: $scope, map: map, $rootScope: $rootScope) ) describe 'init', -> it 'sets appropriate variables', -> expect($scope.activeCounty).toEqual({}) expect($scope.defaultLatLong).toEqual([37.2, -119.7]) expect($scope.defaultZoom).toBe(6) expect($scope.clientDomain).toBe("https://data.debtwatch.treasurer.ca.gov") expect($rootScope.modalFixed).toBeFalsy() expect($rootScope.modalIsDisplayed).toBeFalsy() describe '$scope.createMap', -> it 'disables the scroll wheel', -> expect($scope.map.scrollWheel).toBeFalsy() describe '$scope.highlightFeature', -> it 'calls displaySummaryData if the modal is not fixed', -> $scope.countyHash = {Test: 'foo'} $scope.activeCounty = "bar" $rootScope.modalFixed = false $scope.highlightFeature(layerEl) expect($scope.activeCounty).toBe('foo') describe '$scope.resetHighlight', -> it 'sets opacity and fillColor to the appropriate values', -> $scope.resetHighlight(layerEl) expect(opacity).toBe(1) expect(fillColor).toBe('#4f80b2') describe '$scope.fixModal', -> it 'toggles the value of modalFixed', -> $scope.countyHash = {'Test': 'foo'} $scope.pos = {pageX: '4', pageY: '5'} $rootScope.modalFixed = true $scope.fixModal(layerEl) expect($rootScope.modalFixed).toBeTruthy() describe '$scope.displaySummaryData', -> it 'sets the active county variable to the appropriate value', -> $scope.activeCounty = "Wow" $scope.countyHash = {"Much test": "So county"} $scope.displaySummaryData("Much test") expect($scope.activeCounty).toBe("So county") describe '$scope.onEachFeature', -> it 'sets values for mouseover, mouseout, and click', -> $scope.highlightFeature = "blue" $scope.resetHighlight = "gray" $scope.fixModal = true $scope.onEachFeature('foo', layerEl) expect(mouseover).toBe('blue') expect(mouseout).toBe('gray') expect(click).toBeTruthy() describe '$scope.plotCounties', -> it 'sets countyGeo', -> $scope.clientDomain = 'https://data.debtwatch.treasurer.ca.gov' $scope.plotCounties() $httpBackend.flush() expect($scope.countyGeo[0][0].type).toEqual("FeatureCollection")
true
#= require application #= require jquery #= require jquery_ujs #= require d3 #= require bootstrap-sprockets #= require mapbox.js #= require jasmine-jquery #= require angular #= require angular-resource #= require angular-sanitize #= require angular-mocks describe 'mapController', -> $scope = {} $rootScope = {} controller = {} $httpBackend = {} opacity = 0 fillColor = 'blue' spyEvent = {} mouseover = null mouseout = null click = null layerEl = target: setStyle: (obj) -> opacity = obj.opacity fillColor = obj.fillColor feature: properties: NAME: 'PI:NAME:<NAME>END_PI' on: (obj) -> mouseover = obj.mouseover mouseout = obj.mouseout click = obj.click beforeEach( -> module 'debtwatch' fixture.set('<div class="container"><div id="map"></div></div>') ) beforeEach inject((_$controller_, $injector, $rootScope) -> $controller = _$controller_ $scope = $injector.get('$rootScope').$new() $rootScope = $injector.get('$rootScope').$new() $httpBackend = $injector.get('$httpBackend') $httpBackend.when('GET', 'https://data.debtwatch.treasurer.ca.gov/api/assets/5F68F702-28B2-45D1-AF0A-D4C455A565F3?ca-counties-20m.geo.json') .respond([[{type: "FeatureCollection", features: [ geometry: { "type": "Point", "coordinates": [ -105.01621, 39.57422 ] } properties: CENSUSAREA: 594.583 COUNTY: "005" GEO_ID: "0500000US06005" LSAD: "County" NAME: "PI:NAME:<NAME>END_PI" STATE: "06" ]}], "foo", "bar", "baz"] ); controller = $controller('mapController', $scope: $scope, map: map, $rootScope: $rootScope) ) describe 'init', -> it 'sets appropriate variables', -> expect($scope.activeCounty).toEqual({}) expect($scope.defaultLatLong).toEqual([37.2, -119.7]) expect($scope.defaultZoom).toBe(6) expect($scope.clientDomain).toBe("https://data.debtwatch.treasurer.ca.gov") expect($rootScope.modalFixed).toBeFalsy() expect($rootScope.modalIsDisplayed).toBeFalsy() describe '$scope.createMap', -> it 'disables the scroll wheel', -> expect($scope.map.scrollWheel).toBeFalsy() describe '$scope.highlightFeature', -> it 'calls displaySummaryData if the modal is not fixed', -> $scope.countyHash = {Test: 'foo'} $scope.activeCounty = "bar" $rootScope.modalFixed = false $scope.highlightFeature(layerEl) expect($scope.activeCounty).toBe('foo') describe '$scope.resetHighlight', -> it 'sets opacity and fillColor to the appropriate values', -> $scope.resetHighlight(layerEl) expect(opacity).toBe(1) expect(fillColor).toBe('#4f80b2') describe '$scope.fixModal', -> it 'toggles the value of modalFixed', -> $scope.countyHash = {'Test': 'foo'} $scope.pos = {pageX: '4', pageY: '5'} $rootScope.modalFixed = true $scope.fixModal(layerEl) expect($rootScope.modalFixed).toBeTruthy() describe '$scope.displaySummaryData', -> it 'sets the active county variable to the appropriate value', -> $scope.activeCounty = "Wow" $scope.countyHash = {"Much test": "So county"} $scope.displaySummaryData("Much test") expect($scope.activeCounty).toBe("So county") describe '$scope.onEachFeature', -> it 'sets values for mouseover, mouseout, and click', -> $scope.highlightFeature = "blue" $scope.resetHighlight = "gray" $scope.fixModal = true $scope.onEachFeature('foo', layerEl) expect(mouseover).toBe('blue') expect(mouseout).toBe('gray') expect(click).toBeTruthy() describe '$scope.plotCounties', -> it 'sets countyGeo', -> $scope.clientDomain = 'https://data.debtwatch.treasurer.ca.gov' $scope.plotCounties() $httpBackend.flush() expect($scope.countyGeo[0][0].type).toEqual("FeatureCollection")
[ { "context": "'\n\tcurrentRecipeId: 'currentRecipeId'\n\tusername: 'username'\n\temail: 'email'\n\tpassword: 'password'\n\tisAdmin: ", "end": 165, "score": 0.9993545413017273, "start": 157, "tag": "USERNAME", "value": "username" }, { "context": "\tusername: 'username'\n\temail: 'emai...
app/models/account.coffee
jrdbnntt/theMenu
0
### For 'Account' table. ### #table constants COL = accountId: 'accountId' ownerEaterId: 'ownerEaterId' currentRecipeId: 'currentRecipeId' username: 'username' email: 'email' password: 'password' isAdmin: 'isAdmin' module.exports = (app) -> TNAME = 'Account' TREL = null class app.models.Account constructor: ()-> # Creates a new user in the database. @createNew: (data) -> #email/username MUST be checked for existence prior to call def = app.Q.defer() #Encrypt password app.bcrypt.genSalt 10, (err,salt)-> app.bcrypt.hash data.password, salt, (err, hash)-> sql = app.vsprintf 'INSERT INTO %s (%s,%s,%s,%s) ' + ' VALUES ("%s","%s","%s",%i)' , [ TNAME COL.username COL.email COL.password COL.isAdmin data.username data.email hash 0 #false ] # console.log sql con = app.db.newCon() con.query sql .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() .on 'end', ()-> def.resolve() con.end() return def.promise # Checks if this email belongs to a user. Returns true/false in promise @checkEmailUnused: (email) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.email email ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Email already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise @checkUsernameUnused: (username) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.username username ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Username already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise #checks if it is a valid login @checkLogin: (data) -> def = app.Q.defer() sql = app.vsprintf 'SELECT %s,%s,%s,%s,%s FROM %s WHERE %s = "%s" LIMIT 1' , [ COL.accountId COL.username COL.email COL.password COL.isAdmin TNAME COL.email, data.email ] # console.log sql accountData = {} passTemp = null con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> #user found passTemp = row.password accountData = accountId: parseInt row.accountId username: row.username email: row.email isAdmin: (parseInt row.isAdmin) == 1 res.on 'end', (info)-> if info.numRows > 0 # check password app.bcrypt.compare data.password, passTemp, (err, res)-> if res #valid password def.resolve accountData else console.log 'LOGIN: Invalid password for "'+accountData.email+'"' def.reject 'Invalid login credentials' return else console.log 'LOGIN: Invalid email' def.reject 'Invalid login credentials' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject err con.end() return def.promise
177282
### For 'Account' table. ### #table constants COL = accountId: 'accountId' ownerEaterId: 'ownerEaterId' currentRecipeId: 'currentRecipeId' username: 'username' email: 'email' password: '<PASSWORD>' isAdmin: 'isAdmin' module.exports = (app) -> TNAME = 'Account' TREL = null class app.models.Account constructor: ()-> # Creates a new user in the database. @createNew: (data) -> #email/username MUST be checked for existence prior to call def = app.Q.defer() #Encrypt password app.bcrypt.genSalt 10, (err,salt)-> app.bcrypt.hash data.password, salt, (err, hash)-> sql = app.vsprintf 'INSERT INTO %s (%s,%s,%s,%s) ' + ' VALUES ("%s","%s","%s",%i)' , [ TNAME COL.username COL.email COL.password COL.isAdmin data.username data.email hash 0 #false ] # console.log sql con = app.db.newCon() con.query sql .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() .on 'end', ()-> def.resolve() con.end() return def.promise # Checks if this email belongs to a user. Returns true/false in promise @checkEmailUnused: (email) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.email email ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Email already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise @checkUsernameUnused: (username) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.username username ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Username already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise #checks if it is a valid login @checkLogin: (data) -> def = app.Q.defer() sql = app.vsprintf 'SELECT %s,%s,%s,%s,%s FROM %s WHERE %s = "%s" LIMIT 1' , [ COL.accountId COL.username COL.email COL.password COL.isAdmin TNAME COL.email, data.email ] # console.log sql accountData = {} passTemp = null con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> #user found passTemp = row.password accountData = accountId: parseInt row.accountId username: row.username email: row.email isAdmin: (parseInt row.isAdmin) == 1 res.on 'end', (info)-> if info.numRows > 0 # check password app.bcrypt.compare data.password, passTemp, (err, res)-> if res #valid password def.resolve accountData else console.log 'LOGIN: Invalid password for "'+accountData.email+'"' def.reject 'Invalid login credentials' return else console.log 'LOGIN: Invalid email' def.reject 'Invalid login credentials' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject err con.end() return def.promise
true
### For 'Account' table. ### #table constants COL = accountId: 'accountId' ownerEaterId: 'ownerEaterId' currentRecipeId: 'currentRecipeId' username: 'username' email: 'email' password: 'PI:PASSWORD:<PASSWORD>END_PI' isAdmin: 'isAdmin' module.exports = (app) -> TNAME = 'Account' TREL = null class app.models.Account constructor: ()-> # Creates a new user in the database. @createNew: (data) -> #email/username MUST be checked for existence prior to call def = app.Q.defer() #Encrypt password app.bcrypt.genSalt 10, (err,salt)-> app.bcrypt.hash data.password, salt, (err, hash)-> sql = app.vsprintf 'INSERT INTO %s (%s,%s,%s,%s) ' + ' VALUES ("%s","%s","%s",%i)' , [ TNAME COL.username COL.email COL.password COL.isAdmin data.username data.email hash 0 #false ] # console.log sql con = app.db.newCon() con.query sql .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() .on 'end', ()-> def.resolve() con.end() return def.promise # Checks if this email belongs to a user. Returns true/false in promise @checkEmailUnused: (email) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.email email ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Email already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise @checkUsernameUnused: (username) -> def = app.Q.defer() sql = app.vsprintf 'SELECT COUNT(*) AS c FROM %s WHERE %s = "%s"' , [ TNAME COL.username username ] # console.log sql con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> if row.c == '0' def.resolve() else def.reject 'Username already in use' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject() con.end() return def.promise #checks if it is a valid login @checkLogin: (data) -> def = app.Q.defer() sql = app.vsprintf 'SELECT %s,%s,%s,%s,%s FROM %s WHERE %s = "%s" LIMIT 1' , [ COL.accountId COL.username COL.email COL.password COL.isAdmin TNAME COL.email, data.email ] # console.log sql accountData = {} passTemp = null con = app.db.newCon() con.query sql .on 'result', (res)-> res.on 'row', (row)-> #user found passTemp = row.password accountData = accountId: parseInt row.accountId username: row.username email: row.email isAdmin: (parseInt row.isAdmin) == 1 res.on 'end', (info)-> if info.numRows > 0 # check password app.bcrypt.compare data.password, passTemp, (err, res)-> if res #valid password def.resolve accountData else console.log 'LOGIN: Invalid password for "'+accountData.email+'"' def.reject 'Invalid login credentials' return else console.log 'LOGIN: Invalid email' def.reject 'Invalid login credentials' .on 'error', (err)-> console.log "> DB: Error on old threadId " + this.tId + " = " + err def.reject err con.end() return def.promise
[ { "context": "al'\n ,\n label: 'remote'\n ssh:\n host: '127.0.0.1', username: process.env.USER,\n private_key_p", "end": 260, "score": 0.999576985836029, "start": 251, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " process.env.USER,\n private_key_pa...
packages/docker/test.sample.coffee
wdavidw/node-mecano
0
module.exports = tags: docker: false # disable_docker docker_volume: false docker: # eg `docker-machine create --driver virtualbox nikita` machine: 'nikita' config: [ label: 'local' , label: 'remote' ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: '~/.ssh/id_ed25519' # Exemple with vagrant: # ssh: # host: '127.0.0.1', port: 2222, username: 'vagrant' # private_key_path: "#{require('os').homedir()}/.vagrant.d/insecure_private_key" ]
200162
module.exports = tags: docker: false # disable_docker docker_volume: false docker: # eg `docker-machine create --driver virtualbox nikita` machine: 'nikita' config: [ label: 'local' , label: 'remote' ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: '~/.ssh<KEY>/<KEY>' # Exemple with vagrant: # ssh: # host: '127.0.0.1', port: 2222, username: 'vagrant' # private_key_path: "#{require('os').homedir()}/.vagrant.d/insecure_private_key" ]
true
module.exports = tags: docker: false # disable_docker docker_volume: false docker: # eg `docker-machine create --driver virtualbox nikita` machine: 'nikita' config: [ label: 'local' , label: 'remote' ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: '~/.sshPI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI' # Exemple with vagrant: # ssh: # host: '127.0.0.1', port: 2222, username: 'vagrant' # private_key_path: "#{require('os').homedir()}/.vagrant.d/insecure_private_key" ]
[ { "context": "generator-assemble v0.4.10\n# * https://github.com/assemble/generator-assemble\n# *\n# * Copyright (c) 2014 Har", "end": 92, "score": 0.9986361265182495, "start": 84, "tag": "USERNAME", "value": "assemble" }, { "context": "mble/generator-assemble\n# *\n# * Copyright (c)...
Gruntfile.coffee
daveswebdesigns/portfolio
0
# # * Generated on 2014-03-14 # * generator-assemble v0.4.10 # * https://github.com/assemble/generator-assemble # * # * Copyright (c) 2014 Hariadi Hinta # * Licensed under the MIT license. # "use strict" # # Globbing # for performance reasons we're only matching one level down: # '<%= config.src %>/templates/pages/{,*/}*.hbs' # use this if you want to match all subfolders: # '<%= config.src %>/templates/pages/**/*.hbs' module.exports = (grunt) -> require("time-grunt") grunt # Project configuration. grunt.initConfig config: src: "./src" dist: "./dist" watch: assemble: files: ["<%= config.src %>/templates/{,*/}*.*", "<%= config.src %>/data/{,*/}*"] tasks: ["jsonmin", "assemble"] livereload: options: livereload: "<%= connect.options.livereload %>" files: [ "<%= config.dist %>/assets/{,*/}*.css" "<%= config.dist %>/{,*/}*.html" "<%= config.dist %>/assets/{,*/}*.js" "<%= config.dist %>/assets/{,*/}*.{png,jpg,jpeg,gif,webp,svg}" ] coffee: files: ["<%= config.src %>/coffee/*.coffee"] tasks: ["coffee", "browserify", "uglify:dev"] stylus: files: ["<%= config.src %>/stylus/*.styl"] tasks: ["stylus"] connect: options: port: 9000 livereload: 35729 # change this to '0.0.0.0' to access the server from outside hostname: "localhost" base: ["<%= config.dist %>"] open: true livereload: options: open: target: 'http://localhost:9000/dev.html' app: options: livereload: false keepalive: true coffee: app: options: bare: true expand: true cwd: "<%= config.src %>/coffee/" src: ["**/*.coffee"] dest: "<%= config.src %>/js/" ext: ".js" browserify: app: files: "<%= config.dist %>/assets/js/main.js": ["<%= config.src %>/js/app.js"] options: browserifyOptions: paths: ["<%= config.src %>/js/"] uglify: dev: options: beautify: true compress: false mangle: false files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] app: options: compress: true mangle: true files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] jsonmin: app: files: "<%= config.src %>/data/portfolio.min.json": "<%= config.src %>/data/portfolio.json" stylus: options: compress: false compile: files: "<%= config.dist %>/assets/css/main.css": "<%= config.src %>/stylus/style.styl" postcss: options: processors: [ require('autoprefixer')(browsers: 'last 2 versions') require('cssnano')() ] app: src: '<%= config.dist %>/assets/css/main.css' assemble: options: flatten: true assets: "<%= config.dist %>/assets" helpers: ["handlebars-inline"] layout: "<%= config.src %>/templates/layouts/layout.hbs" data: "<%= config.src %>/data/*.{json,yml}" partials: ["<%= config.src %>/templates/partials/*.hbs", "<%= config.src %>/data/portfolio.json"] pages: files: "<%= config.dist %>/": ["<%= config.src %>/templates/pages/*.hbs"] dev: options: layout: "<%= config.src %>/templates/layouts/layout.dev.hbs" files: "<%= config.dist %>/dev.html": ["<%= config.src %>/templates/pages/index.hbs"] # Before generating any new files, # remove any previously-created files. clean: ["<%= config.dist %>/**/*.{html,css,js}"] grunt.loadNpmTasks "grunt-assemble" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-contrib-connect" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-watch" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-jsonmin" grunt.loadNpmTasks 'grunt-browserify' grunt.loadNpmTasks 'grunt-postcss' # Serve grunt.registerTask "s", [ "connect:livereload" "watch" ] # Dev grunt.registerTask "d", [ "clean" "coffee" "browserify" "uglify:dev" "jsonmin" "stylus" "assemble" "s" ] # Build grunt.registerTask "b", [ "clean" "coffee" "browserify" "uglify:app" "jsonmin" "stylus" "postcss" "assemble" ] # Open grunt.registerTask "o", [ "connect:app" ] # Build and Open grunt.registerTask "default", [ "b" "o" ] return
102220
# # * Generated on 2014-03-14 # * generator-assemble v0.4.10 # * https://github.com/assemble/generator-assemble # * # * Copyright (c) 2014 <NAME> # * Licensed under the MIT license. # "use strict" # # Globbing # for performance reasons we're only matching one level down: # '<%= config.src %>/templates/pages/{,*/}*.hbs' # use this if you want to match all subfolders: # '<%= config.src %>/templates/pages/**/*.hbs' module.exports = (grunt) -> require("time-grunt") grunt # Project configuration. grunt.initConfig config: src: "./src" dist: "./dist" watch: assemble: files: ["<%= config.src %>/templates/{,*/}*.*", "<%= config.src %>/data/{,*/}*"] tasks: ["jsonmin", "assemble"] livereload: options: livereload: "<%= connect.options.livereload %>" files: [ "<%= config.dist %>/assets/{,*/}*.css" "<%= config.dist %>/{,*/}*.html" "<%= config.dist %>/assets/{,*/}*.js" "<%= config.dist %>/assets/{,*/}*.{png,jpg,jpeg,gif,webp,svg}" ] coffee: files: ["<%= config.src %>/coffee/*.coffee"] tasks: ["coffee", "browserify", "uglify:dev"] stylus: files: ["<%= config.src %>/stylus/*.styl"] tasks: ["stylus"] connect: options: port: 9000 livereload: 35729 # change this to '0.0.0.0' to access the server from outside hostname: "localhost" base: ["<%= config.dist %>"] open: true livereload: options: open: target: 'http://localhost:9000/dev.html' app: options: livereload: false keepalive: true coffee: app: options: bare: true expand: true cwd: "<%= config.src %>/coffee/" src: ["**/*.coffee"] dest: "<%= config.src %>/js/" ext: ".js" browserify: app: files: "<%= config.dist %>/assets/js/main.js": ["<%= config.src %>/js/app.js"] options: browserifyOptions: paths: ["<%= config.src %>/js/"] uglify: dev: options: beautify: true compress: false mangle: false files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] app: options: compress: true mangle: true files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] jsonmin: app: files: "<%= config.src %>/data/portfolio.min.json": "<%= config.src %>/data/portfolio.json" stylus: options: compress: false compile: files: "<%= config.dist %>/assets/css/main.css": "<%= config.src %>/stylus/style.styl" postcss: options: processors: [ require('autoprefixer')(browsers: 'last 2 versions') require('cssnano')() ] app: src: '<%= config.dist %>/assets/css/main.css' assemble: options: flatten: true assets: "<%= config.dist %>/assets" helpers: ["handlebars-inline"] layout: "<%= config.src %>/templates/layouts/layout.hbs" data: "<%= config.src %>/data/*.{json,yml}" partials: ["<%= config.src %>/templates/partials/*.hbs", "<%= config.src %>/data/portfolio.json"] pages: files: "<%= config.dist %>/": ["<%= config.src %>/templates/pages/*.hbs"] dev: options: layout: "<%= config.src %>/templates/layouts/layout.dev.hbs" files: "<%= config.dist %>/dev.html": ["<%= config.src %>/templates/pages/index.hbs"] # Before generating any new files, # remove any previously-created files. clean: ["<%= config.dist %>/**/*.{html,css,js}"] grunt.loadNpmTasks "grunt-assemble" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-contrib-connect" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-watch" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-jsonmin" grunt.loadNpmTasks 'grunt-browserify' grunt.loadNpmTasks 'grunt-postcss' # Serve grunt.registerTask "s", [ "connect:livereload" "watch" ] # Dev grunt.registerTask "d", [ "clean" "coffee" "browserify" "uglify:dev" "jsonmin" "stylus" "assemble" "s" ] # Build grunt.registerTask "b", [ "clean" "coffee" "browserify" "uglify:app" "jsonmin" "stylus" "postcss" "assemble" ] # Open grunt.registerTask "o", [ "connect:app" ] # Build and Open grunt.registerTask "default", [ "b" "o" ] return
true
# # * Generated on 2014-03-14 # * generator-assemble v0.4.10 # * https://github.com/assemble/generator-assemble # * # * Copyright (c) 2014 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # "use strict" # # Globbing # for performance reasons we're only matching one level down: # '<%= config.src %>/templates/pages/{,*/}*.hbs' # use this if you want to match all subfolders: # '<%= config.src %>/templates/pages/**/*.hbs' module.exports = (grunt) -> require("time-grunt") grunt # Project configuration. grunt.initConfig config: src: "./src" dist: "./dist" watch: assemble: files: ["<%= config.src %>/templates/{,*/}*.*", "<%= config.src %>/data/{,*/}*"] tasks: ["jsonmin", "assemble"] livereload: options: livereload: "<%= connect.options.livereload %>" files: [ "<%= config.dist %>/assets/{,*/}*.css" "<%= config.dist %>/{,*/}*.html" "<%= config.dist %>/assets/{,*/}*.js" "<%= config.dist %>/assets/{,*/}*.{png,jpg,jpeg,gif,webp,svg}" ] coffee: files: ["<%= config.src %>/coffee/*.coffee"] tasks: ["coffee", "browserify", "uglify:dev"] stylus: files: ["<%= config.src %>/stylus/*.styl"] tasks: ["stylus"] connect: options: port: 9000 livereload: 35729 # change this to '0.0.0.0' to access the server from outside hostname: "localhost" base: ["<%= config.dist %>"] open: true livereload: options: open: target: 'http://localhost:9000/dev.html' app: options: livereload: false keepalive: true coffee: app: options: bare: true expand: true cwd: "<%= config.src %>/coffee/" src: ["**/*.coffee"] dest: "<%= config.src %>/js/" ext: ".js" browserify: app: files: "<%= config.dist %>/assets/js/main.js": ["<%= config.src %>/js/app.js"] options: browserifyOptions: paths: ["<%= config.src %>/js/"] uglify: dev: options: beautify: true compress: false mangle: false files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] app: options: compress: true mangle: true files: [ src: ["<%= config.dist %>/assets/js/main.js"] dest: "<%= config.dist %>/assets/js/main.min.js" ] jsonmin: app: files: "<%= config.src %>/data/portfolio.min.json": "<%= config.src %>/data/portfolio.json" stylus: options: compress: false compile: files: "<%= config.dist %>/assets/css/main.css": "<%= config.src %>/stylus/style.styl" postcss: options: processors: [ require('autoprefixer')(browsers: 'last 2 versions') require('cssnano')() ] app: src: '<%= config.dist %>/assets/css/main.css' assemble: options: flatten: true assets: "<%= config.dist %>/assets" helpers: ["handlebars-inline"] layout: "<%= config.src %>/templates/layouts/layout.hbs" data: "<%= config.src %>/data/*.{json,yml}" partials: ["<%= config.src %>/templates/partials/*.hbs", "<%= config.src %>/data/portfolio.json"] pages: files: "<%= config.dist %>/": ["<%= config.src %>/templates/pages/*.hbs"] dev: options: layout: "<%= config.src %>/templates/layouts/layout.dev.hbs" files: "<%= config.dist %>/dev.html": ["<%= config.src %>/templates/pages/index.hbs"] # Before generating any new files, # remove any previously-created files. clean: ["<%= config.dist %>/**/*.{html,css,js}"] grunt.loadNpmTasks "grunt-assemble" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-contrib-connect" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-watch" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-jsonmin" grunt.loadNpmTasks 'grunt-browserify' grunt.loadNpmTasks 'grunt-postcss' # Serve grunt.registerTask "s", [ "connect:livereload" "watch" ] # Dev grunt.registerTask "d", [ "clean" "coffee" "browserify" "uglify:dev" "jsonmin" "stylus" "assemble" "s" ] # Build grunt.registerTask "b", [ "clean" "coffee" "browserify" "uglify:app" "jsonmin" "stylus" "postcss" "assemble" ] # Open grunt.registerTask "o", [ "connect:app" ] # Build and Open grunt.registerTask "default", [ "b" "o" ] return
[ { "context": "otLedger.Models.Account(\n id: 1\n name: 'Example Account'\n )\n statements = new DotLedger.Collections", "end": 149, "score": 0.9970238208770752, "start": 134, "tag": "NAME", "value": "Example Account" } ]
spec/javascripts/dot_ledger/views/statements/list_spec.js.coffee
malclocke/dotledger
0
describe "DotLedger.Views.Statements.List", -> createView = -> account = new DotLedger.Models.Account( id: 1 name: 'Example Account' ) statements = new DotLedger.Collections.Statements [ { id: 11 account_id: 1 balance: -1223.16 from_date: '2015-01-11' to_date: '2015-02-11' created_at: '2015-02-20T07:52:57.173' # HACK: These dates are really in UTC transaction_count: 211 } { id: 22 account_id: 1 balance: 444.23 from_date: '2015-01-13' to_date: '2015-02-14' created_at: '2015-02-20T07:52:09.854' # HACK: These dates are really in UTC transaction_count: 18 } { id: 33 account_id: 1 balance: 1101.32 from_date: '2015-01-16' to_date: '2015-02-16' created_at: '2015-02-20T07:51:45.000' # HACK: These dates are really in UTC transaction_count: 42 } ] view = new DotLedger.Views.Statements.List collection: statements account: account view it "should be defined", -> expect(DotLedger.Views.Statements.List).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Statements.List).toUseTemplate('statements/list') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the page title", -> view = createView().render() expect(view.$el).toHaveText(/Statements for Example Account/) it "renders the created at timestamps", -> view = createView().render() expect(view.$el).toHaveText(/20 Feb 2015 07:52:57/) expect(view.$el).toHaveText(/20 Feb 2015 07:52:09/) expect(view.$el).toHaveText(/20 Feb 2015 07:51:45/) it "renders the from dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Jan 2015/) expect(view.$el).toHaveText(/13 Jan 2015/) expect(view.$el).toHaveText(/16 Jan 2015/) it "renders the to dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Feb 2015/) expect(view.$el).toHaveText(/14 Feb 2015/) expect(view.$el).toHaveText(/16 Feb 2015/) it "renders the transaction counts", -> view = createView().render() expect(view.$el).toHaveText(/211/) expect(view.$el).toHaveText(/18/) expect(view.$el).toHaveText(/42/) it "renders the closing balances", -> view = createView().render() expect(view.$el).toHaveText(/\$-1,223\.16/) expect(view.$el).toHaveText(/\$444\.23/) expect(view.$el).toHaveText(/\$1,101\.32/)
148397
describe "DotLedger.Views.Statements.List", -> createView = -> account = new DotLedger.Models.Account( id: 1 name: '<NAME>' ) statements = new DotLedger.Collections.Statements [ { id: 11 account_id: 1 balance: -1223.16 from_date: '2015-01-11' to_date: '2015-02-11' created_at: '2015-02-20T07:52:57.173' # HACK: These dates are really in UTC transaction_count: 211 } { id: 22 account_id: 1 balance: 444.23 from_date: '2015-01-13' to_date: '2015-02-14' created_at: '2015-02-20T07:52:09.854' # HACK: These dates are really in UTC transaction_count: 18 } { id: 33 account_id: 1 balance: 1101.32 from_date: '2015-01-16' to_date: '2015-02-16' created_at: '2015-02-20T07:51:45.000' # HACK: These dates are really in UTC transaction_count: 42 } ] view = new DotLedger.Views.Statements.List collection: statements account: account view it "should be defined", -> expect(DotLedger.Views.Statements.List).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Statements.List).toUseTemplate('statements/list') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the page title", -> view = createView().render() expect(view.$el).toHaveText(/Statements for Example Account/) it "renders the created at timestamps", -> view = createView().render() expect(view.$el).toHaveText(/20 Feb 2015 07:52:57/) expect(view.$el).toHaveText(/20 Feb 2015 07:52:09/) expect(view.$el).toHaveText(/20 Feb 2015 07:51:45/) it "renders the from dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Jan 2015/) expect(view.$el).toHaveText(/13 Jan 2015/) expect(view.$el).toHaveText(/16 Jan 2015/) it "renders the to dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Feb 2015/) expect(view.$el).toHaveText(/14 Feb 2015/) expect(view.$el).toHaveText(/16 Feb 2015/) it "renders the transaction counts", -> view = createView().render() expect(view.$el).toHaveText(/211/) expect(view.$el).toHaveText(/18/) expect(view.$el).toHaveText(/42/) it "renders the closing balances", -> view = createView().render() expect(view.$el).toHaveText(/\$-1,223\.16/) expect(view.$el).toHaveText(/\$444\.23/) expect(view.$el).toHaveText(/\$1,101\.32/)
true
describe "DotLedger.Views.Statements.List", -> createView = -> account = new DotLedger.Models.Account( id: 1 name: 'PI:NAME:<NAME>END_PI' ) statements = new DotLedger.Collections.Statements [ { id: 11 account_id: 1 balance: -1223.16 from_date: '2015-01-11' to_date: '2015-02-11' created_at: '2015-02-20T07:52:57.173' # HACK: These dates are really in UTC transaction_count: 211 } { id: 22 account_id: 1 balance: 444.23 from_date: '2015-01-13' to_date: '2015-02-14' created_at: '2015-02-20T07:52:09.854' # HACK: These dates are really in UTC transaction_count: 18 } { id: 33 account_id: 1 balance: 1101.32 from_date: '2015-01-16' to_date: '2015-02-16' created_at: '2015-02-20T07:51:45.000' # HACK: These dates are really in UTC transaction_count: 42 } ] view = new DotLedger.Views.Statements.List collection: statements account: account view it "should be defined", -> expect(DotLedger.Views.Statements.List).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Statements.List).toUseTemplate('statements/list') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the page title", -> view = createView().render() expect(view.$el).toHaveText(/Statements for Example Account/) it "renders the created at timestamps", -> view = createView().render() expect(view.$el).toHaveText(/20 Feb 2015 07:52:57/) expect(view.$el).toHaveText(/20 Feb 2015 07:52:09/) expect(view.$el).toHaveText(/20 Feb 2015 07:51:45/) it "renders the from dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Jan 2015/) expect(view.$el).toHaveText(/13 Jan 2015/) expect(view.$el).toHaveText(/16 Jan 2015/) it "renders the to dates", -> view = createView().render() expect(view.$el).toHaveText(/11 Feb 2015/) expect(view.$el).toHaveText(/14 Feb 2015/) expect(view.$el).toHaveText(/16 Feb 2015/) it "renders the transaction counts", -> view = createView().render() expect(view.$el).toHaveText(/211/) expect(view.$el).toHaveText(/18/) expect(view.$el).toHaveText(/42/) it "renders the closing balances", -> view = createView().render() expect(view.$el).toHaveText(/\$-1,223\.16/) expect(view.$el).toHaveText(/\$444\.23/) expect(view.$el).toHaveText(/\$1,101\.32/)
[ { "context": "Auth2 client', ->\n testProvider = (name) -> 'fillmore' if name is 'millard'\n\n clientFactory = Butt", "end": 616, "score": 0.8492767810821533, "start": 608, "tag": "USERNAME", "value": "fillmore" }, { "context": "hould construct an API key client', ->\n ...
test/client.coffee
buttercoin/buttercoinsdk-node
2
should = require('should') Buttercoin = require('../lib/client') RequestBuilder = require('../lib/request_builder') Order = require('../lib/requests/create_order') Q = require('q') class NoopAuthorizer authorize: (request) -> @lastRequest = request request class NoopHandler do: (request, opts) => Q(@mockResponse) Buttercoin.testClient = () -> new Buttercoin( new RequestBuilder(), new NoopAuthorizer(), new NoopHandler()) describe 'Buttercoin client', -> describe 'constructor methods', -> it 'should construct an OAuth2 client', -> testProvider = (name) -> 'fillmore' if name is 'millard' clientFactory = Buttercoin.withOAuth2(testProvider) client = clientFactory.as('millard') client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'OAuth2Authorizer' client.auth.tokenProvider.should.equal testProvider client.handler.do.should.be.type 'function' it 'should construct an API key client', -> k = 'abcdefghijklmnopqrstuvwxyz123456' s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' client = Buttercoin.withKeySecret(k, s) client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'KeySecretAuthorizer' client.auth.key.should.equal k client.auth.secret.should.equal s client.handler.do.should.be.type 'function' describe 'operations', -> client = Buttercoin.testClient() it 'should support getting the order book', -> client.getOrderBook() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orderbook' req._auth.should.equal false it 'should support getting trade history', -> client.getTradeHistory() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/trades' req._auth.should.equal false it 'should support getting the ticker', -> client.getTicker() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/ticker' req._auth.should.equal false it 'should support getting account balances', -> client.getBalances() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/account/balances' req._auth.should.equal true it 'should reject bad arguments when posting an order', -> (-> client.postOrder("foo")).should.throw('Invalid argument to createOrder: foo') describe 'Orders', -> it 'should support posting an order', (done) -> client.handler.mockResponse = result: statusCode: 202 headers: {location: 'https://sandbox.buttercoin.com/v1/orders/testOrderId' } res = client.postOrder(Order.marketBid(100)) req = client.auth.lastRequest req.method.should.equal 'POST' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true JSON.stringify(req.body).should.equal '{"instrument":"USD_BTC","side":"sell","orderType":"market","quantity":100}' res.then (orderInfo) -> orderInfo.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/testOrderId' orderInfo.orderId.should.equal 'testOrderId' done() .done it 'should be able to query orders', (done) -> client.handler.mockResponse = result: statusCode: 200 body: JSON.stringify( results: [{ side: 'buy', quantity: 1, priceCurrency: 'USD', price: 10, orderId: 'b1b520ba-caf1-4e54-a914-e8fb0ed6e6e3', quantityCurrency: 'BTC', status: 'opened', orderType: 'limit', events: [ {eventType: 'opened', eventDate: '2015-02-07T07:32:55.025Z', quantity: 1}, {eventType: 'created', eventDate: '2015-02-07T07:32:55.021Z'} ]}]) res = client.getOrders({}) req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true res.then (results) -> should.not.exist(results.statusCode) results.length.should.equal 1 done() it 'should be able to cancel an order', (done) -> client.handler.mockResponse = result: statusCode: 204 body: '' res = client.cancelOrder('test-order-id') req = client.auth.lastRequest req.method.should.equal 'DELETE' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/test-order-id' req._auth.should.equal true res.then (result) -> should.exist(result) result.should.equal "OK" done()
163997
should = require('should') Buttercoin = require('../lib/client') RequestBuilder = require('../lib/request_builder') Order = require('../lib/requests/create_order') Q = require('q') class NoopAuthorizer authorize: (request) -> @lastRequest = request request class NoopHandler do: (request, opts) => Q(@mockResponse) Buttercoin.testClient = () -> new Buttercoin( new RequestBuilder(), new NoopAuthorizer(), new NoopHandler()) describe 'Buttercoin client', -> describe 'constructor methods', -> it 'should construct an OAuth2 client', -> testProvider = (name) -> 'fillmore' if name is 'millard' clientFactory = Buttercoin.withOAuth2(testProvider) client = clientFactory.as('millard') client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'OAuth2Authorizer' client.auth.tokenProvider.should.equal testProvider client.handler.do.should.be.type 'function' it 'should construct an API key client', -> k = '<KEY>' s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' client = Buttercoin.withKeySecret(k, s) client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'KeySecretAuthorizer' client.auth.key.should.equal k client.auth.secret.should.equal s client.handler.do.should.be.type 'function' describe 'operations', -> client = Buttercoin.testClient() it 'should support getting the order book', -> client.getOrderBook() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orderbook' req._auth.should.equal false it 'should support getting trade history', -> client.getTradeHistory() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/trades' req._auth.should.equal false it 'should support getting the ticker', -> client.getTicker() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/ticker' req._auth.should.equal false it 'should support getting account balances', -> client.getBalances() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/account/balances' req._auth.should.equal true it 'should reject bad arguments when posting an order', -> (-> client.postOrder("foo")).should.throw('Invalid argument to createOrder: foo') describe 'Orders', -> it 'should support posting an order', (done) -> client.handler.mockResponse = result: statusCode: 202 headers: {location: 'https://sandbox.buttercoin.com/v1/orders/testOrderId' } res = client.postOrder(Order.marketBid(100)) req = client.auth.lastRequest req.method.should.equal 'POST' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true JSON.stringify(req.body).should.equal '{"instrument":"USD_BTC","side":"sell","orderType":"market","quantity":100}' res.then (orderInfo) -> orderInfo.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/testOrderId' orderInfo.orderId.should.equal 'testOrderId' done() .done it 'should be able to query orders', (done) -> client.handler.mockResponse = result: statusCode: 200 body: JSON.stringify( results: [{ side: 'buy', quantity: 1, priceCurrency: 'USD', price: 10, orderId: 'b1b520ba-caf1-4e54-a914-e8fb0ed6e6e3', quantityCurrency: 'BTC', status: 'opened', orderType: 'limit', events: [ {eventType: 'opened', eventDate: '2015-02-07T07:32:55.025Z', quantity: 1}, {eventType: 'created', eventDate: '2015-02-07T07:32:55.021Z'} ]}]) res = client.getOrders({}) req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true res.then (results) -> should.not.exist(results.statusCode) results.length.should.equal 1 done() it 'should be able to cancel an order', (done) -> client.handler.mockResponse = result: statusCode: 204 body: '' res = client.cancelOrder('test-order-id') req = client.auth.lastRequest req.method.should.equal 'DELETE' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/test-order-id' req._auth.should.equal true res.then (result) -> should.exist(result) result.should.equal "OK" done()
true
should = require('should') Buttercoin = require('../lib/client') RequestBuilder = require('../lib/request_builder') Order = require('../lib/requests/create_order') Q = require('q') class NoopAuthorizer authorize: (request) -> @lastRequest = request request class NoopHandler do: (request, opts) => Q(@mockResponse) Buttercoin.testClient = () -> new Buttercoin( new RequestBuilder(), new NoopAuthorizer(), new NoopHandler()) describe 'Buttercoin client', -> describe 'constructor methods', -> it 'should construct an OAuth2 client', -> testProvider = (name) -> 'fillmore' if name is 'millard' clientFactory = Buttercoin.withOAuth2(testProvider) client = clientFactory.as('millard') client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'OAuth2Authorizer' client.auth.tokenProvider.should.equal testProvider client.handler.do.should.be.type 'function' it 'should construct an API key client', -> k = 'PI:KEY:<KEY>END_PI' s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' client = Buttercoin.withKeySecret(k, s) client.should.be.an.instanceOf Buttercoin client.auth.constructor.name.should.equal 'KeySecretAuthorizer' client.auth.key.should.equal k client.auth.secret.should.equal s client.handler.do.should.be.type 'function' describe 'operations', -> client = Buttercoin.testClient() it 'should support getting the order book', -> client.getOrderBook() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orderbook' req._auth.should.equal false it 'should support getting trade history', -> client.getTradeHistory() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/trades' req._auth.should.equal false it 'should support getting the ticker', -> client.getTicker() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/ticker' req._auth.should.equal false it 'should support getting account balances', -> client.getBalances() req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/account/balances' req._auth.should.equal true it 'should reject bad arguments when posting an order', -> (-> client.postOrder("foo")).should.throw('Invalid argument to createOrder: foo') describe 'Orders', -> it 'should support posting an order', (done) -> client.handler.mockResponse = result: statusCode: 202 headers: {location: 'https://sandbox.buttercoin.com/v1/orders/testOrderId' } res = client.postOrder(Order.marketBid(100)) req = client.auth.lastRequest req.method.should.equal 'POST' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true JSON.stringify(req.body).should.equal '{"instrument":"USD_BTC","side":"sell","orderType":"market","quantity":100}' res.then (orderInfo) -> orderInfo.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/testOrderId' orderInfo.orderId.should.equal 'testOrderId' done() .done it 'should be able to query orders', (done) -> client.handler.mockResponse = result: statusCode: 200 body: JSON.stringify( results: [{ side: 'buy', quantity: 1, priceCurrency: 'USD', price: 10, orderId: 'b1b520ba-caf1-4e54-a914-e8fb0ed6e6e3', quantityCurrency: 'BTC', status: 'opened', orderType: 'limit', events: [ {eventType: 'opened', eventDate: '2015-02-07T07:32:55.025Z', quantity: 1}, {eventType: 'created', eventDate: '2015-02-07T07:32:55.021Z'} ]}]) res = client.getOrders({}) req = client.auth.lastRequest req.method.should.equal 'GET' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders' req._auth.should.equal true res.then (results) -> should.not.exist(results.statusCode) results.length.should.equal 1 done() it 'should be able to cancel an order', (done) -> client.handler.mockResponse = result: statusCode: 204 body: '' res = client.cancelOrder('test-order-id') req = client.auth.lastRequest req.method.should.equal 'DELETE' req.url.should.equal 'https://sandbox.buttercoin.com/v1/orders/test-order-id' req._auth.should.equal true res.then (result) -> should.exist(result) result.should.equal "OK" done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.99830561876297, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-symlink-dir-junction.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") path = require("path") fs = require("fs") completed = 0 expected_tests = 4 # test creating and reading symbolic link linkData = path.join(common.fixturesDir, "cycles/") linkPath = path.join(common.tmpDir, "cycles_link") # Delete previously created link try fs.unlinkSync linkPath console.log "linkData: " + linkData console.log "linkPath: " + linkPath fs.symlink linkData, linkPath, "junction", (err) -> throw err if err completed++ fs.lstat linkPath, (err, stats) -> throw err if err assert.ok stats.isSymbolicLink() completed++ fs.readlink linkPath, (err, destination) -> throw err if err assert.equal destination, linkData completed++ fs.unlink linkPath, (err) -> throw err if err assert not fs.existsSync(linkPath) assert fs.existsSync(linkData) completed++ return return return return process.on "exit", -> assert.equal completed, expected_tests return
102280
# 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") path = require("path") fs = require("fs") completed = 0 expected_tests = 4 # test creating and reading symbolic link linkData = path.join(common.fixturesDir, "cycles/") linkPath = path.join(common.tmpDir, "cycles_link") # Delete previously created link try fs.unlinkSync linkPath console.log "linkData: " + linkData console.log "linkPath: " + linkPath fs.symlink linkData, linkPath, "junction", (err) -> throw err if err completed++ fs.lstat linkPath, (err, stats) -> throw err if err assert.ok stats.isSymbolicLink() completed++ fs.readlink linkPath, (err, destination) -> throw err if err assert.equal destination, linkData completed++ fs.unlink linkPath, (err) -> throw err if err assert not fs.existsSync(linkPath) assert fs.existsSync(linkData) completed++ return return return return process.on "exit", -> assert.equal completed, expected_tests 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") path = require("path") fs = require("fs") completed = 0 expected_tests = 4 # test creating and reading symbolic link linkData = path.join(common.fixturesDir, "cycles/") linkPath = path.join(common.tmpDir, "cycles_link") # Delete previously created link try fs.unlinkSync linkPath console.log "linkData: " + linkData console.log "linkPath: " + linkPath fs.symlink linkData, linkPath, "junction", (err) -> throw err if err completed++ fs.lstat linkPath, (err, stats) -> throw err if err assert.ok stats.isSymbolicLink() completed++ fs.readlink linkPath, (err, destination) -> throw err if err assert.equal destination, linkData completed++ fs.unlink linkPath, (err) -> throw err if err assert not fs.existsSync(linkPath) assert fs.existsSync(linkData) completed++ return return return return process.on "exit", -> assert.equal completed, expected_tests return
[ { "context": ",\n \"date\": \"1-20-2015\",\n \"author\": \"brekk\"\n }}}\n # Learning \n Lorem ipsum dolor si", "end": 2222, "score": 0.999064028263092, "start": 2217, "tag": "USERNAME", "value": "brekk" }, { "context": " title: \"Test\"\n ...
README.md.coffee
brekk/raconteur
1
# Raconteur ## a library for converting simple markdown to smart markup Ever been frustrated by the need to separate the concerns of content creation (markdown) from the concerns of design (markup)? Raconteur offers some loosely-opinionated tools to manage robust content and convert it to clean markup. #### Tools 1. scribe ([raconteur-scribe][]) - _a tool for dead-simple content creation in markdown and modified json._ 2. renderer ([marked][]) - _an extensible markdown parser (`marked` internally), used by the scribe._ 3. crier ([raconteur-crier][]]- _a tool for expressive and easy template creation in jade and dust._ 4. herald ([raconteur-herald][])- _a tool for creating a crier instance preloaded with templates._ [raconteur-scribe]: https://www.npmjs.com/package/raconteur-scribe "The raconteur-scribe module" [raconteur-crier]: https://www.npmjs.com/package/raconteur-crier "The raconteur-crier module" [raconteur-herald]: https://www.npmjs.com/package/raconteur-crier#herald "The raconteur-crier module (Herald)" [marked]: https://www.npmjs.com/package/marked "The marked module" #### Utilities 1. telegraph - _a light-weight single-template implementation that binds the scribe and the crier together._ 2. telepath - _a more complex but more reusable implementation which binds the scribe and the crier together._ ## Tools ### Scribe The Scribe is a tool for converting content (think markdown / post format) into a more reusable object format which can resolve itself to HTML, but one which also has easy-to-create metadata. In addition to the standard markdown you probably know and love, because we're using the `marked` library internally, you can modify and extend the existing renderer. (See [below][custom-renderer] for more details.) [custom-renderer]: #custom-renderer "Rendering with a custom markdown renderer" #### Metadata We're using the `json-front-matter` library under the hood, and that allows us to quickly add custom metadata to any content. Here's an example post, using a combination of json-front-matter and markdown: **example-post.md**: {{{ "title": "The Title", "tags": ["a", "b", "c"], "date": "1-20-2015", "author": "brekk" }}} # Learning Lorem ipsum dolor sit amet adipiscine elit. We can easily reference any of those properties in our template later using Crier module, but more on that shortly. Here's an example of using the Scribe module. scribe = require('raconteur').scribe file = "./example-post.md" We can use `scribe.readFile`, which follows the standard node-style callback (function(error, data)) and reads a markdown file into memory: scribe.readFile file, (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from file above: {title, tags, date, author} console.log data.content # prints markdown body as HTML We can use `scribe.readRaw`, which does the same thing as above but reads the content as a raw string: scribe.readRaw "{{{"title": "Hello World"}}}\n*hello* stranger.", (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML Finally, we can use the promise-based version of either of those methods, `scribe.readFileAsPromise` and `scribe.readRawAsPromise` respectively, which don't expect the callback and instead return a promise: happy = (data)-> console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML sad = (error)-> console.log "error during readRaw", error.toString() if error.stack? console.log error.stack scribe.readFileAsPromise("./example-post.md").then happy, sad # or scribe.readRawAsPromise("{{{"title": "Hello World"}}}\n*hello* stranger.").then happy, sad ##### Rendering with a custom markdown renderer If you have a custom renderer (an instance of the `marked.renderer`), you can set it on a Scribe using `scribe.setRenderer(customRendererInstance)`. ### Crier The Crier is a tool for converting markup (either straight HTML, jade, or jade-and-dust together, my preferred sugar syntax) into a template (a function which can be fed data and resolves itself into a view). Here's an example file in the preferred sugar syntax: **example-post.sugar** - an easy to learn, expressive combination of dust and jade: .post .meta header h1|{model.attributes.title} h2|By {model.attributes.author} span.timestamp|{model.attributes.date} ul.tags|{#model.attributes.tags} li.tag|{.} {/model.attributes.tags} p.content|{model.content|s} Here's an example of using the Crier module. In this example we're using mock content, as the Crier and Scribe modules are intended to be used together but are designed to be modular enough to be used independently. (Read more below to see more encapsulated modules / tools.): crier = require('raconteur').crier # this example we'll do the reading ourselves, but there are other ways of adding content which we'll get to below. fs.readFile './example-post.tpl', {encoding: 'utf8'}, (e, content)-> if e? console.log "Error during read:", e.toString() if e.stack? console.log e.stack return useSugarSyntax = true # this adds the template to the dust cache crier.add 'namedTemplate', content, useSugarSyntax mockContent = { model: { attributes: { title: "Test" author: "Brekk" date: "3-30-15" tags: [ "a" "b" "c" ] } content: "<strong>hello</strong>" } } # this retrieves the named template from the dust cache, and populates it with content crier.create 'namedTemplate', mockContent, (e, content)-> if e? console.log e return console.log content # prints converted HTML In addition to reading files from a source, you can also point the Crier at files during runtime: crier = require('raconteur').crier onLoaded = (data)-> console.log "Things loaded.", data.attributes, data.content onError = (e)-> console.log "Error during loadFile", e.toString() if e.stack? console.log e.stack crier.loadFileAsPromise('./example-post.sugar', 'namedTemplate').then onLoaded, onError Please read the tests for a better understanding of all the possible options for the Crier. ### Herald The Herald is essentially a re-wrapper for the Crier. It allows you to create a custom instance of the Crier with templates pre-loaded (they can either be loaded at runtime or pre-added to the output file), so the generated file already has access to the templates you want to use. It's pretty straightforward to use, but the main configurable options are in the `herald.export` method. **retemplater.js** fs = require 'fs' herald = require('raconteur').herald herald.add './post.sugar' herald.add './page.sugar' success = (content)-> fs.writeFile './herald-custom.js', content, {encoding: 'utf8'}, ()-> console.log "success" failure = (e)-> console.log "Error creating custom crier.", e.toString() if e.stack? console.log e.stack settings = { sugar: true mode: 'inline-convert' inflate: false } herald.export(settings).then success, failure Once that retemplater file has been run, you should have a custom version of the Crier which you can use instead of it: crier = require('./herald-custom') crier.has 'post.sugar' # prints true crier.has 'page.sugar' # prints true crier.has 'summary.sugar' # prints false ## Utilities ### Telegraph The Telegraph is a lightweight, single-template-only utility which joins together the functionality of both the Crier and Scribe in a single function which returns a promise. telegraph = require('raconteur').telegraph postLocation = "./posts/somePost" fs.readFile postLocation, {encoding: 'utf8'}, (rawPost)-> telegraphOperation = telegraph('post.html', '<div>{model.content|s}</div>', rawPost) succeed = (content)-> console.log "WE HAVE OUR CONTENT", CONTENT fail = (e)-> console.log "WE ARE FAILURES", e telegraphOperation.then succeed, fail ### Telepath The Telepath is a more fully featured object which joins together the functionality of the Crier and the Scribe with a convenient chainable interface. telepath = require('raconteur').telepath telepath.chain() .sugar() # enables sugar syntax .promise() # switches ready() from expecting a callback to returning a promise .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready().then (posts)-> console.log posts[0] # prints test.md x tpl-post.sugar console.log posts[1] # prints other-test.md x tpl-post.sugar console.log posts[2] # prints shut-up.md x tpl-post.sugar , (e)-> console.log "there was an error!", e You can also give a post first followed by multiple templates: telepath.chain() .sugar() .post("./posts/test.md") .template("post.sugar", "./templates/tpl-post.sugar") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .ready (e, out)-> console.log out.length # prints 3 ### out[0] = test.md x post.sugar out[1] = test.md x post-summary.sugar out[2] = test.md x post-hero.sugar ### You can also make multiple template and post declarations: telepath.chain() .sugar() .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 7 ### out[0] = post.sugar x test.md out[1] = post.sugar x other-test.md out[2] = post.sugar x shut-up.md out[3] = post-summary.sugar x test.md out[4] = post-summary.sugar x other-test.md out[5] = post-hero.sugar x other-test.md out[6] = post-hero.sugar x shut-up.md ### In addition you can also call the `raw()` method at any time, and then the post and template methods will expect raw content instead of a filename. telepath.chain() .raw() .template("post.html", "<div><h1>{model.attributes.title}</h1><p>{model.content|s}</p></div>") .post('{{{ "title": "raw title", }}}\n# Header\n## Subheader\n*strong*\n_emphasis_') .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 1 console.log out[0] # prints the converted template populated with the raw content
43320
# Raconteur ## a library for converting simple markdown to smart markup Ever been frustrated by the need to separate the concerns of content creation (markdown) from the concerns of design (markup)? Raconteur offers some loosely-opinionated tools to manage robust content and convert it to clean markup. #### Tools 1. scribe ([raconteur-scribe][]) - _a tool for dead-simple content creation in markdown and modified json._ 2. renderer ([marked][]) - _an extensible markdown parser (`marked` internally), used by the scribe._ 3. crier ([raconteur-crier][]]- _a tool for expressive and easy template creation in jade and dust._ 4. herald ([raconteur-herald][])- _a tool for creating a crier instance preloaded with templates._ [raconteur-scribe]: https://www.npmjs.com/package/raconteur-scribe "The raconteur-scribe module" [raconteur-crier]: https://www.npmjs.com/package/raconteur-crier "The raconteur-crier module" [raconteur-herald]: https://www.npmjs.com/package/raconteur-crier#herald "The raconteur-crier module (Herald)" [marked]: https://www.npmjs.com/package/marked "The marked module" #### Utilities 1. telegraph - _a light-weight single-template implementation that binds the scribe and the crier together._ 2. telepath - _a more complex but more reusable implementation which binds the scribe and the crier together._ ## Tools ### Scribe The Scribe is a tool for converting content (think markdown / post format) into a more reusable object format which can resolve itself to HTML, but one which also has easy-to-create metadata. In addition to the standard markdown you probably know and love, because we're using the `marked` library internally, you can modify and extend the existing renderer. (See [below][custom-renderer] for more details.) [custom-renderer]: #custom-renderer "Rendering with a custom markdown renderer" #### Metadata We're using the `json-front-matter` library under the hood, and that allows us to quickly add custom metadata to any content. Here's an example post, using a combination of json-front-matter and markdown: **example-post.md**: {{{ "title": "The Title", "tags": ["a", "b", "c"], "date": "1-20-2015", "author": "brekk" }}} # Learning Lorem ipsum dolor sit amet adipiscine elit. We can easily reference any of those properties in our template later using Crier module, but more on that shortly. Here's an example of using the Scribe module. scribe = require('raconteur').scribe file = "./example-post.md" We can use `scribe.readFile`, which follows the standard node-style callback (function(error, data)) and reads a markdown file into memory: scribe.readFile file, (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from file above: {title, tags, date, author} console.log data.content # prints markdown body as HTML We can use `scribe.readRaw`, which does the same thing as above but reads the content as a raw string: scribe.readRaw "{{{"title": "Hello World"}}}\n*hello* stranger.", (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML Finally, we can use the promise-based version of either of those methods, `scribe.readFileAsPromise` and `scribe.readRawAsPromise` respectively, which don't expect the callback and instead return a promise: happy = (data)-> console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML sad = (error)-> console.log "error during readRaw", error.toString() if error.stack? console.log error.stack scribe.readFileAsPromise("./example-post.md").then happy, sad # or scribe.readRawAsPromise("{{{"title": "Hello World"}}}\n*hello* stranger.").then happy, sad ##### Rendering with a custom markdown renderer If you have a custom renderer (an instance of the `marked.renderer`), you can set it on a Scribe using `scribe.setRenderer(customRendererInstance)`. ### Crier The Crier is a tool for converting markup (either straight HTML, jade, or jade-and-dust together, my preferred sugar syntax) into a template (a function which can be fed data and resolves itself into a view). Here's an example file in the preferred sugar syntax: **example-post.sugar** - an easy to learn, expressive combination of dust and jade: .post .meta header h1|{model.attributes.title} h2|By {model.attributes.author} span.timestamp|{model.attributes.date} ul.tags|{#model.attributes.tags} li.tag|{.} {/model.attributes.tags} p.content|{model.content|s} Here's an example of using the Crier module. In this example we're using mock content, as the Crier and Scribe modules are intended to be used together but are designed to be modular enough to be used independently. (Read more below to see more encapsulated modules / tools.): crier = require('raconteur').crier # this example we'll do the reading ourselves, but there are other ways of adding content which we'll get to below. fs.readFile './example-post.tpl', {encoding: 'utf8'}, (e, content)-> if e? console.log "Error during read:", e.toString() if e.stack? console.log e.stack return useSugarSyntax = true # this adds the template to the dust cache crier.add 'namedTemplate', content, useSugarSyntax mockContent = { model: { attributes: { title: "Test" author: "<NAME>" date: "3-30-15" tags: [ "a" "b" "c" ] } content: "<strong>hello</strong>" } } # this retrieves the named template from the dust cache, and populates it with content crier.create 'namedTemplate', mockContent, (e, content)-> if e? console.log e return console.log content # prints converted HTML In addition to reading files from a source, you can also point the Crier at files during runtime: crier = require('raconteur').crier onLoaded = (data)-> console.log "Things loaded.", data.attributes, data.content onError = (e)-> console.log "Error during loadFile", e.toString() if e.stack? console.log e.stack crier.loadFileAsPromise('./example-post.sugar', 'namedTemplate').then onLoaded, onError Please read the tests for a better understanding of all the possible options for the Crier. ### Herald The Herald is essentially a re-wrapper for the Crier. It allows you to create a custom instance of the Crier with templates pre-loaded (they can either be loaded at runtime or pre-added to the output file), so the generated file already has access to the templates you want to use. It's pretty straightforward to use, but the main configurable options are in the `herald.export` method. **retemplater.js** fs = require 'fs' herald = require('raconteur').herald herald.add './post.sugar' herald.add './page.sugar' success = (content)-> fs.writeFile './herald-custom.js', content, {encoding: 'utf8'}, ()-> console.log "success" failure = (e)-> console.log "Error creating custom crier.", e.toString() if e.stack? console.log e.stack settings = { sugar: true mode: 'inline-convert' inflate: false } herald.export(settings).then success, failure Once that retemplater file has been run, you should have a custom version of the Crier which you can use instead of it: crier = require('./herald-custom') crier.has 'post.sugar' # prints true crier.has 'page.sugar' # prints true crier.has 'summary.sugar' # prints false ## Utilities ### Telegraph The Telegraph is a lightweight, single-template-only utility which joins together the functionality of both the Crier and Scribe in a single function which returns a promise. telegraph = require('raconteur').telegraph postLocation = "./posts/somePost" fs.readFile postLocation, {encoding: 'utf8'}, (rawPost)-> telegraphOperation = telegraph('post.html', '<div>{model.content|s}</div>', rawPost) succeed = (content)-> console.log "WE HAVE OUR CONTENT", CONTENT fail = (e)-> console.log "WE ARE FAILURES", e telegraphOperation.then succeed, fail ### Telepath The Telepath is a more fully featured object which joins together the functionality of the Crier and the Scribe with a convenient chainable interface. telepath = require('raconteur').telepath telepath.chain() .sugar() # enables sugar syntax .promise() # switches ready() from expecting a callback to returning a promise .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready().then (posts)-> console.log posts[0] # prints test.md x tpl-post.sugar console.log posts[1] # prints other-test.md x tpl-post.sugar console.log posts[2] # prints shut-up.md x tpl-post.sugar , (e)-> console.log "there was an error!", e You can also give a post first followed by multiple templates: telepath.chain() .sugar() .post("./posts/test.md") .template("post.sugar", "./templates/tpl-post.sugar") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .ready (e, out)-> console.log out.length # prints 3 ### out[0] = test.md x post.sugar out[1] = test.md x post-summary.sugar out[2] = test.md x post-hero.sugar ### You can also make multiple template and post declarations: telepath.chain() .sugar() .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 7 ### out[0] = post.sugar x test.md out[1] = post.sugar x other-test.md out[2] = post.sugar x shut-up.md out[3] = post-summary.sugar x test.md out[4] = post-summary.sugar x other-test.md out[5] = post-hero.sugar x other-test.md out[6] = post-hero.sugar x shut-up.md ### In addition you can also call the `raw()` method at any time, and then the post and template methods will expect raw content instead of a filename. telepath.chain() .raw() .template("post.html", "<div><h1>{model.attributes.title}</h1><p>{model.content|s}</p></div>") .post('{{{ "title": "raw title", }}}\n# Header\n## Subheader\n*strong*\n_emphasis_') .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 1 console.log out[0] # prints the converted template populated with the raw content
true
# Raconteur ## a library for converting simple markdown to smart markup Ever been frustrated by the need to separate the concerns of content creation (markdown) from the concerns of design (markup)? Raconteur offers some loosely-opinionated tools to manage robust content and convert it to clean markup. #### Tools 1. scribe ([raconteur-scribe][]) - _a tool for dead-simple content creation in markdown and modified json._ 2. renderer ([marked][]) - _an extensible markdown parser (`marked` internally), used by the scribe._ 3. crier ([raconteur-crier][]]- _a tool for expressive and easy template creation in jade and dust._ 4. herald ([raconteur-herald][])- _a tool for creating a crier instance preloaded with templates._ [raconteur-scribe]: https://www.npmjs.com/package/raconteur-scribe "The raconteur-scribe module" [raconteur-crier]: https://www.npmjs.com/package/raconteur-crier "The raconteur-crier module" [raconteur-herald]: https://www.npmjs.com/package/raconteur-crier#herald "The raconteur-crier module (Herald)" [marked]: https://www.npmjs.com/package/marked "The marked module" #### Utilities 1. telegraph - _a light-weight single-template implementation that binds the scribe and the crier together._ 2. telepath - _a more complex but more reusable implementation which binds the scribe and the crier together._ ## Tools ### Scribe The Scribe is a tool for converting content (think markdown / post format) into a more reusable object format which can resolve itself to HTML, but one which also has easy-to-create metadata. In addition to the standard markdown you probably know and love, because we're using the `marked` library internally, you can modify and extend the existing renderer. (See [below][custom-renderer] for more details.) [custom-renderer]: #custom-renderer "Rendering with a custom markdown renderer" #### Metadata We're using the `json-front-matter` library under the hood, and that allows us to quickly add custom metadata to any content. Here's an example post, using a combination of json-front-matter and markdown: **example-post.md**: {{{ "title": "The Title", "tags": ["a", "b", "c"], "date": "1-20-2015", "author": "brekk" }}} # Learning Lorem ipsum dolor sit amet adipiscine elit. We can easily reference any of those properties in our template later using Crier module, but more on that shortly. Here's an example of using the Scribe module. scribe = require('raconteur').scribe file = "./example-post.md" We can use `scribe.readFile`, which follows the standard node-style callback (function(error, data)) and reads a markdown file into memory: scribe.readFile file, (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from file above: {title, tags, date, author} console.log data.content # prints markdown body as HTML We can use `scribe.readRaw`, which does the same thing as above but reads the content as a raw string: scribe.readRaw "{{{"title": "Hello World"}}}\n*hello* stranger.", (error, data)-> if error console.log error return console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML Finally, we can use the promise-based version of either of those methods, `scribe.readFileAsPromise` and `scribe.readRawAsPromise` respectively, which don't expect the callback and instead return a promise: happy = (data)-> console.log data.attributes # prints attribute hash from raw string above: {title} console.log data.content # prints markdown body as HTML sad = (error)-> console.log "error during readRaw", error.toString() if error.stack? console.log error.stack scribe.readFileAsPromise("./example-post.md").then happy, sad # or scribe.readRawAsPromise("{{{"title": "Hello World"}}}\n*hello* stranger.").then happy, sad ##### Rendering with a custom markdown renderer If you have a custom renderer (an instance of the `marked.renderer`), you can set it on a Scribe using `scribe.setRenderer(customRendererInstance)`. ### Crier The Crier is a tool for converting markup (either straight HTML, jade, or jade-and-dust together, my preferred sugar syntax) into a template (a function which can be fed data and resolves itself into a view). Here's an example file in the preferred sugar syntax: **example-post.sugar** - an easy to learn, expressive combination of dust and jade: .post .meta header h1|{model.attributes.title} h2|By {model.attributes.author} span.timestamp|{model.attributes.date} ul.tags|{#model.attributes.tags} li.tag|{.} {/model.attributes.tags} p.content|{model.content|s} Here's an example of using the Crier module. In this example we're using mock content, as the Crier and Scribe modules are intended to be used together but are designed to be modular enough to be used independently. (Read more below to see more encapsulated modules / tools.): crier = require('raconteur').crier # this example we'll do the reading ourselves, but there are other ways of adding content which we'll get to below. fs.readFile './example-post.tpl', {encoding: 'utf8'}, (e, content)-> if e? console.log "Error during read:", e.toString() if e.stack? console.log e.stack return useSugarSyntax = true # this adds the template to the dust cache crier.add 'namedTemplate', content, useSugarSyntax mockContent = { model: { attributes: { title: "Test" author: "PI:NAME:<NAME>END_PI" date: "3-30-15" tags: [ "a" "b" "c" ] } content: "<strong>hello</strong>" } } # this retrieves the named template from the dust cache, and populates it with content crier.create 'namedTemplate', mockContent, (e, content)-> if e? console.log e return console.log content # prints converted HTML In addition to reading files from a source, you can also point the Crier at files during runtime: crier = require('raconteur').crier onLoaded = (data)-> console.log "Things loaded.", data.attributes, data.content onError = (e)-> console.log "Error during loadFile", e.toString() if e.stack? console.log e.stack crier.loadFileAsPromise('./example-post.sugar', 'namedTemplate').then onLoaded, onError Please read the tests for a better understanding of all the possible options for the Crier. ### Herald The Herald is essentially a re-wrapper for the Crier. It allows you to create a custom instance of the Crier with templates pre-loaded (they can either be loaded at runtime or pre-added to the output file), so the generated file already has access to the templates you want to use. It's pretty straightforward to use, but the main configurable options are in the `herald.export` method. **retemplater.js** fs = require 'fs' herald = require('raconteur').herald herald.add './post.sugar' herald.add './page.sugar' success = (content)-> fs.writeFile './herald-custom.js', content, {encoding: 'utf8'}, ()-> console.log "success" failure = (e)-> console.log "Error creating custom crier.", e.toString() if e.stack? console.log e.stack settings = { sugar: true mode: 'inline-convert' inflate: false } herald.export(settings).then success, failure Once that retemplater file has been run, you should have a custom version of the Crier which you can use instead of it: crier = require('./herald-custom') crier.has 'post.sugar' # prints true crier.has 'page.sugar' # prints true crier.has 'summary.sugar' # prints false ## Utilities ### Telegraph The Telegraph is a lightweight, single-template-only utility which joins together the functionality of both the Crier and Scribe in a single function which returns a promise. telegraph = require('raconteur').telegraph postLocation = "./posts/somePost" fs.readFile postLocation, {encoding: 'utf8'}, (rawPost)-> telegraphOperation = telegraph('post.html', '<div>{model.content|s}</div>', rawPost) succeed = (content)-> console.log "WE HAVE OUR CONTENT", CONTENT fail = (e)-> console.log "WE ARE FAILURES", e telegraphOperation.then succeed, fail ### Telepath The Telepath is a more fully featured object which joins together the functionality of the Crier and the Scribe with a convenient chainable interface. telepath = require('raconteur').telepath telepath.chain() .sugar() # enables sugar syntax .promise() # switches ready() from expecting a callback to returning a promise .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready().then (posts)-> console.log posts[0] # prints test.md x tpl-post.sugar console.log posts[1] # prints other-test.md x tpl-post.sugar console.log posts[2] # prints shut-up.md x tpl-post.sugar , (e)-> console.log "there was an error!", e You can also give a post first followed by multiple templates: telepath.chain() .sugar() .post("./posts/test.md") .template("post.sugar", "./templates/tpl-post.sugar") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .ready (e, out)-> console.log out.length # prints 3 ### out[0] = test.md x post.sugar out[1] = test.md x post-summary.sugar out[2] = test.md x post-hero.sugar ### You can also make multiple template and post declarations: telepath.chain() .sugar() .template("post.sugar", "./templates/tpl-post.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .post("./posts/shut-up.md") .template("post-summary.sugar", "./templates/tpl-post-summary.sugar") .post("./posts/test.md") .post("./posts/other-test.md") .template("post-hero.sugar", "./templates/tpl-post-hero.sugar") .post("./posts/other-test.md") .post("./posts/shut-up.md") .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 7 ### out[0] = post.sugar x test.md out[1] = post.sugar x other-test.md out[2] = post.sugar x shut-up.md out[3] = post-summary.sugar x test.md out[4] = post-summary.sugar x other-test.md out[5] = post-hero.sugar x other-test.md out[6] = post-hero.sugar x shut-up.md ### In addition you can also call the `raw()` method at any time, and then the post and template methods will expect raw content instead of a filename. telepath.chain() .raw() .template("post.html", "<div><h1>{model.attributes.title}</h1><p>{model.content|s}</p></div>") .post('{{{ "title": "raw title", }}}\n# Header\n## Subheader\n*strong*\n_emphasis_') .ready (e, out)-> console.log e == null # prints true console.log out.length # prints 1 console.log out[0] # prints the converted template populated with the raw content
[ { "context": "= new metrics.Timer(\"lock.#{namespace}\")\n\t\tkey = \"lock:web:#{namespace}:#{id}\"\n\t\tLockManager._getLock key, namespace, (error) ", "end": 837, "score": 0.9784520268440247, "start": 811, "tag": "KEY", "value": "lock:web:#{namespace}:#{id" } ]
app/coffee/infrastructure/LockManager.coffee
dtu-compute/web-sharelatex
0
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "lock:web:#{namespace}:#{id}" LockManager._getLock key, namespace, (error) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree)->)-> rclient.set key, "locked", "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false _getLock: (key, namespace, callback = (error) ->) -> startTime = Date.now() attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null) else setTimeout attempt, LockManager.LOCK_TEST_INTERVAL _releaseLock: (key, callback)-> rclient.del key, callback
43887
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "<KEY>}" LockManager._getLock key, namespace, (error) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree)->)-> rclient.set key, "locked", "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false _getLock: (key, namespace, callback = (error) ->) -> startTime = Date.now() attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null) else setTimeout attempt, LockManager.LOCK_TEST_INTERVAL _releaseLock: (key, callback)-> rclient.del key, callback
true
metrics = require('metrics-sharelatex') Settings = require('settings-sharelatex') RedisWrapper = require("./RedisWrapper") rclient = RedisWrapper.client("lock") logger = require "logger-sharelatex" module.exports = LockManager = LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) -> # This error is defined here so we get a useful stacktrace slowExecutionError = new Error "slow execution during lock" timer = new metrics.Timer("lock.#{namespace}") key = "PI:KEY:<KEY>END_PI}" LockManager._getLock key, namespace, (error) -> return callback(error) if error? # The lock can expire in redis but the process carry on. This setTimout call # is designed to log if this happens. countIfExceededLockTimeout = () -> metrics.inc "lock.#{namespace}.exceeded_lock_timeout" logger.log "exceeded lock timeout", { namespace, id, slowExecutionError } exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 runner (error1, values...) -> LockManager._releaseLock key, (error2) -> clearTimeout exceededLockTimeout timeTaken = new Date - timer.start if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError } timer.done() error = error1 or error2 return callback(error) if error? callback null, values... _tryLock : (key, namespace, callback = (err, isFree)->)-> rclient.set key, "locked", "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)-> return callback(err) if err? if gotLock == "OK" metrics.inc "lock.#{namespace}.try.success" callback err, true else metrics.inc "lock.#{namespace}.try.failed" logger.log key: key, redis_response: gotLock, "lock is locked" callback err, false _getLock: (key, namespace, callback = (error) ->) -> startTime = Date.now() attempts = 0 do attempt = () -> if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME metrics.inc "lock.#{namespace}.get.failed" return callback(new Error("Timeout")) attempts += 1 LockManager._tryLock key, namespace, (error, gotLock) -> return callback(error) if error? if gotLock metrics.gauge "lock.#{namespace}.get.success.tries", attempts callback(null) else setTimeout attempt, LockManager.LOCK_TEST_INTERVAL _releaseLock: (key, callback)-> rclient.del key, callback