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": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apache Lice", "end": 30, "score": 0.9998809695243835, "start": 17, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apac...
mrfogg-front/app/coffee/plugins/i18next.coffee
PIWEEK/mrfogg
0
# Copyright 2013 Andrey Antukh <niwi@niwi.be> # # 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. I18NextDirective = ($parse, $rootScope) -> restrict: "A" link: (scope, elm, attrs) -> t = $rootScope.translate evaluateTranslation = -> element = angular.element(elm) for value in attrs.i18next.split(",") if value.indexOf(":") == -1 element.html(t(value)) else [ns, value] = value.split(":") element.attr(ns, t(value)) evaluateTranslation() $rootScope.$on "i18next:changeLang", -> evaluateTranslation() I18NextProvider = ($rootScope, $q) -> i18n.addPostProcessor "lodashTemplate", (value, key, options) -> template = _.template(value) return template(options.scope) service = {} service.defaultOptions = { postProcess: "lodashTemplate" fallbackLng: "en" useLocalStorage: false localStorageExpirationTime: 60*60*24*1000 # 1 day ns: 'app' resGetPath: 'locales/__lng__/__ns__.json' getAsync: false } service.setLang = (lang) -> $rootScope.currentLang = lang options = _.clone(service.defaultOptions, true) i18n.setLng lang, options, -> $rootScope.$broadcast("i18next:changeLang") service.getCurrentLang = -> return $rootScope.currentLang service.translate = (key, options)-> return $rootScope.t(key, options) service.t = service.translate service.initialize = (async=false, defaultLang="en") -> # Put to rootScope a initial values options = _.clone(service.defaultOptions, true) options.lng = $rootScope.currentLang = defaultLang if async options.getAsync = true defer = $q.defer() onI18nextInit = (t) -> $rootScope.$apply -> $rootScope.translate = t $rootScope.t = t defer.resolve(t) $rootScope.$broadcast("i18next:loadComplete", t) return defer.promise i18n.init(options, onI18nextInit) else i18n.init(options) $rootScope.translate = i18n.t $rootScope.t = i18n.t $rootScope.$broadcast("i18next:loadComplete", i18n.t) return service I18NextTranslateFilter = ($i18next) -> return (key, options) -> return $i18next.t(key, options) module = angular.module('i18next', []) module.factory("$i18next", ['$rootScope', '$q', I18NextProvider]) module.directive('i18next', ['$parse', '$rootScope', I18NextDirective]) module.filter('i18next', ['$i18next', I18NextTranslateFilter])
121586
# Copyright 2013 <NAME> <<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. I18NextDirective = ($parse, $rootScope) -> restrict: "A" link: (scope, elm, attrs) -> t = $rootScope.translate evaluateTranslation = -> element = angular.element(elm) for value in attrs.i18next.split(",") if value.indexOf(":") == -1 element.html(t(value)) else [ns, value] = value.split(":") element.attr(ns, t(value)) evaluateTranslation() $rootScope.$on "i18next:changeLang", -> evaluateTranslation() I18NextProvider = ($rootScope, $q) -> i18n.addPostProcessor "lodashTemplate", (value, key, options) -> template = _.template(value) return template(options.scope) service = {} service.defaultOptions = { postProcess: "lodashTemplate" fallbackLng: "en" useLocalStorage: false localStorageExpirationTime: 60*60*24*1000 # 1 day ns: 'app' resGetPath: 'locales/__lng__/__ns__.json' getAsync: false } service.setLang = (lang) -> $rootScope.currentLang = lang options = _.clone(service.defaultOptions, true) i18n.setLng lang, options, -> $rootScope.$broadcast("i18next:changeLang") service.getCurrentLang = -> return $rootScope.currentLang service.translate = (key, options)-> return $rootScope.t(key, options) service.t = service.translate service.initialize = (async=false, defaultLang="en") -> # Put to rootScope a initial values options = _.clone(service.defaultOptions, true) options.lng = $rootScope.currentLang = defaultLang if async options.getAsync = true defer = $q.defer() onI18nextInit = (t) -> $rootScope.$apply -> $rootScope.translate = t $rootScope.t = t defer.resolve(t) $rootScope.$broadcast("i18next:loadComplete", t) return defer.promise i18n.init(options, onI18nextInit) else i18n.init(options) $rootScope.translate = i18n.t $rootScope.t = i18n.t $rootScope.$broadcast("i18next:loadComplete", i18n.t) return service I18NextTranslateFilter = ($i18next) -> return (key, options) -> return $i18next.t(key, options) module = angular.module('i18next', []) module.factory("$i18next", ['$rootScope', '$q', I18NextProvider]) module.directive('i18next', ['$parse', '$rootScope', I18NextDirective]) module.filter('i18next', ['$i18next', I18NextTranslateFilter])
true
# Copyright 2013 PI:NAME:<NAME>END_PI <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. I18NextDirective = ($parse, $rootScope) -> restrict: "A" link: (scope, elm, attrs) -> t = $rootScope.translate evaluateTranslation = -> element = angular.element(elm) for value in attrs.i18next.split(",") if value.indexOf(":") == -1 element.html(t(value)) else [ns, value] = value.split(":") element.attr(ns, t(value)) evaluateTranslation() $rootScope.$on "i18next:changeLang", -> evaluateTranslation() I18NextProvider = ($rootScope, $q) -> i18n.addPostProcessor "lodashTemplate", (value, key, options) -> template = _.template(value) return template(options.scope) service = {} service.defaultOptions = { postProcess: "lodashTemplate" fallbackLng: "en" useLocalStorage: false localStorageExpirationTime: 60*60*24*1000 # 1 day ns: 'app' resGetPath: 'locales/__lng__/__ns__.json' getAsync: false } service.setLang = (lang) -> $rootScope.currentLang = lang options = _.clone(service.defaultOptions, true) i18n.setLng lang, options, -> $rootScope.$broadcast("i18next:changeLang") service.getCurrentLang = -> return $rootScope.currentLang service.translate = (key, options)-> return $rootScope.t(key, options) service.t = service.translate service.initialize = (async=false, defaultLang="en") -> # Put to rootScope a initial values options = _.clone(service.defaultOptions, true) options.lng = $rootScope.currentLang = defaultLang if async options.getAsync = true defer = $q.defer() onI18nextInit = (t) -> $rootScope.$apply -> $rootScope.translate = t $rootScope.t = t defer.resolve(t) $rootScope.$broadcast("i18next:loadComplete", t) return defer.promise i18n.init(options, onI18nextInit) else i18n.init(options) $rootScope.translate = i18n.t $rootScope.t = i18n.t $rootScope.$broadcast("i18next:loadComplete", i18n.t) return service I18NextTranslateFilter = ($i18next) -> return (key, options) -> return $i18next.t(key, options) module = angular.module('i18next', []) module.factory("$i18next", ['$rootScope', '$q', I18NextProvider]) module.directive('i18next', ['$parse', '$rootScope', I18NextDirective]) module.filter('i18next', ['$i18next', I18NextTranslateFilter])
[ { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach", "end": 35, "score": 0.9998103380203247, "start": 24, "tag": "NAME", "value": "Dan Elliott" }, { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed ...
clients/www/src/coffee/handler/isadore_settings_general_config_config.coffee
bluthen/isadore_server
0
# Copyright 2010-2019 Dan Elliott, Russell Valentine # # 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. class window.GeneralConfigConfig _template: '<div class="settings_general_config_config"><h1>General Config Config</h1><div class="gcc_json_editor" style="height: 700px"></div><button type="button">Save JSON</button><span class="save_status"></span></div>' constructor: ($parent) -> @_$selfdiv = $(@_template) $parent.append(@_$selfdiv) @_$editordiv = $('.gcc_json_editor', @_$selfdiv) @_editor = new JSONEditor(@_$editordiv[0], {modes: ['tree', 'code']}) @_$button = $('button', @_$selfdiv) @_$saveStatus = $('.save_status', @_$selfdiv) @_$button.click(() => @save() ) _showError: (e) -> $('#error_dialog').html("Error: "+e).dialog({ zIndex: 99999, modal: true, buttons: { Ok: () -> $(this).dialog('close'); } }) save: () -> #TODO: Put in some check so it is atleast somewhat valid. #TODO: Check for client_version existence data = @_editor.getText() try JSON.parse(data) catch err console.warn('GeneralConfigConfig syntax error in json while attempting to save') @_showError('Please fix JSON errors before saving.') #Save data #TODO: Make button spin @_$button.prop('disable', true); @_$saveStatus.text('Saving...').fadeIn(0) $.ajax({ url: '../resources/conf/general' type: 'PUT' dataType: 'text' data: {configs: data} success: (d) => #TODO: On save stop button spin @_$button.prop('disable', false); @_$saveStatus.text('Saved!').fadeIn(0).fadeOut(3000) error: (jq, txt, err) => @_$button.prop('disable', false); @_$saveStatus.text('Error Saving').fadeIn(0).fadeOut(3000) @_showError('Error saving General Config Config: '+ txt + " " + err) }) refresh: () -> @_$editordiv.hide() $.ajax({ url: '../resources/conf/general', type: 'GET', dataType: 'json', success: (d) => @_editor.setText(d.configs) @_$editordiv.show() error: (e) => data = "Failed to load config" @_editor.set(data) @_$editordiv.show() })
149864
# Copyright 2010-2019 <NAME>, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.GeneralConfigConfig _template: '<div class="settings_general_config_config"><h1>General Config Config</h1><div class="gcc_json_editor" style="height: 700px"></div><button type="button">Save JSON</button><span class="save_status"></span></div>' constructor: ($parent) -> @_$selfdiv = $(@_template) $parent.append(@_$selfdiv) @_$editordiv = $('.gcc_json_editor', @_$selfdiv) @_editor = new JSONEditor(@_$editordiv[0], {modes: ['tree', 'code']}) @_$button = $('button', @_$selfdiv) @_$saveStatus = $('.save_status', @_$selfdiv) @_$button.click(() => @save() ) _showError: (e) -> $('#error_dialog').html("Error: "+e).dialog({ zIndex: 99999, modal: true, buttons: { Ok: () -> $(this).dialog('close'); } }) save: () -> #TODO: Put in some check so it is atleast somewhat valid. #TODO: Check for client_version existence data = @_editor.getText() try JSON.parse(data) catch err console.warn('GeneralConfigConfig syntax error in json while attempting to save') @_showError('Please fix JSON errors before saving.') #Save data #TODO: Make button spin @_$button.prop('disable', true); @_$saveStatus.text('Saving...').fadeIn(0) $.ajax({ url: '../resources/conf/general' type: 'PUT' dataType: 'text' data: {configs: data} success: (d) => #TODO: On save stop button spin @_$button.prop('disable', false); @_$saveStatus.text('Saved!').fadeIn(0).fadeOut(3000) error: (jq, txt, err) => @_$button.prop('disable', false); @_$saveStatus.text('Error Saving').fadeIn(0).fadeOut(3000) @_showError('Error saving General Config Config: '+ txt + " " + err) }) refresh: () -> @_$editordiv.hide() $.ajax({ url: '../resources/conf/general', type: 'GET', dataType: 'json', success: (d) => @_editor.setText(d.configs) @_$editordiv.show() error: (e) => data = "Failed to load config" @_editor.set(data) @_$editordiv.show() })
true
# Copyright 2010-2019 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.GeneralConfigConfig _template: '<div class="settings_general_config_config"><h1>General Config Config</h1><div class="gcc_json_editor" style="height: 700px"></div><button type="button">Save JSON</button><span class="save_status"></span></div>' constructor: ($parent) -> @_$selfdiv = $(@_template) $parent.append(@_$selfdiv) @_$editordiv = $('.gcc_json_editor', @_$selfdiv) @_editor = new JSONEditor(@_$editordiv[0], {modes: ['tree', 'code']}) @_$button = $('button', @_$selfdiv) @_$saveStatus = $('.save_status', @_$selfdiv) @_$button.click(() => @save() ) _showError: (e) -> $('#error_dialog').html("Error: "+e).dialog({ zIndex: 99999, modal: true, buttons: { Ok: () -> $(this).dialog('close'); } }) save: () -> #TODO: Put in some check so it is atleast somewhat valid. #TODO: Check for client_version existence data = @_editor.getText() try JSON.parse(data) catch err console.warn('GeneralConfigConfig syntax error in json while attempting to save') @_showError('Please fix JSON errors before saving.') #Save data #TODO: Make button spin @_$button.prop('disable', true); @_$saveStatus.text('Saving...').fadeIn(0) $.ajax({ url: '../resources/conf/general' type: 'PUT' dataType: 'text' data: {configs: data} success: (d) => #TODO: On save stop button spin @_$button.prop('disable', false); @_$saveStatus.text('Saved!').fadeIn(0).fadeOut(3000) error: (jq, txt, err) => @_$button.prop('disable', false); @_$saveStatus.text('Error Saving').fadeIn(0).fadeOut(3000) @_showError('Error saving General Config Config: '+ txt + " " + err) }) refresh: () -> @_$editordiv.hide() $.ajax({ url: '../resources/conf/general', type: 'GET', dataType: 'json', success: (d) => @_editor.setText(d.configs) @_$editordiv.show() error: (e) => data = "Failed to load config" @_editor.set(data) @_$editordiv.show() })
[ { "context": "unt (default 5)\n#\n# Notes\n# None\n#\n# Author:\n# Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize)\n\n", "end": 580, "score": 0.999879777431488, "start": 564, "tag": "NAME", "value": "Morgan Wigmanich" }, { "context": " Notes\n# None\n#\n# Autho...
src/garble.coffee
okize/hubot-garble
1
# Description: # Garbles your text # # Dependencies: # None # # Configuration: # YANDEX_TRANSLATE_API_KEY string; a Yandex API key (required) # HUBOT_GARBLE_LOCAL_LANGUAGE string; language code for chatroom language (optional; default is 'en') # HUBOT_GARBLE_TRANSLATION_PATH_LOG boolean; display the translation path that text followed during garbling process (optional; default is true) # # Commands: # hubot garble [1 - 9] <text> - garbles your text by [least - most] amount (default 5) # # Notes # None # # Author: # Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize) querystring = require('querystring') _ = require('lodash') Promise = require('bluebird') request = Promise.promisify(require('request')) LANGUAGES = require('./data/languages.json') TRANSLATE_URI = 'https://translate.yandex.net/api/v1.5/tr.json/translate' API_KEY = process.env.YANDEX_TRANSLATE_API_KEY LOCAL_LANGUAGE = process.env.HUBOT_GARBLE_LOCAL_LANGUAGE || 'en' DISPLAY_TRANSLATION_PATH = process.env.HUBOT_GARBLE_TRANSLATION_PATH_LOG || true DEFAULT_GARBLE_AMOUNT = 5 # get full language name from a language code getLanguageName = (languageCode) -> _.result(_.find(LANGUAGES, 'code', languageCode), 'language') # an array of all available language codes except LOCAL_LANGUAGE getLanguageCodes = () -> _.chain(LANGUAGES).pluck('code').pull(LOCAL_LANGUAGE).value() # an array of random languages; length determined by garbling amount getRandomLanguages = (languageCodes, garbleAmount) -> _.times garbleAmount, () -> lang = _.sample(languageCodes) _.pull(languageCodes, lang) lang # an array of languages to translate text through # wraps LOCAL_LANGUAGE around random assortment of languages getTranslationPath = (garbleAmount) -> path = _.chain(getRandomLanguages(getLanguageCodes(), garbleAmount)) .unshift(LOCAL_LANGUAGE) .push(LOCAL_LANGUAGE) .value() # no doubt there is a better way to do this pairs = _.chain(path) .map((lang, i) -> [lang, path[i+1]]) .dropRight(1) .value() # a string that indicates what "translation path" the text was passed through getTranslationPathLog = (languageCodes) -> languageNames = _.map languageCodes, (code) -> getLanguageName(code[0]) languageNames.push(getLanguageName(LOCAL_LANGUAGE)) "translation path: #{languageNames.join(' → ')}" # a URI that satisfies the Yandex API requirements getRequestURI = (langFrom, langTo, text) -> opts = key: API_KEY lang: "#{langFrom}-#{langTo}" text: text return "#{TRANSLATE_URI}?#{querystring.stringify(opts)}" # returns request promise getTranslation = (fromLang, toLang, text) -> request getRequestURI(fromLang, toLang, text) # a string of translated text parseResponse = (str) -> try return JSON.parse(str).text[0] catch e return str module.exports = (robot) -> robot.respond /garble (.*)/i, (msg) -> text = msg.match[1]?.trim() regex = /^\d+\s*/ garbleAmount = regex.exec(text) if garbleAmount? amount = parseInt(garbleAmount[0], 10) garbleAmount = if (1 <= amount <= 9) then amount else DEFAULT_GARBLE_AMOUNT text = text.replace(regex, '') else garbleAmount = DEFAULT_GARBLE_AMOUNT langs = getTranslationPath(garbleAmount) Promise.reduce(langs, ((text, languagePair) -> getTranslation(languagePair[0], languagePair[1], text).then (response) -> return parseResponse(response[1]) ), text).then (text) -> msg.send text unless DISPLAY_TRANSLATION_PATH == 'false' msg.send getTranslationPathLog(langs)
94882
# Description: # Garbles your text # # Dependencies: # None # # Configuration: # YANDEX_TRANSLATE_API_KEY string; a Yandex API key (required) # HUBOT_GARBLE_LOCAL_LANGUAGE string; language code for chatroom language (optional; default is 'en') # HUBOT_GARBLE_TRANSLATION_PATH_LOG boolean; display the translation path that text followed during garbling process (optional; default is true) # # Commands: # hubot garble [1 - 9] <text> - garbles your text by [least - most] amount (default 5) # # Notes # None # # Author: # <NAME> <<EMAIL>> (https://github.com/okize) querystring = require('querystring') _ = require('lodash') Promise = require('bluebird') request = Promise.promisify(require('request')) LANGUAGES = require('./data/languages.json') TRANSLATE_URI = 'https://translate.yandex.net/api/v1.5/tr.json/translate' API_KEY = process.env.YANDEX_TRANSLATE_API_KEY LOCAL_LANGUAGE = process.env.HUBOT_GARBLE_LOCAL_LANGUAGE || 'en' DISPLAY_TRANSLATION_PATH = process.env.HUBOT_GARBLE_TRANSLATION_PATH_LOG || true DEFAULT_GARBLE_AMOUNT = 5 # get full language name from a language code getLanguageName = (languageCode) -> _.result(_.find(LANGUAGES, 'code', languageCode), 'language') # an array of all available language codes except LOCAL_LANGUAGE getLanguageCodes = () -> _.chain(LANGUAGES).pluck('code').pull(LOCAL_LANGUAGE).value() # an array of random languages; length determined by garbling amount getRandomLanguages = (languageCodes, garbleAmount) -> _.times garbleAmount, () -> lang = _.sample(languageCodes) _.pull(languageCodes, lang) lang # an array of languages to translate text through # wraps LOCAL_LANGUAGE around random assortment of languages getTranslationPath = (garbleAmount) -> path = _.chain(getRandomLanguages(getLanguageCodes(), garbleAmount)) .unshift(LOCAL_LANGUAGE) .push(LOCAL_LANGUAGE) .value() # no doubt there is a better way to do this pairs = _.chain(path) .map((lang, i) -> [lang, path[i+1]]) .dropRight(1) .value() # a string that indicates what "translation path" the text was passed through getTranslationPathLog = (languageCodes) -> languageNames = _.map languageCodes, (code) -> getLanguageName(code[0]) languageNames.push(getLanguageName(LOCAL_LANGUAGE)) "translation path: #{languageNames.join(' → ')}" # a URI that satisfies the Yandex API requirements getRequestURI = (langFrom, langTo, text) -> opts = key: API_KEY lang: "#{langFrom}-#{langTo}" text: text return "#{TRANSLATE_URI}?#{querystring.stringify(opts)}" # returns request promise getTranslation = (fromLang, toLang, text) -> request getRequestURI(fromLang, toLang, text) # a string of translated text parseResponse = (str) -> try return JSON.parse(str).text[0] catch e return str module.exports = (robot) -> robot.respond /garble (.*)/i, (msg) -> text = msg.match[1]?.trim() regex = /^\d+\s*/ garbleAmount = regex.exec(text) if garbleAmount? amount = parseInt(garbleAmount[0], 10) garbleAmount = if (1 <= amount <= 9) then amount else DEFAULT_GARBLE_AMOUNT text = text.replace(regex, '') else garbleAmount = DEFAULT_GARBLE_AMOUNT langs = getTranslationPath(garbleAmount) Promise.reduce(langs, ((text, languagePair) -> getTranslation(languagePair[0], languagePair[1], text).then (response) -> return parseResponse(response[1]) ), text).then (text) -> msg.send text unless DISPLAY_TRANSLATION_PATH == 'false' msg.send getTranslationPathLog(langs)
true
# Description: # Garbles your text # # Dependencies: # None # # Configuration: # YANDEX_TRANSLATE_API_KEY string; a Yandex API key (required) # HUBOT_GARBLE_LOCAL_LANGUAGE string; language code for chatroom language (optional; default is 'en') # HUBOT_GARBLE_TRANSLATION_PATH_LOG boolean; display the translation path that text followed during garbling process (optional; default is true) # # Commands: # hubot garble [1 - 9] <text> - garbles your text by [least - most] amount (default 5) # # Notes # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/okize) querystring = require('querystring') _ = require('lodash') Promise = require('bluebird') request = Promise.promisify(require('request')) LANGUAGES = require('./data/languages.json') TRANSLATE_URI = 'https://translate.yandex.net/api/v1.5/tr.json/translate' API_KEY = process.env.YANDEX_TRANSLATE_API_KEY LOCAL_LANGUAGE = process.env.HUBOT_GARBLE_LOCAL_LANGUAGE || 'en' DISPLAY_TRANSLATION_PATH = process.env.HUBOT_GARBLE_TRANSLATION_PATH_LOG || true DEFAULT_GARBLE_AMOUNT = 5 # get full language name from a language code getLanguageName = (languageCode) -> _.result(_.find(LANGUAGES, 'code', languageCode), 'language') # an array of all available language codes except LOCAL_LANGUAGE getLanguageCodes = () -> _.chain(LANGUAGES).pluck('code').pull(LOCAL_LANGUAGE).value() # an array of random languages; length determined by garbling amount getRandomLanguages = (languageCodes, garbleAmount) -> _.times garbleAmount, () -> lang = _.sample(languageCodes) _.pull(languageCodes, lang) lang # an array of languages to translate text through # wraps LOCAL_LANGUAGE around random assortment of languages getTranslationPath = (garbleAmount) -> path = _.chain(getRandomLanguages(getLanguageCodes(), garbleAmount)) .unshift(LOCAL_LANGUAGE) .push(LOCAL_LANGUAGE) .value() # no doubt there is a better way to do this pairs = _.chain(path) .map((lang, i) -> [lang, path[i+1]]) .dropRight(1) .value() # a string that indicates what "translation path" the text was passed through getTranslationPathLog = (languageCodes) -> languageNames = _.map languageCodes, (code) -> getLanguageName(code[0]) languageNames.push(getLanguageName(LOCAL_LANGUAGE)) "translation path: #{languageNames.join(' → ')}" # a URI that satisfies the Yandex API requirements getRequestURI = (langFrom, langTo, text) -> opts = key: API_KEY lang: "#{langFrom}-#{langTo}" text: text return "#{TRANSLATE_URI}?#{querystring.stringify(opts)}" # returns request promise getTranslation = (fromLang, toLang, text) -> request getRequestURI(fromLang, toLang, text) # a string of translated text parseResponse = (str) -> try return JSON.parse(str).text[0] catch e return str module.exports = (robot) -> robot.respond /garble (.*)/i, (msg) -> text = msg.match[1]?.trim() regex = /^\d+\s*/ garbleAmount = regex.exec(text) if garbleAmount? amount = parseInt(garbleAmount[0], 10) garbleAmount = if (1 <= amount <= 9) then amount else DEFAULT_GARBLE_AMOUNT text = text.replace(regex, '') else garbleAmount = DEFAULT_GARBLE_AMOUNT langs = getTranslationPath(garbleAmount) Promise.reduce(langs, ((text, languagePair) -> getTranslation(languagePair[0], languagePair[1], text).then (response) -> return parseResponse(response[1]) ), text).then (text) -> msg.send text unless DISPLAY_TRANSLATION_PATH == 'false' msg.send getTranslationPathLog(langs)
[ { "context": "###\r\n// ==UserScript==\r\n// @name Silent B\r\n// @namespace https://github.com/hentaiPand", "end": 51, "score": 0.9995946884155273, "start": 43, "tag": "NAME", "value": "Silent B" }, { "context": " Silent B\r\n// @namespace https://github.com/hen...
Silent B/silentb_4672.20.coffee
hentaiPanda/GM_Scripts
1
### // ==UserScript== // @name Silent B // @namespace https://github.com/hentaiPanda // @description 隐藏指定的超展开列表项目,等等 // @author niR // @version 4672.20 pre Bismark // @license MIT License // @encoding utf-8 // @require http://code.jquery.com/jquery-2.1.1.js // @grant GM_getValue // @grant GM_setValue // @include http://bgm.tv/rakuen/topiclist // @include http://bangumi.tv/rakuen/topiclist // @include http://chii.in/rakuen/topiclist // @include http://bgm.tv/ // @include http://bangumi.tv/ // @include http://chii.in/ // @include /^http://bgm\.tv/subject/[0-9]+/ // @include /^http://bangumi\.tv/subject/[0-9]+/ // @include /^http://chii\.in/subject/[0-9]+/ // @include http://bgm.tv/subject_search/* // @include http://bangumi.tv/subject_search/* // @include http://chii.in/subject_search/* // @include /^http://bgm\.tv/(anime|book|music|real)/browser/ // @include /^http://bangumi\.tv/(anime|book|music|real)/browser/ // @include /^http://chii\.in/(anime|book|music|real)/browser/ // @include /^http://bgm\.tv/group/(?!topic).+/ // @include /^http://bangumi.tv/group/(?!topic).+/ // @include /^http://chii.in/group/(?!topic).+/ // @include http://bgm.tv/settings* // @include http://bangumi.tv/settings* // @include http://chii.in/settings* // ==/UserScript== ### getParentNode = (node, level) -> i = level - 1 pn = node.parentNode if level is 0 return node while i > 0 pn = pn.parentNode i -= 1 return pn # +++++ rakuen topiclist +++++ START +++++ # addBtn = -> $('li.item_list > div.inner > span.row').each -> x_btn = '<span class="xlihil"><a href="javascript:;">[X]</a></span>' @.innerHTML = @.innerHTML + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItem(evt.target) removeItem = (node) -> item = getParentNode(node, 4) GM_setValue(item.id, true) # 联动 tpcid = item.id.split("item_group_")[1] console.log tpcid GM_setValue("/group/topic/" + tpcid, true) item.outerHTML = '' initItemList = -> flag = false $('li.item_list').each -> if GM_getValue(@.id, false) @.outerHTML = '' flag = true return flag # +++++ rakuen topiclist +++++ END +++++ # # +++++ home page +++++ START +++++ # addBtnHome = -> $('div#home_subject_tpc a.l, div#home_grp_tpc a.l:not(.rr)').each -> return if $(@).attr("href").startsWith("/group/my") x_btn = '<a class="xlihil" href="javascript:;">[X]</a>' # console.log $(@).attr("href") $(@).next().html (i, old) -> return old + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemHome(evt.target) removeItemHome = (node) -> itemhref = $(node).parents().eq(0).prev().attr("href") # console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListHome = -> flag = false $('div#home_subject_tpc a.l, div#home_grp_tpc a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ home page +++++ END +++++ # # +++++ group page +++++ START +++++ # addBtnGroup = -> $('table.topic_list td.subject').each -> # return if $(@).attr("href").startsWith("/group/my") x_btn = '<small class="grey">\ <a class="xlihil" href="javascript:;">[X] </a></small>' $(@).html (i, old) -> return x_btn + old $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemGroup(evt.target) removeItemGroup = (node) -> itemhref = $(node).parent().next().attr("href") console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListGroup = -> flag = false $('table.topic_list td.subject a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ group page +++++ END +++++ # # rakuen/topiclist refreshList = -> i = true $('li.item_list').each -> return if @.style.display if i @.className = 'line_odd item_list' else @.className = 'line_even item_list' i = not i console.log @.id # homepage refreshIndexList = (klasslist, klass, subklass) -> $(klass).each -> swch = true sub_item = $(@).find(subklass) return if not sub_item.length sub_item.each -> if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return 1 return true # group refreshTopicList = (klasslist, klass) -> swch = true $(klass).each -> return if @.style.display if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return true # +++++ subject page +++++ START +++++ # # Hide Tsukkomi @Bangumi hideTsukkomi = (swch) -> return unless swch $("#comment_box").remove() # +++++ subject page +++++ END +++++ # # +++++ ratings +++++ START +++++ # # Hide Ratings @Bangumi hideRating = (swch) -> return unless swch $("#ChartWarpper, #columnSubjectInHomeB .global_rating").remove() hideRank = (swch) -> return unless swch $("#browserItemList span.rank, #browserItemList p.rateInfo").remove() # +++++ ratings +++++ END +++++ # # setting addSettingBtn = -> $(".secTab").html (i, old) -> return '''<li><a href="javascript:;" id="sb_setting">\ <span>STB设置</span></a></li>''' + old $('body').off 'click.sb_setting' $('body').on 'click.sb_setting', '#sb_setting', -> sbsetting() updateTsuRtg = (node) -> switch node.id when "rtg_yes" then GM_setValue("hiderating", true) when "rtg_no" then GM_setValue("hiderating", false) when "tsu_yes" then GM_setValue("hidetsukkomi", true) when "tsu_no" then GM_setValue("hidetsukkomi", false) else return false checkTsuRtg = -> defaultval = true flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) if flagrtg $("#rtg_yes")[0].checked = true else $("#rtg_no")[0].checked = true if flagtsu $("#tsu_yes")[0].checked = true else $("#tsu_no")[0].checked = true sbsetting = -> $("#columnB").css("display", "none") $("#header > h1").html (i, old) -> return "STB设置" $(".secTab > li > a").removeClass("selected") $("#sb_setting").addClass("selected") newcolumn = '<span class="text">\ <table class="settings" cellpadding="5" cellspacing="0" \ align="center" width="98%">\ <tbody>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏评分信息</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_no" type="radio"></td></tr>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏概览页吐槽箱</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_no" type="radio"></td></tr>\ </tbody></span>' $("#columnA").html(newcolumn) checkTsuRtg() $('body').off 'click.sb_input' $('body').on 'click.sb_input', 'input.stb', (evt) -> updateTsuRtg(evt.target) main = -> defaultval = true path = location.pathname regPatt = "/$" : -> # 首页 console.log "http://bangumi.tv" # 首页热门讨论和小组话题 flag = initItemListHome() addBtnHome() if flag refreshIndexList( ['line_odd clearit', 'line_even clearit'],'.sideTpcList', 'li') "/rakuen/topiclist" : -> console.log "/rakuen" flag = initItemList() refreshList() if flag addBtn() "/subject/[0-9]+$" : -> flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) hideTsukkomi(flagtsu) hideRating(flagrtg) "/subject_search/.*" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/(anime|book|music|real)/browser" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/group/(?!topic).+" : -> flag = initItemListGroup() addBtnGroup() if flag refreshTopicList(['topic odd', 'topic even'], '.topic') "/settings" : -> console.log "/settings" addSettingBtn(); for i in Object.keys(regPatt) if RegExp(i).test(path) regPatt[i]() main()
189951
### // ==UserScript== // @name <NAME> // @namespace https://github.com/hentaiPanda // @description 隐藏指定的超展开列表项目,等等 // @author niR // @version 4672.20 pre Bismark // @license MIT License // @encoding utf-8 // @require http://code.jquery.com/jquery-2.1.1.js // @grant GM_getValue // @grant GM_setValue // @include http://bgm.tv/rakuen/topiclist // @include http://bangumi.tv/rakuen/topiclist // @include http://chii.in/rakuen/topiclist // @include http://bgm.tv/ // @include http://bangumi.tv/ // @include http://chii.in/ // @include /^http://bgm\.tv/subject/[0-9]+/ // @include /^http://bangumi\.tv/subject/[0-9]+/ // @include /^http://chii\.in/subject/[0-9]+/ // @include http://bgm.tv/subject_search/* // @include http://bangumi.tv/subject_search/* // @include http://chii.in/subject_search/* // @include /^http://bgm\.tv/(anime|book|music|real)/browser/ // @include /^http://bangumi\.tv/(anime|book|music|real)/browser/ // @include /^http://chii\.in/(anime|book|music|real)/browser/ // @include /^http://bgm\.tv/group/(?!topic).+/ // @include /^http://bangumi.tv/group/(?!topic).+/ // @include /^http://chii.in/group/(?!topic).+/ // @include http://bgm.tv/settings* // @include http://bangumi.tv/settings* // @include http://chii.in/settings* // ==/UserScript== ### getParentNode = (node, level) -> i = level - 1 pn = node.parentNode if level is 0 return node while i > 0 pn = pn.parentNode i -= 1 return pn # +++++ rakuen topiclist +++++ START +++++ # addBtn = -> $('li.item_list > div.inner > span.row').each -> x_btn = '<span class="xlihil"><a href="javascript:;">[X]</a></span>' @.innerHTML = @.innerHTML + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItem(evt.target) removeItem = (node) -> item = getParentNode(node, 4) GM_setValue(item.id, true) # 联动 tpcid = item.id.split("item_group_")[1] console.log tpcid GM_setValue("/group/topic/" + tpcid, true) item.outerHTML = '' initItemList = -> flag = false $('li.item_list').each -> if GM_getValue(@.id, false) @.outerHTML = '' flag = true return flag # +++++ rakuen topiclist +++++ END +++++ # # +++++ home page +++++ START +++++ # addBtnHome = -> $('div#home_subject_tpc a.l, div#home_grp_tpc a.l:not(.rr)').each -> return if $(@).attr("href").startsWith("/group/my") x_btn = '<a class="xlihil" href="javascript:;">[X]</a>' # console.log $(@).attr("href") $(@).next().html (i, old) -> return old + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemHome(evt.target) removeItemHome = (node) -> itemhref = $(node).parents().eq(0).prev().attr("href") # console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListHome = -> flag = false $('div#home_subject_tpc a.l, div#home_grp_tpc a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ home page +++++ END +++++ # # +++++ group page +++++ START +++++ # addBtnGroup = -> $('table.topic_list td.subject').each -> # return if $(@).attr("href").startsWith("/group/my") x_btn = '<small class="grey">\ <a class="xlihil" href="javascript:;">[X] </a></small>' $(@).html (i, old) -> return x_btn + old $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemGroup(evt.target) removeItemGroup = (node) -> itemhref = $(node).parent().next().attr("href") console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListGroup = -> flag = false $('table.topic_list td.subject a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ group page +++++ END +++++ # # rakuen/topiclist refreshList = -> i = true $('li.item_list').each -> return if @.style.display if i @.className = 'line_odd item_list' else @.className = 'line_even item_list' i = not i console.log @.id # homepage refreshIndexList = (klasslist, klass, subklass) -> $(klass).each -> swch = true sub_item = $(@).find(subklass) return if not sub_item.length sub_item.each -> if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return 1 return true # group refreshTopicList = (klasslist, klass) -> swch = true $(klass).each -> return if @.style.display if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return true # +++++ subject page +++++ START +++++ # # Hide Tsukkomi @Bangumi hideTsukkomi = (swch) -> return unless swch $("#comment_box").remove() # +++++ subject page +++++ END +++++ # # +++++ ratings +++++ START +++++ # # Hide Ratings @Bangumi hideRating = (swch) -> return unless swch $("#ChartWarpper, #columnSubjectInHomeB .global_rating").remove() hideRank = (swch) -> return unless swch $("#browserItemList span.rank, #browserItemList p.rateInfo").remove() # +++++ ratings +++++ END +++++ # # setting addSettingBtn = -> $(".secTab").html (i, old) -> return '''<li><a href="javascript:;" id="sb_setting">\ <span>STB设置</span></a></li>''' + old $('body').off 'click.sb_setting' $('body').on 'click.sb_setting', '#sb_setting', -> sbsetting() updateTsuRtg = (node) -> switch node.id when "rtg_yes" then GM_setValue("hiderating", true) when "rtg_no" then GM_setValue("hiderating", false) when "tsu_yes" then GM_setValue("hidetsukkomi", true) when "tsu_no" then GM_setValue("hidetsukkomi", false) else return false checkTsuRtg = -> defaultval = true flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) if flagrtg $("#rtg_yes")[0].checked = true else $("#rtg_no")[0].checked = true if flagtsu $("#tsu_yes")[0].checked = true else $("#tsu_no")[0].checked = true sbsetting = -> $("#columnB").css("display", "none") $("#header > h1").html (i, old) -> return "STB设置" $(".secTab > li > a").removeClass("selected") $("#sb_setting").addClass("selected") newcolumn = '<span class="text">\ <table class="settings" cellpadding="5" cellspacing="0" \ align="center" width="98%">\ <tbody>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏评分信息</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_no" type="radio"></td></tr>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏概览页吐槽箱</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_no" type="radio"></td></tr>\ </tbody></span>' $("#columnA").html(newcolumn) checkTsuRtg() $('body').off 'click.sb_input' $('body').on 'click.sb_input', 'input.stb', (evt) -> updateTsuRtg(evt.target) main = -> defaultval = true path = location.pathname regPatt = "/$" : -> # 首页 console.log "http://bangumi.tv" # 首页热门讨论和小组话题 flag = initItemListHome() addBtnHome() if flag refreshIndexList( ['line_odd clearit', 'line_even clearit'],'.sideTpcList', 'li') "/rakuen/topiclist" : -> console.log "/rakuen" flag = initItemList() refreshList() if flag addBtn() "/subject/[0-9]+$" : -> flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) hideTsukkomi(flagtsu) hideRating(flagrtg) "/subject_search/.*" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/(anime|book|music|real)/browser" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/group/(?!topic).+" : -> flag = initItemListGroup() addBtnGroup() if flag refreshTopicList(['topic odd', 'topic even'], '.topic') "/settings" : -> console.log "/settings" addSettingBtn(); for i in Object.keys(regPatt) if RegExp(i).test(path) regPatt[i]() main()
true
### // ==UserScript== // @name PI:NAME:<NAME>END_PI // @namespace https://github.com/hentaiPanda // @description 隐藏指定的超展开列表项目,等等 // @author niR // @version 4672.20 pre Bismark // @license MIT License // @encoding utf-8 // @require http://code.jquery.com/jquery-2.1.1.js // @grant GM_getValue // @grant GM_setValue // @include http://bgm.tv/rakuen/topiclist // @include http://bangumi.tv/rakuen/topiclist // @include http://chii.in/rakuen/topiclist // @include http://bgm.tv/ // @include http://bangumi.tv/ // @include http://chii.in/ // @include /^http://bgm\.tv/subject/[0-9]+/ // @include /^http://bangumi\.tv/subject/[0-9]+/ // @include /^http://chii\.in/subject/[0-9]+/ // @include http://bgm.tv/subject_search/* // @include http://bangumi.tv/subject_search/* // @include http://chii.in/subject_search/* // @include /^http://bgm\.tv/(anime|book|music|real)/browser/ // @include /^http://bangumi\.tv/(anime|book|music|real)/browser/ // @include /^http://chii\.in/(anime|book|music|real)/browser/ // @include /^http://bgm\.tv/group/(?!topic).+/ // @include /^http://bangumi.tv/group/(?!topic).+/ // @include /^http://chii.in/group/(?!topic).+/ // @include http://bgm.tv/settings* // @include http://bangumi.tv/settings* // @include http://chii.in/settings* // ==/UserScript== ### getParentNode = (node, level) -> i = level - 1 pn = node.parentNode if level is 0 return node while i > 0 pn = pn.parentNode i -= 1 return pn # +++++ rakuen topiclist +++++ START +++++ # addBtn = -> $('li.item_list > div.inner > span.row').each -> x_btn = '<span class="xlihil"><a href="javascript:;">[X]</a></span>' @.innerHTML = @.innerHTML + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItem(evt.target) removeItem = (node) -> item = getParentNode(node, 4) GM_setValue(item.id, true) # 联动 tpcid = item.id.split("item_group_")[1] console.log tpcid GM_setValue("/group/topic/" + tpcid, true) item.outerHTML = '' initItemList = -> flag = false $('li.item_list').each -> if GM_getValue(@.id, false) @.outerHTML = '' flag = true return flag # +++++ rakuen topiclist +++++ END +++++ # # +++++ home page +++++ START +++++ # addBtnHome = -> $('div#home_subject_tpc a.l, div#home_grp_tpc a.l:not(.rr)').each -> return if $(@).attr("href").startsWith("/group/my") x_btn = '<a class="xlihil" href="javascript:;">[X]</a>' # console.log $(@).attr("href") $(@).next().html (i, old) -> return old + x_btn $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemHome(evt.target) removeItemHome = (node) -> itemhref = $(node).parents().eq(0).prev().attr("href") # console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListHome = -> flag = false $('div#home_subject_tpc a.l, div#home_grp_tpc a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ home page +++++ END +++++ # # +++++ group page +++++ START +++++ # addBtnGroup = -> $('table.topic_list td.subject').each -> # return if $(@).attr("href").startsWith("/group/my") x_btn = '<small class="grey">\ <a class="xlihil" href="javascript:;">[X] </a></small>' $(@).html (i, old) -> return x_btn + old $('body').on 'click.removeli', '.xlihil', (evt) -> removeItemGroup(evt.target) removeItemGroup = (node) -> itemhref = $(node).parent().next().attr("href") console.log itemhref GM_setValue(itemhref, true) # 联动 tpcid = itemhref.split("/group/topic/")[1] console.log tpcid GM_setValue("item_group_" + tpcid, true) $(node).parents().eq(2).remove() initItemListGroup = -> flag = false $('table.topic_list td.subject a.l').each -> href = $(@).attr("href") # console.log href if GM_getValue(href, false) $(@).parents().eq(1).remove() flag = true return flag # +++++ group page +++++ END +++++ # # rakuen/topiclist refreshList = -> i = true $('li.item_list').each -> return if @.style.display if i @.className = 'line_odd item_list' else @.className = 'line_even item_list' i = not i console.log @.id # homepage refreshIndexList = (klasslist, klass, subklass) -> $(klass).each -> swch = true sub_item = $(@).find(subklass) return if not sub_item.length sub_item.each -> if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return 1 return true # group refreshTopicList = (klasslist, klass) -> swch = true $(klass).each -> return if @.style.display if swch @.className = klasslist[0] else @.className = klasslist[1] swch = not swch return 1 return true # +++++ subject page +++++ START +++++ # # Hide Tsukkomi @Bangumi hideTsukkomi = (swch) -> return unless swch $("#comment_box").remove() # +++++ subject page +++++ END +++++ # # +++++ ratings +++++ START +++++ # # Hide Ratings @Bangumi hideRating = (swch) -> return unless swch $("#ChartWarpper, #columnSubjectInHomeB .global_rating").remove() hideRank = (swch) -> return unless swch $("#browserItemList span.rank, #browserItemList p.rateInfo").remove() # +++++ ratings +++++ END +++++ # # setting addSettingBtn = -> $(".secTab").html (i, old) -> return '''<li><a href="javascript:;" id="sb_setting">\ <span>STB设置</span></a></li>''' + old $('body').off 'click.sb_setting' $('body').on 'click.sb_setting', '#sb_setting', -> sbsetting() updateTsuRtg = (node) -> switch node.id when "rtg_yes" then GM_setValue("hiderating", true) when "rtg_no" then GM_setValue("hiderating", false) when "tsu_yes" then GM_setValue("hidetsukkomi", true) when "tsu_no" then GM_setValue("hidetsukkomi", false) else return false checkTsuRtg = -> defaultval = true flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) if flagrtg $("#rtg_yes")[0].checked = true else $("#rtg_no")[0].checked = true if flagtsu $("#tsu_yes")[0].checked = true else $("#tsu_no")[0].checked = true sbsetting = -> $("#columnB").css("display", "none") $("#header > h1").html (i, old) -> return "STB设置" $(".secTab > li > a").removeClass("selected") $("#sb_setting").addClass("selected") newcolumn = '<span class="text">\ <table class="settings" cellpadding="5" cellspacing="0" \ align="center" width="98%">\ <tbody>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏评分信息</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="rtg_radio" class="stb" \ id="rtg_no" type="radio"></td></tr>\ <tr><td valign="top" width="12%">\ <h2 class="subtitle">隐藏概览页吐槽箱</h2></td>\ <td valign="top"></td></tr>\ <tr><td valign="top" width="20%">是</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_yes" type="radio"></td></tr>\ <tr><td valign="top" width="20%">否</td>\ <td valign="top"><input name="tsu_radio" class="stb" \ id="tsu_no" type="radio"></td></tr>\ </tbody></span>' $("#columnA").html(newcolumn) checkTsuRtg() $('body').off 'click.sb_input' $('body').on 'click.sb_input', 'input.stb', (evt) -> updateTsuRtg(evt.target) main = -> defaultval = true path = location.pathname regPatt = "/$" : -> # 首页 console.log "http://bangumi.tv" # 首页热门讨论和小组话题 flag = initItemListHome() addBtnHome() if flag refreshIndexList( ['line_odd clearit', 'line_even clearit'],'.sideTpcList', 'li') "/rakuen/topiclist" : -> console.log "/rakuen" flag = initItemList() refreshList() if flag addBtn() "/subject/[0-9]+$" : -> flagtsu = GM_getValue("hidetsukkomi", defaultval) flagrtg = GM_getValue("hiderating", defaultval) hideTsukkomi(flagtsu) hideRating(flagrtg) "/subject_search/.*" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/(anime|book|music|real)/browser" : -> flagrtg = GM_getValue("hiderating", defaultval) hideRank(flagrtg) "/group/(?!topic).+" : -> flag = initItemListGroup() addBtnGroup() if flag refreshTopicList(['topic odd', 'topic even'], '.topic') "/settings" : -> console.log "/settings" addSettingBtn(); for i in Object.keys(regPatt) if RegExp(i).test(path) regPatt[i]() main()
[ { "context": "om, automatically generated\n# Generator created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'execute", "end": 78, "score": 0.9982182383537292, "start": 72, "tag": "NAME", "value": "Renato" }, { "context": "atically generated\n# Generator created by Renato ...
snippets/YSF.cson
Wuzi/language-pawn
4
# YSF Snippets for Atom, automatically generated # Generator created by Renato "Hii" Garcia '.source.pwn, .source.inc': 'execute': 'prefix': 'execute' 'body': 'execute(${1:const command[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ffind': 'prefix': 'ffind' 'body': 'ffind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'frename': 'prefix': 'frename' 'body': 'frename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dfind': 'prefix': 'dfind' 'body': 'dfind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dcreate': 'prefix': 'dcreate' 'body': 'dcreate(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'drename': 'prefix': 'drename' 'body': 'drename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetModeRestartTime': 'prefix': 'SetModeRestartTime' 'body': 'SetModeRestartTime(${1:Float:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetModeRestartTime': 'prefix': 'GetModeRestartTime' 'body': 'GetModeRestartTime()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxPlayers': 'prefix': 'SetMaxPlayers' 'body': 'SetMaxPlayers(${1:maxplayers})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxNPCs': 'prefix': 'SetMaxNPCs' 'body': 'SetMaxNPCs(${1:maxnpcs})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'LoadFilterScript': 'prefix': 'LoadFilterScript' 'body': 'LoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'UnLoadFilterScript': 'prefix': 'UnLoadFilterScript' 'body': 'UnLoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptCount': 'prefix': 'GetFilterScriptCount' 'body': 'GetFilterScriptCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptName': 'prefix': 'GetFilterScriptName' 'body': 'GetFilterScriptName(${1:id}, ${2:name[]}, ${3:len = sizeof(name})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddServerRule': 'prefix': 'AddServerRule' 'body': 'AddServerRule(${1:const name[]}, ${2:const value[]}, ${3:E_SERVER_RULE_FLAGS:flags = CON_VARFLAG_RULE})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRule': 'prefix': 'SetServerRule' 'body': 'SetServerRule(${1:const name[]}, ${2:const value[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidServerRule': 'prefix': 'IsValidServerRule' 'body': 'IsValidServerRule(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRuleFlags': 'prefix': 'SetServerRuleFlags' 'body': 'SetServerRuleFlags(${1:const name[]}, ${2:E_SERVER_RULE_FLAGS:flags})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'E_SERVER_RULE_FLAGS:GetServerRuleFlags': 'prefix': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags' 'body': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetServerSettings': 'prefix': 'GetServerSettings' 'body': 'GetServerSettings(${1:&showplayermarkes}, ${2:&shownametags}, ${3:&stuntbonus}, ${4:&useplayerpedanims}, ${5:&bLimitchatradius}, ${6:&disableinteriorenterexits}, ${7:&nametaglos}, ${8:&manualvehicleengine}, ${9:&limitplayermarkers}, ${10:&vehiclefriendlyfire}, ${11:&defaultcameracollision}, ${12:&Float:fGlobalchatradius}, ${13:&Float:fNameTagDrawDistance}, ${14:&Float:fPlayermarkerslimit})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EnableConsoleMSGsForPlayer': 'prefix': 'EnableConsoleMSGsForPlayer' 'body': 'EnableConsoleMSGsForPlayer(${1:playerid}, ${2:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DisableConsoleMSGsForPlayer': 'prefix': 'DisableConsoleMSGsForPlayer' 'body': 'DisableConsoleMSGsForPlayer(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasPlayerConsoleMessages': 'prefix': 'HasPlayerConsoleMessages' 'body': 'HasPlayerConsoleMessages(${1:playerid}, ${2:&color = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetTickRate': 'prefix': 'YSF_SetTickRate' 'body': 'YSF_SetTickRate(${1:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetTickRate': 'prefix': 'YSF_GetTickRate' 'body': 'YSF_GetTickRate()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_EnableNightVisionFix': 'prefix': 'YSF_EnableNightVisionFix' 'body': 'YSF_EnableNightVisionFix(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsNightVisionFixEnabled': 'prefix': 'YSF_IsNightVisionFixEnabled' 'body': 'YSF_IsNightVisionFixEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetExtendedNetStatsEnabled': 'prefix': 'YSF_SetExtendedNetStatsEnabled' 'body': 'YSF_SetExtendedNetStatsEnabled(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsExtendedNetStatsEnabled': 'prefix': 'YSF_IsExtendedNetStatsEnabled' 'body': 'YSF_IsExtendedNetStatsEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetAFKAccuracy': 'prefix': 'YSF_SetAFKAccuracy' 'body': 'YSF_SetAFKAccuracy(${1:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetAFKAccuracy': 'prefix': 'YSF_GetAFKAccuracy' 'body': 'YSF_GetAFKAccuracy()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetRecordingDirectory': 'prefix': 'SetRecordingDirectory' 'body': 'SetRecordingDirectory(${1:const dir[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRecordingDirectory': 'prefix': 'GetRecordingDirectory' 'body': 'GetRecordingDirectory(${1:dir[]}, ${2:len = sizeof(dir})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidNickName': 'prefix': 'IsValidNickName' 'body': 'IsValidNickName(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AllowNickNameCharacter': 'prefix': 'AllowNickNameCharacter' 'body': 'AllowNickNameCharacter(${1:character}, ${2:bool:allow})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsNickNameCharacterAllowed': 'prefix': 'IsNickNameCharacterAllowed' 'body': 'IsNickNameCharacterAllowed(${1:character})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetAvailableClasses': 'prefix': 'GetAvailableClasses' 'body': 'GetAvailableClasses()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerClass': 'prefix': 'GetPlayerClass' 'body': 'GetPlayerClass(${1:classid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EditPlayerClass': 'prefix': 'EditPlayerClass' 'body': 'EditPlayerClass(${1:classid}, ${2:teamid}, ${3:modelid}, ${4:Float:spawn_x}, ${5:Float:spawn_y}, ${6:Float:spawn_z}, ${7:Float:z_angle}, ${8:weapon1}, ${9:weapon1_ammo}, ${10:weapon2}, ${11:weapon2_ammo}, ${12:weapon3}, ${13:weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRunningTimers': 'prefix': 'GetRunningTimers' 'body': 'GetRunningTimers()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerGravity': 'prefix': 'SetPlayerGravity' 'body': 'SetPlayerGravity(${1:playerid}, ${2:Float:gravity})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerGravity': 'prefix': 'GetPlayerGravity' 'body': 'GetPlayerGravity(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerAdmin': 'prefix': 'SetPlayerAdmin' 'body': 'SetPlayerAdmin(${1:playerid}, ${2:bool:admin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerTeamForPlayer': 'prefix': 'SetPlayerTeamForPlayer' 'body': 'SetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid}, ${3:teamid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTeamForPlayer': 'prefix': 'GetPlayerTeamForPlayer' 'body': 'GetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerSkinForPlayer': 'prefix': 'SetPlayerSkinForPlayer' 'body': 'SetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid}, ${3:skin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkinForPlayer': 'prefix': 'GetPlayerSkinForPlayer' 'body': 'GetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerNameForPlayer': 'prefix': 'SetPlayerNameForPlayer' 'body': 'SetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:const playername[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerNameForPlayer': 'prefix': 'GetPlayerNameForPlayer' 'body': 'GetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:playername[]}, ${4:size = sizeof(playername})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFightStyleForPlayer': 'prefix': 'SetPlayerFightStyleForPlayer' 'body': 'SetPlayerFightStyleForPlayer(${1:playerid}, ${2:styleplayerid}, ${3:style})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerFightStyleForPlayer': 'prefix': 'GetPlayerFightStyleForPlayer' 'body': 'GetPlayerFightStyleForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerPosForPlayer': 'prefix': 'SetPlayerPosForPlayer' 'body': 'SetPlayerPosForPlayer(${1:playerid}, ${2:posplayerid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerRotationQuatForPlayer': 'prefix': 'SetPlayerRotationQuatForPlayer' 'body': 'SetPlayerRotationQuatForPlayer(${1:playerid}, ${2:quatplayerid}, ${3:Float:w}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ApplyAnimationForPlayer': 'prefix': 'ApplyAnimationForPlayer' 'body': 'ApplyAnimationForPlayer(${1:playerid}, ${2:animplayerid}, ${3:const animlib[]}, ${4:const animname[]}, ${5:Float:fDelta}, ${6:loop}, ${7:lockx}, ${8:locky}, ${9:freeze}, ${10:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWeather': 'prefix': 'GetPlayerWeather' 'body': 'GetPlayerWeather(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerWidescreen': 'prefix': 'TogglePlayerWidescreen' 'body': 'TogglePlayerWidescreen(${1:playerid}, ${2:bool:set})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerWidescreenToggled': 'prefix': 'IsPlayerWidescreenToggled' 'body': 'IsPlayerWidescreenToggled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetSpawnInfo': 'prefix': 'GetSpawnInfo' 'body': 'GetSpawnInfo(${1:playerid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkillLevel': 'prefix': 'GetPlayerSkillLevel' 'body': 'GetPlayerSkillLevel(${1:playerid}, ${2:skill})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCheckpointActive': 'prefix': 'IsPlayerCheckpointActive' 'body': 'IsPlayerCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCheckpoint': 'prefix': 'GetPlayerCheckpoint' 'body': 'GetPlayerCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerRaceCheckpointActive': 'prefix': 'IsPlayerRaceCheckpointActive' 'body': 'IsPlayerRaceCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRaceCheckpoint': 'prefix': 'GetPlayerRaceCheckpoint' 'body': 'GetPlayerRaceCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fNextX}, ${6:&Float:fNextY}, ${7:&Float:fNextZ}, ${8:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWorldBounds': 'prefix': 'GetPlayerWorldBounds' 'body': 'GetPlayerWorldBounds(${1:playerid}, ${2:&Float:x_max}, ${3:&Float:x_min}, ${4:&Float:y_max}, ${5:&Float:y_min})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInModShop': 'prefix': 'IsPlayerInModShop' 'body': 'IsPlayerInModShop(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSirenState': 'prefix': 'GetPlayerSirenState' 'body': 'GetPlayerSirenState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLandingGearState': 'prefix': 'GetPlayerLandingGearState' 'body': 'GetPlayerLandingGearState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerHydraReactorAngle': 'prefix': 'GetPlayerHydraReactorAngle' 'body': 'GetPlayerHydraReactorAngle(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTrainSpeed': 'prefix': 'GetPlayerTrainSpeed' 'body': 'GetPlayerTrainSpeed(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerZAim': 'prefix': 'GetPlayerZAim' 'body': 'GetPlayerZAim(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingOffsets': 'prefix': 'GetPlayerSurfingOffsets' 'body': 'GetPlayerSurfingOffsets(${1:playerid}, ${2:&Float:fOffsetX}, ${3:&Float:fOffsetY}, ${4:&Float:fOffsetZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRotationQuat': 'prefix': 'GetPlayerRotationQuat' 'body': 'GetPlayerRotationQuat(${1:playerid}, ${2:&Float:w}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDialogID': 'prefix': 'GetPlayerDialogID' 'body': 'GetPlayerDialogID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateID': 'prefix': 'GetPlayerSpectateID' 'body': 'GetPlayerSpectateID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateType': 'prefix': 'GetPlayerSpectateType' 'body': 'GetPlayerSpectateType(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedVehicleID': 'prefix': 'GetPlayerLastSyncedVehicleID' 'body': 'GetPlayerLastSyncedVehicleID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedTrailerID': 'prefix': 'GetPlayerLastSyncedTrailerID' 'body': 'GetPlayerLastSyncedTrailerID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendBulletData': 'prefix': 'SendBulletData' 'body': 'SendBulletData(${1:senderid}, ${2:forplayerid = -1}, ${3:weaponid}, ${4:hittype}, ${5:hitid}, ${6:Float:fHitOriginX}, ${7:Float:fHitOriginY}, ${8:Float:fHitOriginZ}, ${9:Float:fHitTargetX}, ${10:Float:fHitTargetY}, ${11:Float:fHitTargetZ}, ${12:Float:fCenterOfHitX}, ${13:Float:fCenterOfHitY}, ${14:Float:fCenterOfHitZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ShowPlayerForPlayer': 'prefix': 'ShowPlayerForPlayer' 'body': 'ShowPlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HidePlayerForPlayer': 'prefix': 'HidePlayerForPlayer' 'body': 'HidePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddPlayerForPlayer': 'prefix': 'AddPlayerForPlayer' 'body': 'AddPlayerForPlayer(${1:forplayerid}, ${2:playerid}, ${3:isnpc = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'RemovePlayerForPlayer': 'prefix': 'RemovePlayerForPlayer' 'body': 'RemovePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerChatBubbleForPlayer': 'prefix': 'SetPlayerChatBubbleForPlayer' 'body': 'SetPlayerChatBubbleForPlayer(${1:forplayerid}, ${2:playerid}, ${3:const text[]}, ${4:color}, ${5:Float:drawdistance}, ${6:expiretime})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ResetPlayerMarkerForPlayer': 'prefix': 'ResetPlayerMarkerForPlayer' 'body': 'ResetPlayerMarkerForPlayer(${1:playerid}, ${2:resetplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerVersion': 'prefix': 'SetPlayerVersion' 'body': 'SetPlayerVersion(${1:playerid}, ${2:const version[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerSpawned': 'prefix': 'IsPlayerSpawned' 'body': 'IsPlayerSpawned(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerControllable': 'prefix': 'IsPlayerControllable' 'body': 'IsPlayerControllable(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SpawnForWorld': 'prefix': 'SpawnForWorld' 'body': 'SpawnForWorld(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'BroadcastDeath': 'prefix': 'BroadcastDeath' 'body': 'BroadcastDeath(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCameraTargetEnabled': 'prefix': 'IsPlayerCameraTargetEnabled' 'body': 'IsPlayerCameraTargetEnabled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerDisabledKeysSync': 'prefix': 'SetPlayerDisabledKeysSync' 'body': 'SetPlayerDisabledKeysSync(${1:playerid}, ${2:keys}, ${3:updown = 0}, ${4:leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDisabledKeysSync': 'prefix': 'GetPlayerDisabledKeysSync' 'body': 'GetPlayerDisabledKeysSync(${1:playerid}, ${2:&keys}, ${3:&updown = 0}, ${4:&leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSpawnInfo': 'prefix': 'GetActorSpawnInfo' 'body': 'GetActorSpawnInfo(${1:actorid}, ${2:&skinid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fAngle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSkin': 'prefix': 'GetActorSkin' 'body': 'GetActorSkin(${1:actorid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorAnimation': 'prefix': 'GetActorAnimation' 'body': 'GetActorAnimation(${1:actorid}, ${2:animlib[]}, ${3:animlibsize = sizeof(animlib})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerScoresPingsUpdate': 'prefix': 'TogglePlayerScoresPingsUpdate' 'body': 'TogglePlayerScoresPingsUpdate(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerFakePing': 'prefix': 'TogglePlayerFakePing' 'body': 'TogglePlayerFakePing(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFakePing': 'prefix': 'SetPlayerFakePing' 'body': 'SetPlayerFakePing(${1:playerid}, ${2:ping})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerInServerQuery': 'prefix': 'TogglePlayerInServerQuery' 'body': 'TogglePlayerInServerQuery(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerToggledInServerQuery': 'prefix': 'IsPlayerToggledInServerQuery' 'body': 'IsPlayerToggledInServerQuery(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPaused': 'prefix': 'IsPlayerPaused' 'body': 'IsPlayerPaused(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPausedTime': 'prefix': 'GetPlayerPausedTime' 'body': 'GetPlayerPausedTime(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectDrawDistance': 'prefix': 'GetObjectDrawDistance' 'body': 'GetObjectDrawDistance(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetObjectMoveSpeed': 'prefix': 'SetObjectMoveSpeed' 'body': 'SetObjectMoveSpeed(${1:objectid}, ${2:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMoveSpeed': 'prefix': 'GetObjectMoveSpeed' 'body': 'GetObjectMoveSpeed(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectTarget': 'prefix': 'GetObjectTarget' 'body': 'GetObjectTarget(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedData': 'prefix': 'GetObjectAttachedData' 'body': 'GetObjectAttachedData(${1:objectid}, ${2:&attached_vehicleid}, ${3:&attached_objectid}, ${4:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedOffset': 'prefix': 'GetObjectAttachedOffset' 'body': 'GetObjectAttachedOffset(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRotX}, ${6:&Float:fRotY}, ${7:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectMaterialSlotUsed': 'prefix': 'IsObjectMaterialSlotUsed' 'body': 'IsObjectMaterialSlotUsed(${1:objectid}, ${2:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterial': 'prefix': 'GetObjectMaterial' 'body': 'GetObjectMaterial(${1:objectid}, ${2:materialindex}, ${3:&modelid}, ${4:txdname[]}, ${5:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterialText': 'prefix': 'GetObjectMaterialText' 'body': 'GetObjectMaterialText(${1:objectid}, ${2:materialindex}, ${3:text[]}, ${4:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectNoCameraCol': 'prefix': 'IsObjectNoCameraCol' 'body': 'IsObjectNoCameraCol(${1:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectDrawDistance': 'prefix': 'GetPlayerObjectDrawDistance' 'body': 'GetPlayerObjectDrawDistance(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerObjectMoveSpeed': 'prefix': 'SetPlayerObjectMoveSpeed' 'body': 'SetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid}, ${3:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMoveSpeed': 'prefix': 'GetPlayerObjectMoveSpeed' 'body': 'GetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectTarget': 'prefix': 'GetPlayerObjectTarget' 'body': 'GetPlayerObjectTarget(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedData': 'prefix': 'GetPlayerObjectAttachedData' 'body': 'GetPlayerObjectAttachedData(${1:playerid}, ${2:objectid}, ${3:&attached_vehicleid}, ${4:&attached_objectid}, ${5:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedOffset': 'prefix': 'GetPlayerObjectAttachedOffset' 'body': 'GetPlayerObjectAttachedOffset(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fRotX}, ${7:&Float:fRotY}, ${8:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectMaterialSlotUsed': 'prefix': 'IsPlayerObjectMaterialSlotUsed' 'body': 'IsPlayerObjectMaterialSlotUsed(${1:playerid}, ${2:objectid}, ${3:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterial': 'prefix': 'GetPlayerObjectMaterial' 'body': 'GetPlayerObjectMaterial(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:&modelid}, ${5:txdname[]}, ${6:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterialText': 'prefix': 'GetPlayerObjectMaterialText' 'body': 'GetPlayerObjectMaterialText(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:text[]}, ${5:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectNoCameraCol': 'prefix': 'IsPlayerObjectNoCameraCol' 'body': 'IsPlayerObjectNoCameraCol(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingPlayerObjectID': 'prefix': 'GetPlayerSurfingPlayerObjectID' 'body': 'GetPlayerSurfingPlayerObjectID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCameraTargetPlayerObj': 'prefix': 'GetPlayerCameraTargetPlayerObj' 'body': 'GetPlayerCameraTargetPlayerObj(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectType': 'prefix': 'GetObjectType' 'body': 'GetObjectType(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerAttachedObject': 'prefix': 'GetPlayerAttachedObject' 'body': 'GetPlayerAttachedObject(${1:playerid}, ${2:index}, ${3:&modelid}, ${4:&bone}, ${5:&Float:fX}, ${6:&Float:fY}, ${7:&Float:fZ}, ${8:&Float:fRotX}, ${9:&Float:fRotY}, ${10:&Float:fRotZ}, ${11:&Float:fSacleX}, ${12:&Float:fScaleY}, ${13:&Float:fScaleZ}, ${14:&materialcolor1}, ${15:&materialcolor2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AttachPlayerObjectToObject': 'prefix': 'AttachPlayerObjectToObject' 'body': 'AttachPlayerObjectToObject(${1:playerid}, ${2:objectid}, ${3:attachtoid}, ${4:Float:OffsetX}, ${5:Float:OffsetY}, ${6:Float:OffsetZ}, ${7:Float:RotX}, ${8:Float:RotY}, ${9:Float:RotZ}, ${10:SyncRotation = 1})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ClearBanList': 'prefix': 'ClearBanList' 'body': 'ClearBanList()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsBanned': 'prefix': 'IsBanned' 'body': 'IsBanned(${1:const ipaddress[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetTimeoutTime': 'prefix': 'SetTimeoutTime' 'body': 'SetTimeoutTime(${1:playerid}, ${2:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetLocalIP': 'prefix': 'GetLocalIP' 'body': 'GetLocalIP(${1:index}, ${2:localip[]}, ${3:len = sizeof(localip})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleSpawnInfo': 'prefix': 'GetVehicleSpawnInfo' 'body': 'GetVehicleSpawnInfo(${1:vehicleid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRot}, ${6:&color1}, ${7:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleSpawnInfo': 'prefix': 'SetVehicleSpawnInfo' 'body': 'SetVehicleSpawnInfo(${1:vehicleid}, ${2:modelid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:Float:fAngle}, ${7:color1}, ${8:color2}, ${9:respawntime = -2}, ${10:interior = -2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleColor': 'prefix': 'GetVehicleColor' 'body': 'GetVehicleColor(${1:vehicleid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehiclePaintjob': 'prefix': 'GetVehiclePaintjob' 'body': 'GetVehiclePaintjob(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleInterior': 'prefix': 'GetVehicleInterior' 'body': 'GetVehicleInterior(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleNumberPlate': 'prefix': 'GetVehicleNumberPlate' 'body': 'GetVehicleNumberPlate(${1:vehicleid}, ${2:plate[]}, ${3:len = sizeof(plate})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnDelay': 'prefix': 'SetVehicleRespawnDelay' 'body': 'SetVehicleRespawnDelay(${1:vehicleid}, ${2:delay})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnDelay': 'prefix': 'GetVehicleRespawnDelay' 'body': 'GetVehicleRespawnDelay(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleOccupiedTick': 'prefix': 'SetVehicleOccupiedTick' 'body': 'SetVehicleOccupiedTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleOccupiedTick': 'prefix': 'GetVehicleOccupiedTick' 'body': 'GetVehicleOccupiedTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnTick': 'prefix': 'SetVehicleRespawnTick' 'body': 'SetVehicleRespawnTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnTick': 'prefix': 'GetVehicleRespawnTick' 'body': 'GetVehicleRespawnTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleLastDriver': 'prefix': 'GetVehicleLastDriver' 'body': 'GetVehicleLastDriver(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleCab': 'prefix': 'GetVehicleCab' 'body': 'GetVehicleCab(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasVehicleBeenOccupied': 'prefix': 'HasVehicleBeenOccupied' 'body': 'HasVehicleBeenOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleBeenOccupied': 'prefix': 'SetVehicleBeenOccupied' 'body': 'SetVehicleBeenOccupied(${1:vehicleid}, ${2:occupied})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleOccupied': 'prefix': 'IsVehicleOccupied' 'body': 'IsVehicleOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleDead': 'prefix': 'IsVehicleDead' 'body': 'IsVehicleDead(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelCount': 'prefix': 'GetVehicleModelCount' 'body': 'GetVehicleModelCount(${1:modelid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelsUsed': 'prefix': 'GetVehicleModelsUsed' 'body': 'GetVehicleModelsUsed()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidGangZone': 'prefix': 'IsValidGangZone' 'body': 'IsValidGangZone(${1:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInGangZone': 'prefix': 'IsPlayerInGangZone' 'body': 'IsPlayerInGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneVisibleForPlayer': 'prefix': 'IsGangZoneVisibleForPlayer' 'body': 'IsGangZoneVisibleForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetColorForPlayer': 'prefix': 'GangZoneGetColorForPlayer' 'body': 'GangZoneGetColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetFlashColorForPlayer': 'prefix': 'GangZoneGetFlashColorForPlayer' 'body': 'GangZoneGetFlashColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneFlashingForPlayer': 'prefix': 'IsGangZoneFlashingForPlayer' 'body': 'IsGangZoneFlashingForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetPos': 'prefix': 'GangZoneGetPos' 'body': 'GangZoneGetPos(${1:zoneid}, ${2:&Float:fMinX}, ${3:&Float:fMinY}, ${4:&Float:fMaxX}, ${5:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerGangZone': 'prefix': 'CreatePlayerGangZone' 'body': 'CreatePlayerGangZone(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneDestroy': 'prefix': 'PlayerGangZoneDestroy' 'body': 'PlayerGangZoneDestroy(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneShow': 'prefix': 'PlayerGangZoneShow' 'body': 'PlayerGangZoneShow(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneHide': 'prefix': 'PlayerGangZoneHide' 'body': 'PlayerGangZoneHide(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneFlash': 'prefix': 'PlayerGangZoneFlash' 'body': 'PlayerGangZoneFlash(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneStopFlash': 'prefix': 'PlayerGangZoneStopFlash' 'body': 'PlayerGangZoneStopFlash(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerGangZone': 'prefix': 'IsValidPlayerGangZone' 'body': 'IsValidPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInPlayerGangZone': 'prefix': 'IsPlayerInPlayerGangZone' 'body': 'IsPlayerInPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneVisible': 'prefix': 'IsPlayerGangZoneVisible' 'body': 'IsPlayerGangZoneVisible(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetColor': 'prefix': 'PlayerGangZoneGetColor' 'body': 'PlayerGangZoneGetColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetFlashColor': 'prefix': 'PlayerGangZoneGetFlashColor' 'body': 'PlayerGangZoneGetFlashColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneFlashing': 'prefix': 'IsPlayerGangZoneFlashing' 'body': 'IsPlayerGangZoneFlashing(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetPos': 'prefix': 'PlayerGangZoneGetPos' 'body': 'PlayerGangZoneGetPos(${1:playerid}, ${2:zoneid}, ${3:&Float:fMinX}, ${4:&Float:fMinY}, ${5:&Float:fMaxX}, ${6:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidTextDraw': 'prefix': 'IsValidTextDraw' 'body': 'IsValidTextDraw(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsTextDrawVisibleForPlayer': 'prefix': 'IsTextDrawVisibleForPlayer' 'body': 'IsTextDrawVisibleForPlayer(${1:playerid}, ${2:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetString': 'prefix': 'TextDrawGetString' 'body': 'TextDrawGetString(${1:Text:textdrawid}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawSetPos': 'prefix': 'TextDrawSetPos' 'body': 'TextDrawSetPos(${1:Text:textdrawid}, ${2:Float:fX}, ${3:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetLetterSize': 'prefix': 'TextDrawGetLetterSize' 'body': 'TextDrawGetLetterSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetTextSize': 'prefix': 'TextDrawGetTextSize' 'body': 'TextDrawGetTextSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPos': 'prefix': 'TextDrawGetPos' 'body': 'TextDrawGetPos(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetColor': 'prefix': 'TextDrawGetColor' 'body': 'TextDrawGetColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBoxColor': 'prefix': 'TextDrawGetBoxColor' 'body': 'TextDrawGetBoxColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBackgroundColor': 'prefix': 'TextDrawGetBackgroundColor' 'body': 'TextDrawGetBackgroundColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetShadow': 'prefix': 'TextDrawGetShadow' 'body': 'TextDrawGetShadow(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetOutline': 'prefix': 'TextDrawGetOutline' 'body': 'TextDrawGetOutline(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetFont': 'prefix': 'TextDrawGetFont' 'body': 'TextDrawGetFont(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsBox': 'prefix': 'TextDrawIsBox' 'body': 'TextDrawIsBox(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsProportional': 'prefix': 'TextDrawIsProportional' 'body': 'TextDrawIsProportional(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsSelectable': 'prefix': 'TextDrawIsSelectable' 'body': 'TextDrawIsSelectable(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetAlignment': 'prefix': 'TextDrawGetAlignment' 'body': 'TextDrawGetAlignment(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewModel': 'prefix': 'TextDrawGetPreviewModel' 'body': 'TextDrawGetPreviewModel(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewRot': 'prefix': 'TextDrawGetPreviewRot' 'body': 'TextDrawGetPreviewRot(${1:Text:textdrawid}, ${2:&Float:fRotX}, ${3:&Float:fRotY}, ${4:&Float:fRotZ}, ${5:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewVehCol': 'prefix': 'TextDrawGetPreviewVehCol' 'body': 'TextDrawGetPreviewVehCol(${1:Text:textdrawid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerTextDraw': 'prefix': 'IsValidPlayerTextDraw' 'body': 'IsValidPlayerTextDraw(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerTextDrawVisible': 'prefix': 'IsPlayerTextDrawVisible' 'body': 'IsPlayerTextDrawVisible(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetString': 'prefix': 'PlayerTextDrawGetString' 'body': 'PlayerTextDrawGetString(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawSetPos': 'prefix': 'PlayerTextDrawSetPos' 'body': 'PlayerTextDrawSetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:Float:fX}, ${4:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetLetterSize': 'prefix': 'PlayerTextDrawGetLetterSize' 'body': 'PlayerTextDrawGetLetterSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetTextSize': 'prefix': 'PlayerTextDrawGetTextSize' 'body': 'PlayerTextDrawGetTextSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPos': 'prefix': 'PlayerTextDrawGetPos' 'body': 'PlayerTextDrawGetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetColor': 'prefix': 'PlayerTextDrawGetColor' 'body': 'PlayerTextDrawGetColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBoxColor': 'prefix': 'PlayerTextDrawGetBoxColor' 'body': 'PlayerTextDrawGetBoxColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBackgroundCol': 'prefix': 'PlayerTextDrawGetBackgroundCol' 'body': 'PlayerTextDrawGetBackgroundCol(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetShadow': 'prefix': 'PlayerTextDrawGetShadow' 'body': 'PlayerTextDrawGetShadow(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetOutline': 'prefix': 'PlayerTextDrawGetOutline' 'body': 'PlayerTextDrawGetOutline(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetFont': 'prefix': 'PlayerTextDrawGetFont' 'body': 'PlayerTextDrawGetFont(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsBox': 'prefix': 'PlayerTextDrawIsBox' 'body': 'PlayerTextDrawIsBox(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsProportional': 'prefix': 'PlayerTextDrawIsProportional' 'body': 'PlayerTextDrawIsProportional(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsSelectable': 'prefix': 'PlayerTextDrawIsSelectable' 'body': 'PlayerTextDrawIsSelectable(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetAlignment': 'prefix': 'PlayerTextDrawGetAlignment' 'body': 'PlayerTextDrawGetAlignment(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewModel': 'prefix': 'PlayerTextDrawGetPreviewModel' 'body': 'PlayerTextDrawGetPreviewModel(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewRot': 'prefix': 'PlayerTextDrawGetPreviewRot' 'body': 'PlayerTextDrawGetPreviewRot(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fRotX}, ${4:&Float:fRotY}, ${5:&Float:fRotZ}, ${6:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewVehCol': 'prefix': 'PlayerTextDrawGetPreviewVehCol' 'body': 'PlayerTextDrawGetPreviewVehCol(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&color1}, ${4:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValid3DTextLabel': 'prefix': 'IsValid3DTextLabel' 'body': 'IsValid3DTextLabel(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Is3DTextLabelStreamedIn': 'prefix': 'Is3DTextLabelStreamedIn' 'body': 'Is3DTextLabelStreamedIn(${1:playerid}, ${2:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelText': 'prefix': 'Get3DTextLabelText' 'body': 'Get3DTextLabelText(${1:Text3D:id}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelColor': 'prefix': 'Get3DTextLabelColor' 'body': 'Get3DTextLabelColor(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelPos': 'prefix': 'Get3DTextLabelPos' 'body': 'Get3DTextLabelPos(${1:Text3D:id}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelDrawDistance': 'prefix': 'Get3DTextLabelDrawDistance' 'body': 'Get3DTextLabelDrawDistance(${1:Text3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelLOS': 'prefix': 'Get3DTextLabelLOS' 'body': 'Get3DTextLabelLOS(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelVirtualWorld': 'prefix': 'Get3DTextLabelVirtualWorld' 'body': 'Get3DTextLabelVirtualWorld(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelAttachedData': 'prefix': 'Get3DTextLabelAttachedData' 'body': 'Get3DTextLabelAttachedData(${1:Text3D:id}, ${2:&attached_playerid}, ${3:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayer3DTextLabel': 'prefix': 'IsValidPlayer3DTextLabel' 'body': 'IsValidPlayer3DTextLabel(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelText': 'prefix': 'GetPlayer3DTextLabelText' 'body': 'GetPlayer3DTextLabelText(${1:playerid}, ${2:PlayerText3D:id}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelColor': 'prefix': 'GetPlayer3DTextLabelColor' 'body': 'GetPlayer3DTextLabelColor(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelPos': 'prefix': 'GetPlayer3DTextLabelPos' 'body': 'GetPlayer3DTextLabelPos(${1:playerid}, ${2:PlayerText3D:id}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelDrawDist': 'prefix': 'GetPlayer3DTextLabelDrawDist' 'body': 'GetPlayer3DTextLabelDrawDist(${1:playerid}, ${2:PlayerText3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelLOS': 'prefix': 'GetPlayer3DTextLabelLOS' 'body': 'GetPlayer3DTextLabelLOS(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelVirtualW': 'prefix': 'GetPlayer3DTextLabelVirtualW' 'body': 'GetPlayer3DTextLabelVirtualW(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelAttached': 'prefix': 'GetPlayer3DTextLabelAttached' 'body': 'GetPlayer3DTextLabelAttached(${1:playerid}, ${2:PlayerText3D:id}, ${3:&attached_playerid}, ${4:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuDisabled': 'prefix': 'IsMenuDisabled' 'body': 'IsMenuDisabled(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuRowDisabled': 'prefix': 'IsMenuRowDisabled' 'body': 'IsMenuRowDisabled(${1:Menu:menuid}, ${2:row})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumns': 'prefix': 'GetMenuColumns' 'body': 'GetMenuColumns(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItems': 'prefix': 'GetMenuItems' 'body': 'GetMenuItems(${1:Menu:menuid}, ${2:column})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuPos': 'prefix': 'GetMenuPos' 'body': 'GetMenuPos(${1:Menu:menuid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnWidth': 'prefix': 'GetMenuColumnWidth' 'body': 'GetMenuColumnWidth(${1:Menu:menuid}, ${2:&Float:fColumn1}, ${3:&Float:fColumn2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnHeader': 'prefix': 'GetMenuColumnHeader' 'body': 'GetMenuColumnHeader(${1:Menu:menuid}, ${2:column}, ${3:header[]}, ${4:len = sizeof(header})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItem': 'prefix': 'GetMenuItem' 'body': 'GetMenuItem(${1:Menu:menuid}, ${2:column}, ${3:itemid}, ${4:item[]}, ${5:len = sizeof(item})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPickup': 'prefix': 'IsValidPickup' 'body': 'IsValidPickup(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPickupStreamedIn': 'prefix': 'IsPickupStreamedIn' 'body': 'IsPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupPos': 'prefix': 'GetPickupPos' 'body': 'GetPickupPos(${1:pickupid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupModel': 'prefix': 'GetPickupModel' 'body': 'GetPickupModel(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupType': 'prefix': 'GetPickupType' 'body': 'GetPickupType(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupVirtualWorld': 'prefix': 'GetPickupVirtualWorld' 'body': 'GetPickupVirtualWorld(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerPickup': 'prefix': 'CreatePlayerPickup' 'body': 'CreatePlayerPickup(${1:playerid}, ${2:model}, ${3:type}, ${4:Float:X}, ${5:Float:Y}, ${6:Float:Z}, ${7:virtualworld = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DestroyPlayerPickup': 'prefix': 'DestroyPlayerPickup' 'body': 'DestroyPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerPickup': 'prefix': 'IsValidPlayerPickup' 'body': 'IsValidPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPickupStreamedIn': 'prefix': 'IsPlayerPickupStreamedIn' 'body': 'IsPlayerPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupPos': 'prefix': 'GetPlayerPickupPos' 'body': 'GetPlayerPickupPos(${1:playerid}, ${2:pickupid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupModel': 'prefix': 'GetPlayerPickupModel' 'body': 'GetPlayerPickupModel(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupType': 'prefix': 'GetPlayerPickupType' 'body': 'GetPlayerPickupType(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupVirtualWorld': 'prefix': 'GetPlayerPickupVirtualWorld' 'body': 'GetPlayerPickupVirtualWorld(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColCount': 'prefix': 'GetColCount' 'body': 'GetColCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereRadius': 'prefix': 'GetColSphereRadius' 'body': 'GetColSphereRadius(${1:modelid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereOffset': 'prefix': 'GetColSphereOffset' 'body': 'GetColSphereOffset(${1:modelid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessagef': 'prefix': 'SendClientMessagef' 'body': 'SendClientMessagef(${1:playerid}, ${2:color}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessageToAllf': 'prefix': 'SendClientMessageToAllf' 'body': 'SendClientMessageToAllf(${1:color}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForPlayerf': 'prefix': 'GameTextForPlayerf' 'body': 'GameTextForPlayerf(${1:playerid}, ${2:displaytime}, ${3:style}, ${4:const message[]}, ${5:{Float}, ${6:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForAllf': 'prefix': 'GameTextForAllf' 'body': 'GameTextForAllf(${1:displaytime}, ${2:style}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToPlayerf': 'prefix': 'SendPlayerMessageToPlayerf' 'body': 'SendPlayerMessageToPlayerf(${1:playerid}, ${2:senderid}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToAllf': 'prefix': 'SendPlayerMessageToAllf' 'body': 'SendPlayerMessageToAllf(${1:senderid}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRconCommandf': 'prefix': 'SendRconCommandf' 'body': 'SendRconCommandf(${1:const command[]}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetWeaponSlot': 'prefix': 'GetWeaponSlot' 'body': 'GetWeaponSlot(${1:weaponid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRPC': 'prefix': 'SendRPC' 'body': 'SendRPC(${1:playerid}, ${2:RPC}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendData': 'prefix': 'SendData' 'body': 'SendData(${1:playerid}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetGravity': 'prefix': 'GetGravity' 'body': 'GetGravity()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499'
36367
# YSF Snippets for Atom, automatically generated # Generator created by <NAME> "<NAME>" <NAME> '.source.pwn, .source.inc': 'execute': 'prefix': 'execute' 'body': 'execute(${1:const command[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ffind': 'prefix': 'ffind' 'body': 'ffind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'frename': 'prefix': 'frename' 'body': 'frename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dfind': 'prefix': 'dfind' 'body': 'dfind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dcreate': 'prefix': 'dcreate' 'body': 'dcreate(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'drename': 'prefix': 'drename' 'body': 'drename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetModeRestartTime': 'prefix': 'SetModeRestartTime' 'body': 'SetModeRestartTime(${1:Float:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetModeRestartTime': 'prefix': 'GetModeRestartTime' 'body': 'GetModeRestartTime()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxPlayers': 'prefix': 'SetMaxPlayers' 'body': 'SetMaxPlayers(${1:maxplayers})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxNPCs': 'prefix': 'SetMaxNPCs' 'body': 'SetMaxNPCs(${1:maxnpcs})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'LoadFilterScript': 'prefix': 'LoadFilterScript' 'body': 'LoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'UnLoadFilterScript': 'prefix': 'UnLoadFilterScript' 'body': 'UnLoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptCount': 'prefix': 'GetFilterScriptCount' 'body': 'GetFilterScriptCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptName': 'prefix': 'GetFilterScriptName' 'body': 'GetFilterScriptName(${1:id}, ${2:name[]}, ${3:len = sizeof(name})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddServerRule': 'prefix': 'AddServerRule' 'body': 'AddServerRule(${1:const name[]}, ${2:const value[]}, ${3:E_SERVER_RULE_FLAGS:flags = CON_VARFLAG_RULE})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRule': 'prefix': 'SetServerRule' 'body': 'SetServerRule(${1:const name[]}, ${2:const value[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidServerRule': 'prefix': 'IsValidServerRule' 'body': 'IsValidServerRule(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRuleFlags': 'prefix': 'SetServerRuleFlags' 'body': 'SetServerRuleFlags(${1:const name[]}, ${2:E_SERVER_RULE_FLAGS:flags})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'E_SERVER_RULE_FLAGS:GetServerRuleFlags': 'prefix': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags' 'body': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetServerSettings': 'prefix': 'GetServerSettings' 'body': 'GetServerSettings(${1:&showplayermarkes}, ${2:&shownametags}, ${3:&stuntbonus}, ${4:&useplayerpedanims}, ${5:&bLimitchatradius}, ${6:&disableinteriorenterexits}, ${7:&nametaglos}, ${8:&manualvehicleengine}, ${9:&limitplayermarkers}, ${10:&vehiclefriendlyfire}, ${11:&defaultcameracollision}, ${12:&Float:fGlobalchatradius}, ${13:&Float:fNameTagDrawDistance}, ${14:&Float:fPlayermarkerslimit})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EnableConsoleMSGsForPlayer': 'prefix': 'EnableConsoleMSGsForPlayer' 'body': 'EnableConsoleMSGsForPlayer(${1:playerid}, ${2:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DisableConsoleMSGsForPlayer': 'prefix': 'DisableConsoleMSGsForPlayer' 'body': 'DisableConsoleMSGsForPlayer(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasPlayerConsoleMessages': 'prefix': 'HasPlayerConsoleMessages' 'body': 'HasPlayerConsoleMessages(${1:playerid}, ${2:&color = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetTickRate': 'prefix': 'YSF_SetTickRate' 'body': 'YSF_SetTickRate(${1:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetTickRate': 'prefix': 'YSF_GetTickRate' 'body': 'YSF_GetTickRate()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_EnableNightVisionFix': 'prefix': 'YSF_EnableNightVisionFix' 'body': 'YSF_EnableNightVisionFix(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsNightVisionFixEnabled': 'prefix': 'YSF_IsNightVisionFixEnabled' 'body': 'YSF_IsNightVisionFixEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetExtendedNetStatsEnabled': 'prefix': 'YSF_SetExtendedNetStatsEnabled' 'body': 'YSF_SetExtendedNetStatsEnabled(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsExtendedNetStatsEnabled': 'prefix': 'YSF_IsExtendedNetStatsEnabled' 'body': 'YSF_IsExtendedNetStatsEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetAFKAccuracy': 'prefix': 'YSF_SetAFKAccuracy' 'body': 'YSF_SetAFKAccuracy(${1:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetAFKAccuracy': 'prefix': 'YSF_GetAFKAccuracy' 'body': 'YSF_GetAFKAccuracy()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetRecordingDirectory': 'prefix': 'SetRecordingDirectory' 'body': 'SetRecordingDirectory(${1:const dir[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRecordingDirectory': 'prefix': 'GetRecordingDirectory' 'body': 'GetRecordingDirectory(${1:dir[]}, ${2:len = sizeof(dir})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidNickName': 'prefix': 'IsValidNickName' 'body': 'IsValidNickName(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AllowNickNameCharacter': 'prefix': 'AllowNickNameCharacter' 'body': 'AllowNickNameCharacter(${1:character}, ${2:bool:allow})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsNickNameCharacterAllowed': 'prefix': 'IsNickNameCharacterAllowed' 'body': 'IsNickNameCharacterAllowed(${1:character})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetAvailableClasses': 'prefix': 'GetAvailableClasses' 'body': 'GetAvailableClasses()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerClass': 'prefix': 'GetPlayerClass' 'body': 'GetPlayerClass(${1:classid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EditPlayerClass': 'prefix': 'EditPlayerClass' 'body': 'EditPlayerClass(${1:classid}, ${2:teamid}, ${3:modelid}, ${4:Float:spawn_x}, ${5:Float:spawn_y}, ${6:Float:spawn_z}, ${7:Float:z_angle}, ${8:weapon1}, ${9:weapon1_ammo}, ${10:weapon2}, ${11:weapon2_ammo}, ${12:weapon3}, ${13:weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRunningTimers': 'prefix': 'GetRunningTimers' 'body': 'GetRunningTimers()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerGravity': 'prefix': 'SetPlayerGravity' 'body': 'SetPlayerGravity(${1:playerid}, ${2:Float:gravity})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerGravity': 'prefix': 'GetPlayerGravity' 'body': 'GetPlayerGravity(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerAdmin': 'prefix': 'SetPlayerAdmin' 'body': 'SetPlayerAdmin(${1:playerid}, ${2:bool:admin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerTeamForPlayer': 'prefix': 'SetPlayerTeamForPlayer' 'body': 'SetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid}, ${3:teamid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTeamForPlayer': 'prefix': 'GetPlayerTeamForPlayer' 'body': 'GetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerSkinForPlayer': 'prefix': 'SetPlayerSkinForPlayer' 'body': 'SetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid}, ${3:skin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkinForPlayer': 'prefix': 'GetPlayerSkinForPlayer' 'body': 'GetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerNameForPlayer': 'prefix': 'SetPlayerNameForPlayer' 'body': 'SetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:const playername[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerNameForPlayer': 'prefix': 'GetPlayerNameForPlayer' 'body': 'GetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:playername[]}, ${4:size = sizeof(playername})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFightStyleForPlayer': 'prefix': 'SetPlayerFightStyleForPlayer' 'body': 'SetPlayerFightStyleForPlayer(${1:playerid}, ${2:styleplayerid}, ${3:style})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerFightStyleForPlayer': 'prefix': 'GetPlayerFightStyleForPlayer' 'body': 'GetPlayerFightStyleForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerPosForPlayer': 'prefix': 'SetPlayerPosForPlayer' 'body': 'SetPlayerPosForPlayer(${1:playerid}, ${2:posplayerid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerRotationQuatForPlayer': 'prefix': 'SetPlayerRotationQuatForPlayer' 'body': 'SetPlayerRotationQuatForPlayer(${1:playerid}, ${2:quatplayerid}, ${3:Float:w}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ApplyAnimationForPlayer': 'prefix': 'ApplyAnimationForPlayer' 'body': 'ApplyAnimationForPlayer(${1:playerid}, ${2:animplayerid}, ${3:const animlib[]}, ${4:const animname[]}, ${5:Float:fDelta}, ${6:loop}, ${7:lockx}, ${8:locky}, ${9:freeze}, ${10:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWeather': 'prefix': 'GetPlayerWeather' 'body': 'GetPlayerWeather(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerWidescreen': 'prefix': 'TogglePlayerWidescreen' 'body': 'TogglePlayerWidescreen(${1:playerid}, ${2:bool:set})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerWidescreenToggled': 'prefix': 'IsPlayerWidescreenToggled' 'body': 'IsPlayerWidescreenToggled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetSpawnInfo': 'prefix': 'GetSpawnInfo' 'body': 'GetSpawnInfo(${1:playerid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkillLevel': 'prefix': 'GetPlayerSkillLevel' 'body': 'GetPlayerSkillLevel(${1:playerid}, ${2:skill})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCheckpointActive': 'prefix': 'IsPlayerCheckpointActive' 'body': 'IsPlayerCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCheckpoint': 'prefix': 'GetPlayerCheckpoint' 'body': 'GetPlayerCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerRaceCheckpointActive': 'prefix': 'IsPlayerRaceCheckpointActive' 'body': 'IsPlayerRaceCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRaceCheckpoint': 'prefix': 'GetPlayerRaceCheckpoint' 'body': 'GetPlayerRaceCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fNextX}, ${6:&Float:fNextY}, ${7:&Float:fNextZ}, ${8:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWorldBounds': 'prefix': 'GetPlayerWorldBounds' 'body': 'GetPlayerWorldBounds(${1:playerid}, ${2:&Float:x_max}, ${3:&Float:x_min}, ${4:&Float:y_max}, ${5:&Float:y_min})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInModShop': 'prefix': 'IsPlayerInModShop' 'body': 'IsPlayerInModShop(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSirenState': 'prefix': 'GetPlayerSirenState' 'body': 'GetPlayerSirenState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLandingGearState': 'prefix': 'GetPlayerLandingGearState' 'body': 'GetPlayerLandingGearState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerHydraReactorAngle': 'prefix': 'GetPlayerHydraReactorAngle' 'body': 'GetPlayerHydraReactorAngle(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTrainSpeed': 'prefix': 'GetPlayerTrainSpeed' 'body': 'GetPlayerTrainSpeed(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerZAim': 'prefix': 'GetPlayerZAim' 'body': 'GetPlayerZAim(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingOffsets': 'prefix': 'GetPlayerSurfingOffsets' 'body': 'GetPlayerSurfingOffsets(${1:playerid}, ${2:&Float:fOffsetX}, ${3:&Float:fOffsetY}, ${4:&Float:fOffsetZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRotationQuat': 'prefix': 'GetPlayerRotationQuat' 'body': 'GetPlayerRotationQuat(${1:playerid}, ${2:&Float:w}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDialogID': 'prefix': 'GetPlayerDialogID' 'body': 'GetPlayerDialogID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateID': 'prefix': 'GetPlayerSpectateID' 'body': 'GetPlayerSpectateID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateType': 'prefix': 'GetPlayerSpectateType' 'body': 'GetPlayerSpectateType(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedVehicleID': 'prefix': 'GetPlayerLastSyncedVehicleID' 'body': 'GetPlayerLastSyncedVehicleID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedTrailerID': 'prefix': 'GetPlayerLastSyncedTrailerID' 'body': 'GetPlayerLastSyncedTrailerID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendBulletData': 'prefix': 'SendBulletData' 'body': 'SendBulletData(${1:senderid}, ${2:forplayerid = -1}, ${3:weaponid}, ${4:hittype}, ${5:hitid}, ${6:Float:fHitOriginX}, ${7:Float:fHitOriginY}, ${8:Float:fHitOriginZ}, ${9:Float:fHitTargetX}, ${10:Float:fHitTargetY}, ${11:Float:fHitTargetZ}, ${12:Float:fCenterOfHitX}, ${13:Float:fCenterOfHitY}, ${14:Float:fCenterOfHitZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ShowPlayerForPlayer': 'prefix': 'ShowPlayerForPlayer' 'body': 'ShowPlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HidePlayerForPlayer': 'prefix': 'HidePlayerForPlayer' 'body': 'HidePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddPlayerForPlayer': 'prefix': 'AddPlayerForPlayer' 'body': 'AddPlayerForPlayer(${1:forplayerid}, ${2:playerid}, ${3:isnpc = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'RemovePlayerForPlayer': 'prefix': 'RemovePlayerForPlayer' 'body': 'RemovePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerChatBubbleForPlayer': 'prefix': 'SetPlayerChatBubbleForPlayer' 'body': 'SetPlayerChatBubbleForPlayer(${1:forplayerid}, ${2:playerid}, ${3:const text[]}, ${4:color}, ${5:Float:drawdistance}, ${6:expiretime})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ResetPlayerMarkerForPlayer': 'prefix': 'ResetPlayerMarkerForPlayer' 'body': 'ResetPlayerMarkerForPlayer(${1:playerid}, ${2:resetplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerVersion': 'prefix': 'SetPlayerVersion' 'body': 'SetPlayerVersion(${1:playerid}, ${2:const version[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerSpawned': 'prefix': 'IsPlayerSpawned' 'body': 'IsPlayerSpawned(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerControllable': 'prefix': 'IsPlayerControllable' 'body': 'IsPlayerControllable(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SpawnForWorld': 'prefix': 'SpawnForWorld' 'body': 'SpawnForWorld(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'BroadcastDeath': 'prefix': 'BroadcastDeath' 'body': 'BroadcastDeath(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCameraTargetEnabled': 'prefix': 'IsPlayerCameraTargetEnabled' 'body': 'IsPlayerCameraTargetEnabled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerDisabledKeysSync': 'prefix': 'SetPlayerDisabledKeysSync' 'body': 'SetPlayerDisabledKeysSync(${1:playerid}, ${2:keys}, ${3:updown = 0}, ${4:leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDisabledKeysSync': 'prefix': 'GetPlayerDisabledKeysSync' 'body': 'GetPlayerDisabledKeysSync(${1:playerid}, ${2:&keys}, ${3:&updown = 0}, ${4:&leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSpawnInfo': 'prefix': 'GetActorSpawnInfo' 'body': 'GetActorSpawnInfo(${1:actorid}, ${2:&skinid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fAngle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSkin': 'prefix': 'GetActorSkin' 'body': 'GetActorSkin(${1:actorid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorAnimation': 'prefix': 'GetActorAnimation' 'body': 'GetActorAnimation(${1:actorid}, ${2:animlib[]}, ${3:animlibsize = sizeof(animlib})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerScoresPingsUpdate': 'prefix': 'TogglePlayerScoresPingsUpdate' 'body': 'TogglePlayerScoresPingsUpdate(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerFakePing': 'prefix': 'TogglePlayerFakePing' 'body': 'TogglePlayerFakePing(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFakePing': 'prefix': 'SetPlayerFakePing' 'body': 'SetPlayerFakePing(${1:playerid}, ${2:ping})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerInServerQuery': 'prefix': 'TogglePlayerInServerQuery' 'body': 'TogglePlayerInServerQuery(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerToggledInServerQuery': 'prefix': 'IsPlayerToggledInServerQuery' 'body': 'IsPlayerToggledInServerQuery(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPaused': 'prefix': 'IsPlayerPaused' 'body': 'IsPlayerPaused(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPausedTime': 'prefix': 'GetPlayerPausedTime' 'body': 'GetPlayerPausedTime(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectDrawDistance': 'prefix': 'GetObjectDrawDistance' 'body': 'GetObjectDrawDistance(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetObjectMoveSpeed': 'prefix': 'SetObjectMoveSpeed' 'body': 'SetObjectMoveSpeed(${1:objectid}, ${2:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMoveSpeed': 'prefix': 'GetObjectMoveSpeed' 'body': 'GetObjectMoveSpeed(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectTarget': 'prefix': 'GetObjectTarget' 'body': 'GetObjectTarget(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedData': 'prefix': 'GetObjectAttachedData' 'body': 'GetObjectAttachedData(${1:objectid}, ${2:&attached_vehicleid}, ${3:&attached_objectid}, ${4:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedOffset': 'prefix': 'GetObjectAttachedOffset' 'body': 'GetObjectAttachedOffset(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRotX}, ${6:&Float:fRotY}, ${7:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectMaterialSlotUsed': 'prefix': 'IsObjectMaterialSlotUsed' 'body': 'IsObjectMaterialSlotUsed(${1:objectid}, ${2:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterial': 'prefix': 'GetObjectMaterial' 'body': 'GetObjectMaterial(${1:objectid}, ${2:materialindex}, ${3:&modelid}, ${4:txdname[]}, ${5:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterialText': 'prefix': 'GetObjectMaterialText' 'body': 'GetObjectMaterialText(${1:objectid}, ${2:materialindex}, ${3:text[]}, ${4:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectNoCameraCol': 'prefix': 'IsObjectNoCameraCol' 'body': 'IsObjectNoCameraCol(${1:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectDrawDistance': 'prefix': 'GetPlayerObjectDrawDistance' 'body': 'GetPlayerObjectDrawDistance(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerObjectMoveSpeed': 'prefix': 'SetPlayerObjectMoveSpeed' 'body': 'SetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid}, ${3:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMoveSpeed': 'prefix': 'GetPlayerObjectMoveSpeed' 'body': 'GetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectTarget': 'prefix': 'GetPlayerObjectTarget' 'body': 'GetPlayerObjectTarget(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedData': 'prefix': 'GetPlayerObjectAttachedData' 'body': 'GetPlayerObjectAttachedData(${1:playerid}, ${2:objectid}, ${3:&attached_vehicleid}, ${4:&attached_objectid}, ${5:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedOffset': 'prefix': 'GetPlayerObjectAttachedOffset' 'body': 'GetPlayerObjectAttachedOffset(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fRotX}, ${7:&Float:fRotY}, ${8:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectMaterialSlotUsed': 'prefix': 'IsPlayerObjectMaterialSlotUsed' 'body': 'IsPlayerObjectMaterialSlotUsed(${1:playerid}, ${2:objectid}, ${3:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterial': 'prefix': 'GetPlayerObjectMaterial' 'body': 'GetPlayerObjectMaterial(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:&modelid}, ${5:txdname[]}, ${6:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterialText': 'prefix': 'GetPlayerObjectMaterialText' 'body': 'GetPlayerObjectMaterialText(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:text[]}, ${5:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectNoCameraCol': 'prefix': 'IsPlayerObjectNoCameraCol' 'body': 'IsPlayerObjectNoCameraCol(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingPlayerObjectID': 'prefix': 'GetPlayerSurfingPlayerObjectID' 'body': 'GetPlayerSurfingPlayerObjectID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCameraTargetPlayerObj': 'prefix': 'GetPlayerCameraTargetPlayerObj' 'body': 'GetPlayerCameraTargetPlayerObj(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectType': 'prefix': 'GetObjectType' 'body': 'GetObjectType(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerAttachedObject': 'prefix': 'GetPlayerAttachedObject' 'body': 'GetPlayerAttachedObject(${1:playerid}, ${2:index}, ${3:&modelid}, ${4:&bone}, ${5:&Float:fX}, ${6:&Float:fY}, ${7:&Float:fZ}, ${8:&Float:fRotX}, ${9:&Float:fRotY}, ${10:&Float:fRotZ}, ${11:&Float:fSacleX}, ${12:&Float:fScaleY}, ${13:&Float:fScaleZ}, ${14:&materialcolor1}, ${15:&materialcolor2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AttachPlayerObjectToObject': 'prefix': 'AttachPlayerObjectToObject' 'body': 'AttachPlayerObjectToObject(${1:playerid}, ${2:objectid}, ${3:attachtoid}, ${4:Float:OffsetX}, ${5:Float:OffsetY}, ${6:Float:OffsetZ}, ${7:Float:RotX}, ${8:Float:RotY}, ${9:Float:RotZ}, ${10:SyncRotation = 1})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ClearBanList': 'prefix': 'ClearBanList' 'body': 'ClearBanList()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsBanned': 'prefix': 'IsBanned' 'body': 'IsBanned(${1:const ipaddress[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetTimeoutTime': 'prefix': 'SetTimeoutTime' 'body': 'SetTimeoutTime(${1:playerid}, ${2:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetLocalIP': 'prefix': 'GetLocalIP' 'body': 'GetLocalIP(${1:index}, ${2:localip[]}, ${3:len = sizeof(localip})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleSpawnInfo': 'prefix': 'GetVehicleSpawnInfo' 'body': 'GetVehicleSpawnInfo(${1:vehicleid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRot}, ${6:&color1}, ${7:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleSpawnInfo': 'prefix': 'SetVehicleSpawnInfo' 'body': 'SetVehicleSpawnInfo(${1:vehicleid}, ${2:modelid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:Float:fAngle}, ${7:color1}, ${8:color2}, ${9:respawntime = -2}, ${10:interior = -2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleColor': 'prefix': 'GetVehicleColor' 'body': 'GetVehicleColor(${1:vehicleid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehiclePaintjob': 'prefix': 'GetVehiclePaintjob' 'body': 'GetVehiclePaintjob(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleInterior': 'prefix': 'GetVehicleInterior' 'body': 'GetVehicleInterior(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleNumberPlate': 'prefix': 'GetVehicleNumberPlate' 'body': 'GetVehicleNumberPlate(${1:vehicleid}, ${2:plate[]}, ${3:len = sizeof(plate})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnDelay': 'prefix': 'SetVehicleRespawnDelay' 'body': 'SetVehicleRespawnDelay(${1:vehicleid}, ${2:delay})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnDelay': 'prefix': 'GetVehicleRespawnDelay' 'body': 'GetVehicleRespawnDelay(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleOccupiedTick': 'prefix': 'SetVehicleOccupiedTick' 'body': 'SetVehicleOccupiedTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleOccupiedTick': 'prefix': 'GetVehicleOccupiedTick' 'body': 'GetVehicleOccupiedTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnTick': 'prefix': 'SetVehicleRespawnTick' 'body': 'SetVehicleRespawnTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnTick': 'prefix': 'GetVehicleRespawnTick' 'body': 'GetVehicleRespawnTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleLastDriver': 'prefix': 'GetVehicleLastDriver' 'body': 'GetVehicleLastDriver(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleCab': 'prefix': 'GetVehicleCab' 'body': 'GetVehicleCab(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasVehicleBeenOccupied': 'prefix': 'HasVehicleBeenOccupied' 'body': 'HasVehicleBeenOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleBeenOccupied': 'prefix': 'SetVehicleBeenOccupied' 'body': 'SetVehicleBeenOccupied(${1:vehicleid}, ${2:occupied})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleOccupied': 'prefix': 'IsVehicleOccupied' 'body': 'IsVehicleOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleDead': 'prefix': 'IsVehicleDead' 'body': 'IsVehicleDead(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelCount': 'prefix': 'GetVehicleModelCount' 'body': 'GetVehicleModelCount(${1:modelid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelsUsed': 'prefix': 'GetVehicleModelsUsed' 'body': 'GetVehicleModelsUsed()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidGangZone': 'prefix': 'IsValidGangZone' 'body': 'IsValidGangZone(${1:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInGangZone': 'prefix': 'IsPlayerInGangZone' 'body': 'IsPlayerInGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneVisibleForPlayer': 'prefix': 'IsGangZoneVisibleForPlayer' 'body': 'IsGangZoneVisibleForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetColorForPlayer': 'prefix': 'GangZoneGetColorForPlayer' 'body': 'GangZoneGetColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetFlashColorForPlayer': 'prefix': 'GangZoneGetFlashColorForPlayer' 'body': 'GangZoneGetFlashColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneFlashingForPlayer': 'prefix': 'IsGangZoneFlashingForPlayer' 'body': 'IsGangZoneFlashingForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetPos': 'prefix': 'GangZoneGetPos' 'body': 'GangZoneGetPos(${1:zoneid}, ${2:&Float:fMinX}, ${3:&Float:fMinY}, ${4:&Float:fMaxX}, ${5:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerGangZone': 'prefix': 'CreatePlayerGangZone' 'body': 'CreatePlayerGangZone(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneDestroy': 'prefix': 'PlayerGangZoneDestroy' 'body': 'PlayerGangZoneDestroy(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneShow': 'prefix': 'PlayerGangZoneShow' 'body': 'PlayerGangZoneShow(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneHide': 'prefix': 'PlayerGangZoneHide' 'body': 'PlayerGangZoneHide(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneFlash': 'prefix': 'PlayerGangZoneFlash' 'body': 'PlayerGangZoneFlash(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneStopFlash': 'prefix': 'PlayerGangZoneStopFlash' 'body': 'PlayerGangZoneStopFlash(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerGangZone': 'prefix': 'IsValidPlayerGangZone' 'body': 'IsValidPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInPlayerGangZone': 'prefix': 'IsPlayerInPlayerGangZone' 'body': 'IsPlayerInPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneVisible': 'prefix': 'IsPlayerGangZoneVisible' 'body': 'IsPlayerGangZoneVisible(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetColor': 'prefix': 'PlayerGangZoneGetColor' 'body': 'PlayerGangZoneGetColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetFlashColor': 'prefix': 'PlayerGangZoneGetFlashColor' 'body': 'PlayerGangZoneGetFlashColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneFlashing': 'prefix': 'IsPlayerGangZoneFlashing' 'body': 'IsPlayerGangZoneFlashing(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetPos': 'prefix': 'PlayerGangZoneGetPos' 'body': 'PlayerGangZoneGetPos(${1:playerid}, ${2:zoneid}, ${3:&Float:fMinX}, ${4:&Float:fMinY}, ${5:&Float:fMaxX}, ${6:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidTextDraw': 'prefix': 'IsValidTextDraw' 'body': 'IsValidTextDraw(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsTextDrawVisibleForPlayer': 'prefix': 'IsTextDrawVisibleForPlayer' 'body': 'IsTextDrawVisibleForPlayer(${1:playerid}, ${2:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetString': 'prefix': 'TextDrawGetString' 'body': 'TextDrawGetString(${1:Text:textdrawid}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawSetPos': 'prefix': 'TextDrawSetPos' 'body': 'TextDrawSetPos(${1:Text:textdrawid}, ${2:Float:fX}, ${3:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetLetterSize': 'prefix': 'TextDrawGetLetterSize' 'body': 'TextDrawGetLetterSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetTextSize': 'prefix': 'TextDrawGetTextSize' 'body': 'TextDrawGetTextSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPos': 'prefix': 'TextDrawGetPos' 'body': 'TextDrawGetPos(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetColor': 'prefix': 'TextDrawGetColor' 'body': 'TextDrawGetColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBoxColor': 'prefix': 'TextDrawGetBoxColor' 'body': 'TextDrawGetBoxColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBackgroundColor': 'prefix': 'TextDrawGetBackgroundColor' 'body': 'TextDrawGetBackgroundColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetShadow': 'prefix': 'TextDrawGetShadow' 'body': 'TextDrawGetShadow(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetOutline': 'prefix': 'TextDrawGetOutline' 'body': 'TextDrawGetOutline(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetFont': 'prefix': 'TextDrawGetFont' 'body': 'TextDrawGetFont(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsBox': 'prefix': 'TextDrawIsBox' 'body': 'TextDrawIsBox(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsProportional': 'prefix': 'TextDrawIsProportional' 'body': 'TextDrawIsProportional(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsSelectable': 'prefix': 'TextDrawIsSelectable' 'body': 'TextDrawIsSelectable(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetAlignment': 'prefix': 'TextDrawGetAlignment' 'body': 'TextDrawGetAlignment(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewModel': 'prefix': 'TextDrawGetPreviewModel' 'body': 'TextDrawGetPreviewModel(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewRot': 'prefix': 'TextDrawGetPreviewRot' 'body': 'TextDrawGetPreviewRot(${1:Text:textdrawid}, ${2:&Float:fRotX}, ${3:&Float:fRotY}, ${4:&Float:fRotZ}, ${5:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewVehCol': 'prefix': 'TextDrawGetPreviewVehCol' 'body': 'TextDrawGetPreviewVehCol(${1:Text:textdrawid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerTextDraw': 'prefix': 'IsValidPlayerTextDraw' 'body': 'IsValidPlayerTextDraw(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerTextDrawVisible': 'prefix': 'IsPlayerTextDrawVisible' 'body': 'IsPlayerTextDrawVisible(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetString': 'prefix': 'PlayerTextDrawGetString' 'body': 'PlayerTextDrawGetString(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawSetPos': 'prefix': 'PlayerTextDrawSetPos' 'body': 'PlayerTextDrawSetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:Float:fX}, ${4:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetLetterSize': 'prefix': 'PlayerTextDrawGetLetterSize' 'body': 'PlayerTextDrawGetLetterSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetTextSize': 'prefix': 'PlayerTextDrawGetTextSize' 'body': 'PlayerTextDrawGetTextSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPos': 'prefix': 'PlayerTextDrawGetPos' 'body': 'PlayerTextDrawGetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetColor': 'prefix': 'PlayerTextDrawGetColor' 'body': 'PlayerTextDrawGetColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBoxColor': 'prefix': 'PlayerTextDrawGetBoxColor' 'body': 'PlayerTextDrawGetBoxColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBackgroundCol': 'prefix': 'PlayerTextDrawGetBackgroundCol' 'body': 'PlayerTextDrawGetBackgroundCol(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetShadow': 'prefix': 'PlayerTextDrawGetShadow' 'body': 'PlayerTextDrawGetShadow(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetOutline': 'prefix': 'PlayerTextDrawGetOutline' 'body': 'PlayerTextDrawGetOutline(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetFont': 'prefix': 'PlayerTextDrawGetFont' 'body': 'PlayerTextDrawGetFont(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsBox': 'prefix': 'PlayerTextDrawIsBox' 'body': 'PlayerTextDrawIsBox(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsProportional': 'prefix': 'PlayerTextDrawIsProportional' 'body': 'PlayerTextDrawIsProportional(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsSelectable': 'prefix': 'PlayerTextDrawIsSelectable' 'body': 'PlayerTextDrawIsSelectable(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetAlignment': 'prefix': 'PlayerTextDrawGetAlignment' 'body': 'PlayerTextDrawGetAlignment(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewModel': 'prefix': 'PlayerTextDrawGetPreviewModel' 'body': 'PlayerTextDrawGetPreviewModel(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewRot': 'prefix': 'PlayerTextDrawGetPreviewRot' 'body': 'PlayerTextDrawGetPreviewRot(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fRotX}, ${4:&Float:fRotY}, ${5:&Float:fRotZ}, ${6:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewVehCol': 'prefix': 'PlayerTextDrawGetPreviewVehCol' 'body': 'PlayerTextDrawGetPreviewVehCol(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&color1}, ${4:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValid3DTextLabel': 'prefix': 'IsValid3DTextLabel' 'body': 'IsValid3DTextLabel(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Is3DTextLabelStreamedIn': 'prefix': 'Is3DTextLabelStreamedIn' 'body': 'Is3DTextLabelStreamedIn(${1:playerid}, ${2:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelText': 'prefix': 'Get3DTextLabelText' 'body': 'Get3DTextLabelText(${1:Text3D:id}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelColor': 'prefix': 'Get3DTextLabelColor' 'body': 'Get3DTextLabelColor(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelPos': 'prefix': 'Get3DTextLabelPos' 'body': 'Get3DTextLabelPos(${1:Text3D:id}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelDrawDistance': 'prefix': 'Get3DTextLabelDrawDistance' 'body': 'Get3DTextLabelDrawDistance(${1:Text3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelLOS': 'prefix': 'Get3DTextLabelLOS' 'body': 'Get3DTextLabelLOS(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelVirtualWorld': 'prefix': 'Get3DTextLabelVirtualWorld' 'body': 'Get3DTextLabelVirtualWorld(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelAttachedData': 'prefix': 'Get3DTextLabelAttachedData' 'body': 'Get3DTextLabelAttachedData(${1:Text3D:id}, ${2:&attached_playerid}, ${3:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayer3DTextLabel': 'prefix': 'IsValidPlayer3DTextLabel' 'body': 'IsValidPlayer3DTextLabel(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelText': 'prefix': 'GetPlayer3DTextLabelText' 'body': 'GetPlayer3DTextLabelText(${1:playerid}, ${2:PlayerText3D:id}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelColor': 'prefix': 'GetPlayer3DTextLabelColor' 'body': 'GetPlayer3DTextLabelColor(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelPos': 'prefix': 'GetPlayer3DTextLabelPos' 'body': 'GetPlayer3DTextLabelPos(${1:playerid}, ${2:PlayerText3D:id}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelDrawDist': 'prefix': 'GetPlayer3DTextLabelDrawDist' 'body': 'GetPlayer3DTextLabelDrawDist(${1:playerid}, ${2:PlayerText3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelLOS': 'prefix': 'GetPlayer3DTextLabelLOS' 'body': 'GetPlayer3DTextLabelLOS(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelVirtualW': 'prefix': 'GetPlayer3DTextLabelVirtualW' 'body': 'GetPlayer3DTextLabelVirtualW(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelAttached': 'prefix': 'GetPlayer3DTextLabelAttached' 'body': 'GetPlayer3DTextLabelAttached(${1:playerid}, ${2:PlayerText3D:id}, ${3:&attached_playerid}, ${4:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuDisabled': 'prefix': 'IsMenuDisabled' 'body': 'IsMenuDisabled(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuRowDisabled': 'prefix': 'IsMenuRowDisabled' 'body': 'IsMenuRowDisabled(${1:Menu:menuid}, ${2:row})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumns': 'prefix': 'GetMenuColumns' 'body': 'GetMenuColumns(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItems': 'prefix': 'GetMenuItems' 'body': 'GetMenuItems(${1:Menu:menuid}, ${2:column})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuPos': 'prefix': 'GetMenuPos' 'body': 'GetMenuPos(${1:Menu:menuid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnWidth': 'prefix': 'GetMenuColumnWidth' 'body': 'GetMenuColumnWidth(${1:Menu:menuid}, ${2:&Float:fColumn1}, ${3:&Float:fColumn2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnHeader': 'prefix': 'GetMenuColumnHeader' 'body': 'GetMenuColumnHeader(${1:Menu:menuid}, ${2:column}, ${3:header[]}, ${4:len = sizeof(header})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItem': 'prefix': 'GetMenuItem' 'body': 'GetMenuItem(${1:Menu:menuid}, ${2:column}, ${3:itemid}, ${4:item[]}, ${5:len = sizeof(item})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPickup': 'prefix': 'IsValidPickup' 'body': 'IsValidPickup(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPickupStreamedIn': 'prefix': 'IsPickupStreamedIn' 'body': 'IsPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupPos': 'prefix': 'GetPickupPos' 'body': 'GetPickupPos(${1:pickupid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupModel': 'prefix': 'GetPickupModel' 'body': 'GetPickupModel(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupType': 'prefix': 'GetPickupType' 'body': 'GetPickupType(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupVirtualWorld': 'prefix': 'GetPickupVirtualWorld' 'body': 'GetPickupVirtualWorld(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerPickup': 'prefix': 'CreatePlayerPickup' 'body': 'CreatePlayerPickup(${1:playerid}, ${2:model}, ${3:type}, ${4:Float:X}, ${5:Float:Y}, ${6:Float:Z}, ${7:virtualworld = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DestroyPlayerPickup': 'prefix': 'DestroyPlayerPickup' 'body': 'DestroyPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerPickup': 'prefix': 'IsValidPlayerPickup' 'body': 'IsValidPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPickupStreamedIn': 'prefix': 'IsPlayerPickupStreamedIn' 'body': 'IsPlayerPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupPos': 'prefix': 'GetPlayerPickupPos' 'body': 'GetPlayerPickupPos(${1:playerid}, ${2:pickupid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupModel': 'prefix': 'GetPlayerPickupModel' 'body': 'GetPlayerPickupModel(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupType': 'prefix': 'GetPlayerPickupType' 'body': 'GetPlayerPickupType(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupVirtualWorld': 'prefix': 'GetPlayerPickupVirtualWorld' 'body': 'GetPlayerPickupVirtualWorld(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColCount': 'prefix': 'GetColCount' 'body': 'GetColCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereRadius': 'prefix': 'GetColSphereRadius' 'body': 'GetColSphereRadius(${1:modelid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereOffset': 'prefix': 'GetColSphereOffset' 'body': 'GetColSphereOffset(${1:modelid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessagef': 'prefix': 'SendClientMessagef' 'body': 'SendClientMessagef(${1:playerid}, ${2:color}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessageToAllf': 'prefix': 'SendClientMessageToAllf' 'body': 'SendClientMessageToAllf(${1:color}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForPlayerf': 'prefix': 'GameTextForPlayerf' 'body': 'GameTextForPlayerf(${1:playerid}, ${2:displaytime}, ${3:style}, ${4:const message[]}, ${5:{Float}, ${6:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForAllf': 'prefix': 'GameTextForAllf' 'body': 'GameTextForAllf(${1:displaytime}, ${2:style}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToPlayerf': 'prefix': 'SendPlayerMessageToPlayerf' 'body': 'SendPlayerMessageToPlayerf(${1:playerid}, ${2:senderid}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToAllf': 'prefix': 'SendPlayerMessageToAllf' 'body': 'SendPlayerMessageToAllf(${1:senderid}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRconCommandf': 'prefix': 'SendRconCommandf' 'body': 'SendRconCommandf(${1:const command[]}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetWeaponSlot': 'prefix': 'GetWeaponSlot' 'body': 'GetWeaponSlot(${1:weaponid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRPC': 'prefix': 'SendRPC' 'body': 'SendRPC(${1:playerid}, ${2:RPC}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendData': 'prefix': 'SendData' 'body': 'SendData(${1:playerid}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetGravity': 'prefix': 'GetGravity' 'body': 'GetGravity()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499'
true
# YSF Snippets for Atom, automatically generated # Generator created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI '.source.pwn, .source.inc': 'execute': 'prefix': 'execute' 'body': 'execute(${1:const command[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ffind': 'prefix': 'ffind' 'body': 'ffind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'frename': 'prefix': 'frename' 'body': 'frename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dfind': 'prefix': 'dfind' 'body': 'dfind(${1:const pattern[]}, ${2:filename[]}, ${3:len}, ${4:&idx})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'dcreate': 'prefix': 'dcreate' 'body': 'dcreate(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'drename': 'prefix': 'drename' 'body': 'drename(${1:const oldname[]}, ${2:const newname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetModeRestartTime': 'prefix': 'SetModeRestartTime' 'body': 'SetModeRestartTime(${1:Float:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetModeRestartTime': 'prefix': 'GetModeRestartTime' 'body': 'GetModeRestartTime()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxPlayers': 'prefix': 'SetMaxPlayers' 'body': 'SetMaxPlayers(${1:maxplayers})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetMaxNPCs': 'prefix': 'SetMaxNPCs' 'body': 'SetMaxNPCs(${1:maxnpcs})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'LoadFilterScript': 'prefix': 'LoadFilterScript' 'body': 'LoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'UnLoadFilterScript': 'prefix': 'UnLoadFilterScript' 'body': 'UnLoadFilterScript(${1:const scriptname[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptCount': 'prefix': 'GetFilterScriptCount' 'body': 'GetFilterScriptCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetFilterScriptName': 'prefix': 'GetFilterScriptName' 'body': 'GetFilterScriptName(${1:id}, ${2:name[]}, ${3:len = sizeof(name})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddServerRule': 'prefix': 'AddServerRule' 'body': 'AddServerRule(${1:const name[]}, ${2:const value[]}, ${3:E_SERVER_RULE_FLAGS:flags = CON_VARFLAG_RULE})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRule': 'prefix': 'SetServerRule' 'body': 'SetServerRule(${1:const name[]}, ${2:const value[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidServerRule': 'prefix': 'IsValidServerRule' 'body': 'IsValidServerRule(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetServerRuleFlags': 'prefix': 'SetServerRuleFlags' 'body': 'SetServerRuleFlags(${1:const name[]}, ${2:E_SERVER_RULE_FLAGS:flags})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'E_SERVER_RULE_FLAGS:GetServerRuleFlags': 'prefix': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags' 'body': 'E_SERVER_RULE_FLAGS:GetServerRuleFlags(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetServerSettings': 'prefix': 'GetServerSettings' 'body': 'GetServerSettings(${1:&showplayermarkes}, ${2:&shownametags}, ${3:&stuntbonus}, ${4:&useplayerpedanims}, ${5:&bLimitchatradius}, ${6:&disableinteriorenterexits}, ${7:&nametaglos}, ${8:&manualvehicleengine}, ${9:&limitplayermarkers}, ${10:&vehiclefriendlyfire}, ${11:&defaultcameracollision}, ${12:&Float:fGlobalchatradius}, ${13:&Float:fNameTagDrawDistance}, ${14:&Float:fPlayermarkerslimit})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EnableConsoleMSGsForPlayer': 'prefix': 'EnableConsoleMSGsForPlayer' 'body': 'EnableConsoleMSGsForPlayer(${1:playerid}, ${2:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DisableConsoleMSGsForPlayer': 'prefix': 'DisableConsoleMSGsForPlayer' 'body': 'DisableConsoleMSGsForPlayer(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasPlayerConsoleMessages': 'prefix': 'HasPlayerConsoleMessages' 'body': 'HasPlayerConsoleMessages(${1:playerid}, ${2:&color = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetTickRate': 'prefix': 'YSF_SetTickRate' 'body': 'YSF_SetTickRate(${1:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetTickRate': 'prefix': 'YSF_GetTickRate' 'body': 'YSF_GetTickRate()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_EnableNightVisionFix': 'prefix': 'YSF_EnableNightVisionFix' 'body': 'YSF_EnableNightVisionFix(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsNightVisionFixEnabled': 'prefix': 'YSF_IsNightVisionFixEnabled' 'body': 'YSF_IsNightVisionFixEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetExtendedNetStatsEnabled': 'prefix': 'YSF_SetExtendedNetStatsEnabled' 'body': 'YSF_SetExtendedNetStatsEnabled(${1:enable})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_IsExtendedNetStatsEnabled': 'prefix': 'YSF_IsExtendedNetStatsEnabled' 'body': 'YSF_IsExtendedNetStatsEnabled()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_SetAFKAccuracy': 'prefix': 'YSF_SetAFKAccuracy' 'body': 'YSF_SetAFKAccuracy(${1:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'YSF_GetAFKAccuracy': 'prefix': 'YSF_GetAFKAccuracy' 'body': 'YSF_GetAFKAccuracy()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetRecordingDirectory': 'prefix': 'SetRecordingDirectory' 'body': 'SetRecordingDirectory(${1:const dir[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRecordingDirectory': 'prefix': 'GetRecordingDirectory' 'body': 'GetRecordingDirectory(${1:dir[]}, ${2:len = sizeof(dir})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidNickName': 'prefix': 'IsValidNickName' 'body': 'IsValidNickName(${1:const name[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AllowNickNameCharacter': 'prefix': 'AllowNickNameCharacter' 'body': 'AllowNickNameCharacter(${1:character}, ${2:bool:allow})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsNickNameCharacterAllowed': 'prefix': 'IsNickNameCharacterAllowed' 'body': 'IsNickNameCharacterAllowed(${1:character})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetAvailableClasses': 'prefix': 'GetAvailableClasses' 'body': 'GetAvailableClasses()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerClass': 'prefix': 'GetPlayerClass' 'body': 'GetPlayerClass(${1:classid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'EditPlayerClass': 'prefix': 'EditPlayerClass' 'body': 'EditPlayerClass(${1:classid}, ${2:teamid}, ${3:modelid}, ${4:Float:spawn_x}, ${5:Float:spawn_y}, ${6:Float:spawn_z}, ${7:Float:z_angle}, ${8:weapon1}, ${9:weapon1_ammo}, ${10:weapon2}, ${11:weapon2_ammo}, ${12:weapon3}, ${13:weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetRunningTimers': 'prefix': 'GetRunningTimers' 'body': 'GetRunningTimers()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerGravity': 'prefix': 'SetPlayerGravity' 'body': 'SetPlayerGravity(${1:playerid}, ${2:Float:gravity})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerGravity': 'prefix': 'GetPlayerGravity' 'body': 'GetPlayerGravity(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerAdmin': 'prefix': 'SetPlayerAdmin' 'body': 'SetPlayerAdmin(${1:playerid}, ${2:bool:admin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerTeamForPlayer': 'prefix': 'SetPlayerTeamForPlayer' 'body': 'SetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid}, ${3:teamid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTeamForPlayer': 'prefix': 'GetPlayerTeamForPlayer' 'body': 'GetPlayerTeamForPlayer(${1:playerid}, ${2:teamplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerSkinForPlayer': 'prefix': 'SetPlayerSkinForPlayer' 'body': 'SetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid}, ${3:skin})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkinForPlayer': 'prefix': 'GetPlayerSkinForPlayer' 'body': 'GetPlayerSkinForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerNameForPlayer': 'prefix': 'SetPlayerNameForPlayer' 'body': 'SetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:const playername[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerNameForPlayer': 'prefix': 'GetPlayerNameForPlayer' 'body': 'GetPlayerNameForPlayer(${1:playerid}, ${2:nameplayerid}, ${3:playername[]}, ${4:size = sizeof(playername})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFightStyleForPlayer': 'prefix': 'SetPlayerFightStyleForPlayer' 'body': 'SetPlayerFightStyleForPlayer(${1:playerid}, ${2:styleplayerid}, ${3:style})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerFightStyleForPlayer': 'prefix': 'GetPlayerFightStyleForPlayer' 'body': 'GetPlayerFightStyleForPlayer(${1:playerid}, ${2:skinplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerPosForPlayer': 'prefix': 'SetPlayerPosForPlayer' 'body': 'SetPlayerPosForPlayer(${1:playerid}, ${2:posplayerid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerRotationQuatForPlayer': 'prefix': 'SetPlayerRotationQuatForPlayer' 'body': 'SetPlayerRotationQuatForPlayer(${1:playerid}, ${2:quatplayerid}, ${3:Float:w}, ${4:Float:x}, ${5:Float:y}, ${6:Float:z}, ${7:bool:forcesync = true})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ApplyAnimationForPlayer': 'prefix': 'ApplyAnimationForPlayer' 'body': 'ApplyAnimationForPlayer(${1:playerid}, ${2:animplayerid}, ${3:const animlib[]}, ${4:const animname[]}, ${5:Float:fDelta}, ${6:loop}, ${7:lockx}, ${8:locky}, ${9:freeze}, ${10:time})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWeather': 'prefix': 'GetPlayerWeather' 'body': 'GetPlayerWeather(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerWidescreen': 'prefix': 'TogglePlayerWidescreen' 'body': 'TogglePlayerWidescreen(${1:playerid}, ${2:bool:set})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerWidescreenToggled': 'prefix': 'IsPlayerWidescreenToggled' 'body': 'IsPlayerWidescreenToggled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetSpawnInfo': 'prefix': 'GetSpawnInfo' 'body': 'GetSpawnInfo(${1:playerid}, ${2:&teamid}, ${3:&modelid}, ${4:&Float:spawn_x}, ${5:&Float:spawn_y}, ${6:&Float:spawn_z}, ${7:&Float:z_angle}, ${8:&weapon1}, ${9:&weapon1_ammo}, ${10:&weapon2}, ${11:&weapon2_ammo}, ${12:& weapon3}, ${13:&weapon3_ammo})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSkillLevel': 'prefix': 'GetPlayerSkillLevel' 'body': 'GetPlayerSkillLevel(${1:playerid}, ${2:skill})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCheckpointActive': 'prefix': 'IsPlayerCheckpointActive' 'body': 'IsPlayerCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCheckpoint': 'prefix': 'GetPlayerCheckpoint' 'body': 'GetPlayerCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerRaceCheckpointActive': 'prefix': 'IsPlayerRaceCheckpointActive' 'body': 'IsPlayerRaceCheckpointActive(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRaceCheckpoint': 'prefix': 'GetPlayerRaceCheckpoint' 'body': 'GetPlayerRaceCheckpoint(${1:playerid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fNextX}, ${6:&Float:fNextY}, ${7:&Float:fNextZ}, ${8:&Float:fSize})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerWorldBounds': 'prefix': 'GetPlayerWorldBounds' 'body': 'GetPlayerWorldBounds(${1:playerid}, ${2:&Float:x_max}, ${3:&Float:x_min}, ${4:&Float:y_max}, ${5:&Float:y_min})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInModShop': 'prefix': 'IsPlayerInModShop' 'body': 'IsPlayerInModShop(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSirenState': 'prefix': 'GetPlayerSirenState' 'body': 'GetPlayerSirenState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLandingGearState': 'prefix': 'GetPlayerLandingGearState' 'body': 'GetPlayerLandingGearState(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerHydraReactorAngle': 'prefix': 'GetPlayerHydraReactorAngle' 'body': 'GetPlayerHydraReactorAngle(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerTrainSpeed': 'prefix': 'GetPlayerTrainSpeed' 'body': 'GetPlayerTrainSpeed(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerZAim': 'prefix': 'GetPlayerZAim' 'body': 'GetPlayerZAim(${1:playerid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingOffsets': 'prefix': 'GetPlayerSurfingOffsets' 'body': 'GetPlayerSurfingOffsets(${1:playerid}, ${2:&Float:fOffsetX}, ${3:&Float:fOffsetY}, ${4:&Float:fOffsetZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerRotationQuat': 'prefix': 'GetPlayerRotationQuat' 'body': 'GetPlayerRotationQuat(${1:playerid}, ${2:&Float:w}, ${3:&Float:x}, ${4:&Float:y}, ${5:&Float:z})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDialogID': 'prefix': 'GetPlayerDialogID' 'body': 'GetPlayerDialogID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateID': 'prefix': 'GetPlayerSpectateID' 'body': 'GetPlayerSpectateID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSpectateType': 'prefix': 'GetPlayerSpectateType' 'body': 'GetPlayerSpectateType(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedVehicleID': 'prefix': 'GetPlayerLastSyncedVehicleID' 'body': 'GetPlayerLastSyncedVehicleID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerLastSyncedTrailerID': 'prefix': 'GetPlayerLastSyncedTrailerID' 'body': 'GetPlayerLastSyncedTrailerID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendBulletData': 'prefix': 'SendBulletData' 'body': 'SendBulletData(${1:senderid}, ${2:forplayerid = -1}, ${3:weaponid}, ${4:hittype}, ${5:hitid}, ${6:Float:fHitOriginX}, ${7:Float:fHitOriginY}, ${8:Float:fHitOriginZ}, ${9:Float:fHitTargetX}, ${10:Float:fHitTargetY}, ${11:Float:fHitTargetZ}, ${12:Float:fCenterOfHitX}, ${13:Float:fCenterOfHitY}, ${14:Float:fCenterOfHitZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ShowPlayerForPlayer': 'prefix': 'ShowPlayerForPlayer' 'body': 'ShowPlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HidePlayerForPlayer': 'prefix': 'HidePlayerForPlayer' 'body': 'HidePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AddPlayerForPlayer': 'prefix': 'AddPlayerForPlayer' 'body': 'AddPlayerForPlayer(${1:forplayerid}, ${2:playerid}, ${3:isnpc = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'RemovePlayerForPlayer': 'prefix': 'RemovePlayerForPlayer' 'body': 'RemovePlayerForPlayer(${1:forplayerid}, ${2:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerChatBubbleForPlayer': 'prefix': 'SetPlayerChatBubbleForPlayer' 'body': 'SetPlayerChatBubbleForPlayer(${1:forplayerid}, ${2:playerid}, ${3:const text[]}, ${4:color}, ${5:Float:drawdistance}, ${6:expiretime})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ResetPlayerMarkerForPlayer': 'prefix': 'ResetPlayerMarkerForPlayer' 'body': 'ResetPlayerMarkerForPlayer(${1:playerid}, ${2:resetplayerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerVersion': 'prefix': 'SetPlayerVersion' 'body': 'SetPlayerVersion(${1:playerid}, ${2:const version[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerSpawned': 'prefix': 'IsPlayerSpawned' 'body': 'IsPlayerSpawned(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerControllable': 'prefix': 'IsPlayerControllable' 'body': 'IsPlayerControllable(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SpawnForWorld': 'prefix': 'SpawnForWorld' 'body': 'SpawnForWorld(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'BroadcastDeath': 'prefix': 'BroadcastDeath' 'body': 'BroadcastDeath(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerCameraTargetEnabled': 'prefix': 'IsPlayerCameraTargetEnabled' 'body': 'IsPlayerCameraTargetEnabled(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerDisabledKeysSync': 'prefix': 'SetPlayerDisabledKeysSync' 'body': 'SetPlayerDisabledKeysSync(${1:playerid}, ${2:keys}, ${3:updown = 0}, ${4:leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerDisabledKeysSync': 'prefix': 'GetPlayerDisabledKeysSync' 'body': 'GetPlayerDisabledKeysSync(${1:playerid}, ${2:&keys}, ${3:&updown = 0}, ${4:&leftright = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSpawnInfo': 'prefix': 'GetActorSpawnInfo' 'body': 'GetActorSpawnInfo(${1:actorid}, ${2:&skinid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fAngle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorSkin': 'prefix': 'GetActorSkin' 'body': 'GetActorSkin(${1:actorid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetActorAnimation': 'prefix': 'GetActorAnimation' 'body': 'GetActorAnimation(${1:actorid}, ${2:animlib[]}, ${3:animlibsize = sizeof(animlib})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerScoresPingsUpdate': 'prefix': 'TogglePlayerScoresPingsUpdate' 'body': 'TogglePlayerScoresPingsUpdate(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerFakePing': 'prefix': 'TogglePlayerFakePing' 'body': 'TogglePlayerFakePing(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerFakePing': 'prefix': 'SetPlayerFakePing' 'body': 'SetPlayerFakePing(${1:playerid}, ${2:ping})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TogglePlayerInServerQuery': 'prefix': 'TogglePlayerInServerQuery' 'body': 'TogglePlayerInServerQuery(${1:playerid}, ${2:bool:toggle})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerToggledInServerQuery': 'prefix': 'IsPlayerToggledInServerQuery' 'body': 'IsPlayerToggledInServerQuery(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPaused': 'prefix': 'IsPlayerPaused' 'body': 'IsPlayerPaused(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPausedTime': 'prefix': 'GetPlayerPausedTime' 'body': 'GetPlayerPausedTime(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectDrawDistance': 'prefix': 'GetObjectDrawDistance' 'body': 'GetObjectDrawDistance(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetObjectMoveSpeed': 'prefix': 'SetObjectMoveSpeed' 'body': 'SetObjectMoveSpeed(${1:objectid}, ${2:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMoveSpeed': 'prefix': 'GetObjectMoveSpeed' 'body': 'GetObjectMoveSpeed(${1:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectTarget': 'prefix': 'GetObjectTarget' 'body': 'GetObjectTarget(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedData': 'prefix': 'GetObjectAttachedData' 'body': 'GetObjectAttachedData(${1:objectid}, ${2:&attached_vehicleid}, ${3:&attached_objectid}, ${4:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectAttachedOffset': 'prefix': 'GetObjectAttachedOffset' 'body': 'GetObjectAttachedOffset(${1:objectid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRotX}, ${6:&Float:fRotY}, ${7:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectMaterialSlotUsed': 'prefix': 'IsObjectMaterialSlotUsed' 'body': 'IsObjectMaterialSlotUsed(${1:objectid}, ${2:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterial': 'prefix': 'GetObjectMaterial' 'body': 'GetObjectMaterial(${1:objectid}, ${2:materialindex}, ${3:&modelid}, ${4:txdname[]}, ${5:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectMaterialText': 'prefix': 'GetObjectMaterialText' 'body': 'GetObjectMaterialText(${1:objectid}, ${2:materialindex}, ${3:text[]}, ${4:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsObjectNoCameraCol': 'prefix': 'IsObjectNoCameraCol' 'body': 'IsObjectNoCameraCol(${1:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectDrawDistance': 'prefix': 'GetPlayerObjectDrawDistance' 'body': 'GetPlayerObjectDrawDistance(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetPlayerObjectMoveSpeed': 'prefix': 'SetPlayerObjectMoveSpeed' 'body': 'SetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid}, ${3:Float:fSpeed})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMoveSpeed': 'prefix': 'GetPlayerObjectMoveSpeed' 'body': 'GetPlayerObjectMoveSpeed(${1:playerid}, ${2:objectid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectTarget': 'prefix': 'GetPlayerObjectTarget' 'body': 'GetPlayerObjectTarget(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedData': 'prefix': 'GetPlayerObjectAttachedData' 'body': 'GetPlayerObjectAttachedData(${1:playerid}, ${2:objectid}, ${3:&attached_vehicleid}, ${4:&attached_objectid}, ${5:&attached_playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectAttachedOffset': 'prefix': 'GetPlayerObjectAttachedOffset' 'body': 'GetPlayerObjectAttachedOffset(${1:playerid}, ${2:objectid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ}, ${6:&Float:fRotX}, ${7:&Float:fRotY}, ${8:&Float:fRotZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectMaterialSlotUsed': 'prefix': 'IsPlayerObjectMaterialSlotUsed' 'body': 'IsPlayerObjectMaterialSlotUsed(${1:playerid}, ${2:objectid}, ${3:materialindex})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterial': 'prefix': 'GetPlayerObjectMaterial' 'body': 'GetPlayerObjectMaterial(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:&modelid}, ${5:txdname[]}, ${6:txdnamelen = sizeof(txdname})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerObjectMaterialText': 'prefix': 'GetPlayerObjectMaterialText' 'body': 'GetPlayerObjectMaterialText(${1:playerid}, ${2:objectid}, ${3:materialindex}, ${4:text[]}, ${5:textlen = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerObjectNoCameraCol': 'prefix': 'IsPlayerObjectNoCameraCol' 'body': 'IsPlayerObjectNoCameraCol(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerSurfingPlayerObjectID': 'prefix': 'GetPlayerSurfingPlayerObjectID' 'body': 'GetPlayerSurfingPlayerObjectID(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerCameraTargetPlayerObj': 'prefix': 'GetPlayerCameraTargetPlayerObj' 'body': 'GetPlayerCameraTargetPlayerObj(${1:playerid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetObjectType': 'prefix': 'GetObjectType' 'body': 'GetObjectType(${1:playerid}, ${2:objectid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerAttachedObject': 'prefix': 'GetPlayerAttachedObject' 'body': 'GetPlayerAttachedObject(${1:playerid}, ${2:index}, ${3:&modelid}, ${4:&bone}, ${5:&Float:fX}, ${6:&Float:fY}, ${7:&Float:fZ}, ${8:&Float:fRotX}, ${9:&Float:fRotY}, ${10:&Float:fRotZ}, ${11:&Float:fSacleX}, ${12:&Float:fScaleY}, ${13:&Float:fScaleZ}, ${14:&materialcolor1}, ${15:&materialcolor2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'AttachPlayerObjectToObject': 'prefix': 'AttachPlayerObjectToObject' 'body': 'AttachPlayerObjectToObject(${1:playerid}, ${2:objectid}, ${3:attachtoid}, ${4:Float:OffsetX}, ${5:Float:OffsetY}, ${6:Float:OffsetZ}, ${7:Float:RotX}, ${8:Float:RotY}, ${9:Float:RotZ}, ${10:SyncRotation = 1})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'ClearBanList': 'prefix': 'ClearBanList' 'body': 'ClearBanList()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsBanned': 'prefix': 'IsBanned' 'body': 'IsBanned(${1:const ipaddress[]})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetTimeoutTime': 'prefix': 'SetTimeoutTime' 'body': 'SetTimeoutTime(${1:playerid}, ${2:time_ms})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetLocalIP': 'prefix': 'GetLocalIP' 'body': 'GetLocalIP(${1:index}, ${2:localip[]}, ${3:len = sizeof(localip})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleSpawnInfo': 'prefix': 'GetVehicleSpawnInfo' 'body': 'GetVehicleSpawnInfo(${1:vehicleid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ}, ${5:&Float:fRot}, ${6:&color1}, ${7:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleSpawnInfo': 'prefix': 'SetVehicleSpawnInfo' 'body': 'SetVehicleSpawnInfo(${1:vehicleid}, ${2:modelid}, ${3:Float:fX}, ${4:Float:fY}, ${5:Float:fZ}, ${6:Float:fAngle}, ${7:color1}, ${8:color2}, ${9:respawntime = -2}, ${10:interior = -2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleColor': 'prefix': 'GetVehicleColor' 'body': 'GetVehicleColor(${1:vehicleid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehiclePaintjob': 'prefix': 'GetVehiclePaintjob' 'body': 'GetVehiclePaintjob(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleInterior': 'prefix': 'GetVehicleInterior' 'body': 'GetVehicleInterior(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleNumberPlate': 'prefix': 'GetVehicleNumberPlate' 'body': 'GetVehicleNumberPlate(${1:vehicleid}, ${2:plate[]}, ${3:len = sizeof(plate})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnDelay': 'prefix': 'SetVehicleRespawnDelay' 'body': 'SetVehicleRespawnDelay(${1:vehicleid}, ${2:delay})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnDelay': 'prefix': 'GetVehicleRespawnDelay' 'body': 'GetVehicleRespawnDelay(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleOccupiedTick': 'prefix': 'SetVehicleOccupiedTick' 'body': 'SetVehicleOccupiedTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleOccupiedTick': 'prefix': 'GetVehicleOccupiedTick' 'body': 'GetVehicleOccupiedTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleRespawnTick': 'prefix': 'SetVehicleRespawnTick' 'body': 'SetVehicleRespawnTick(${1:vehicleid}, ${2:ticks})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleRespawnTick': 'prefix': 'GetVehicleRespawnTick' 'body': 'GetVehicleRespawnTick(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleLastDriver': 'prefix': 'GetVehicleLastDriver' 'body': 'GetVehicleLastDriver(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleCab': 'prefix': 'GetVehicleCab' 'body': 'GetVehicleCab(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'HasVehicleBeenOccupied': 'prefix': 'HasVehicleBeenOccupied' 'body': 'HasVehicleBeenOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SetVehicleBeenOccupied': 'prefix': 'SetVehicleBeenOccupied' 'body': 'SetVehicleBeenOccupied(${1:vehicleid}, ${2:occupied})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleOccupied': 'prefix': 'IsVehicleOccupied' 'body': 'IsVehicleOccupied(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsVehicleDead': 'prefix': 'IsVehicleDead' 'body': 'IsVehicleDead(${1:vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelCount': 'prefix': 'GetVehicleModelCount' 'body': 'GetVehicleModelCount(${1:modelid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetVehicleModelsUsed': 'prefix': 'GetVehicleModelsUsed' 'body': 'GetVehicleModelsUsed()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidGangZone': 'prefix': 'IsValidGangZone' 'body': 'IsValidGangZone(${1:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInGangZone': 'prefix': 'IsPlayerInGangZone' 'body': 'IsPlayerInGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneVisibleForPlayer': 'prefix': 'IsGangZoneVisibleForPlayer' 'body': 'IsGangZoneVisibleForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetColorForPlayer': 'prefix': 'GangZoneGetColorForPlayer' 'body': 'GangZoneGetColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetFlashColorForPlayer': 'prefix': 'GangZoneGetFlashColorForPlayer' 'body': 'GangZoneGetFlashColorForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsGangZoneFlashingForPlayer': 'prefix': 'IsGangZoneFlashingForPlayer' 'body': 'IsGangZoneFlashingForPlayer(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GangZoneGetPos': 'prefix': 'GangZoneGetPos' 'body': 'GangZoneGetPos(${1:zoneid}, ${2:&Float:fMinX}, ${3:&Float:fMinY}, ${4:&Float:fMaxX}, ${5:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerGangZone': 'prefix': 'CreatePlayerGangZone' 'body': 'CreatePlayerGangZone(${1:playerid}, ${2:Float:minx}, ${3:Float:miny}, ${4:Float:maxx}, ${5:Float:maxy})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneDestroy': 'prefix': 'PlayerGangZoneDestroy' 'body': 'PlayerGangZoneDestroy(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneShow': 'prefix': 'PlayerGangZoneShow' 'body': 'PlayerGangZoneShow(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneHide': 'prefix': 'PlayerGangZoneHide' 'body': 'PlayerGangZoneHide(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneFlash': 'prefix': 'PlayerGangZoneFlash' 'body': 'PlayerGangZoneFlash(${1:playerid}, ${2:zoneid}, ${3:color})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneStopFlash': 'prefix': 'PlayerGangZoneStopFlash' 'body': 'PlayerGangZoneStopFlash(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerGangZone': 'prefix': 'IsValidPlayerGangZone' 'body': 'IsValidPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerInPlayerGangZone': 'prefix': 'IsPlayerInPlayerGangZone' 'body': 'IsPlayerInPlayerGangZone(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneVisible': 'prefix': 'IsPlayerGangZoneVisible' 'body': 'IsPlayerGangZoneVisible(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetColor': 'prefix': 'PlayerGangZoneGetColor' 'body': 'PlayerGangZoneGetColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetFlashColor': 'prefix': 'PlayerGangZoneGetFlashColor' 'body': 'PlayerGangZoneGetFlashColor(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerGangZoneFlashing': 'prefix': 'IsPlayerGangZoneFlashing' 'body': 'IsPlayerGangZoneFlashing(${1:playerid}, ${2:zoneid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerGangZoneGetPos': 'prefix': 'PlayerGangZoneGetPos' 'body': 'PlayerGangZoneGetPos(${1:playerid}, ${2:zoneid}, ${3:&Float:fMinX}, ${4:&Float:fMinY}, ${5:&Float:fMaxX}, ${6:&Float:fMaxY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidTextDraw': 'prefix': 'IsValidTextDraw' 'body': 'IsValidTextDraw(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsTextDrawVisibleForPlayer': 'prefix': 'IsTextDrawVisibleForPlayer' 'body': 'IsTextDrawVisibleForPlayer(${1:playerid}, ${2:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetString': 'prefix': 'TextDrawGetString' 'body': 'TextDrawGetString(${1:Text:textdrawid}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawSetPos': 'prefix': 'TextDrawSetPos' 'body': 'TextDrawSetPos(${1:Text:textdrawid}, ${2:Float:fX}, ${3:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetLetterSize': 'prefix': 'TextDrawGetLetterSize' 'body': 'TextDrawGetLetterSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetTextSize': 'prefix': 'TextDrawGetTextSize' 'body': 'TextDrawGetTextSize(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPos': 'prefix': 'TextDrawGetPos' 'body': 'TextDrawGetPos(${1:Text:textdrawid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetColor': 'prefix': 'TextDrawGetColor' 'body': 'TextDrawGetColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBoxColor': 'prefix': 'TextDrawGetBoxColor' 'body': 'TextDrawGetBoxColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetBackgroundColor': 'prefix': 'TextDrawGetBackgroundColor' 'body': 'TextDrawGetBackgroundColor(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetShadow': 'prefix': 'TextDrawGetShadow' 'body': 'TextDrawGetShadow(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetOutline': 'prefix': 'TextDrawGetOutline' 'body': 'TextDrawGetOutline(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetFont': 'prefix': 'TextDrawGetFont' 'body': 'TextDrawGetFont(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsBox': 'prefix': 'TextDrawIsBox' 'body': 'TextDrawIsBox(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsProportional': 'prefix': 'TextDrawIsProportional' 'body': 'TextDrawIsProportional(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawIsSelectable': 'prefix': 'TextDrawIsSelectable' 'body': 'TextDrawIsSelectable(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetAlignment': 'prefix': 'TextDrawGetAlignment' 'body': 'TextDrawGetAlignment(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewModel': 'prefix': 'TextDrawGetPreviewModel' 'body': 'TextDrawGetPreviewModel(${1:Text:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewRot': 'prefix': 'TextDrawGetPreviewRot' 'body': 'TextDrawGetPreviewRot(${1:Text:textdrawid}, ${2:&Float:fRotX}, ${3:&Float:fRotY}, ${4:&Float:fRotZ}, ${5:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'TextDrawGetPreviewVehCol': 'prefix': 'TextDrawGetPreviewVehCol' 'body': 'TextDrawGetPreviewVehCol(${1:Text:textdrawid}, ${2:&color1}, ${3:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerTextDraw': 'prefix': 'IsValidPlayerTextDraw' 'body': 'IsValidPlayerTextDraw(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerTextDrawVisible': 'prefix': 'IsPlayerTextDrawVisible' 'body': 'IsPlayerTextDrawVisible(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetString': 'prefix': 'PlayerTextDrawGetString' 'body': 'PlayerTextDrawGetString(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawSetPos': 'prefix': 'PlayerTextDrawSetPos' 'body': 'PlayerTextDrawSetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:Float:fX}, ${4:Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetLetterSize': 'prefix': 'PlayerTextDrawGetLetterSize' 'body': 'PlayerTextDrawGetLetterSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetTextSize': 'prefix': 'PlayerTextDrawGetTextSize' 'body': 'PlayerTextDrawGetTextSize(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPos': 'prefix': 'PlayerTextDrawGetPos' 'body': 'PlayerTextDrawGetPos(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fX}, ${4:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetColor': 'prefix': 'PlayerTextDrawGetColor' 'body': 'PlayerTextDrawGetColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBoxColor': 'prefix': 'PlayerTextDrawGetBoxColor' 'body': 'PlayerTextDrawGetBoxColor(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetBackgroundCol': 'prefix': 'PlayerTextDrawGetBackgroundCol' 'body': 'PlayerTextDrawGetBackgroundCol(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetShadow': 'prefix': 'PlayerTextDrawGetShadow' 'body': 'PlayerTextDrawGetShadow(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetOutline': 'prefix': 'PlayerTextDrawGetOutline' 'body': 'PlayerTextDrawGetOutline(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetFont': 'prefix': 'PlayerTextDrawGetFont' 'body': 'PlayerTextDrawGetFont(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsBox': 'prefix': 'PlayerTextDrawIsBox' 'body': 'PlayerTextDrawIsBox(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsProportional': 'prefix': 'PlayerTextDrawIsProportional' 'body': 'PlayerTextDrawIsProportional(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawIsSelectable': 'prefix': 'PlayerTextDrawIsSelectable' 'body': 'PlayerTextDrawIsSelectable(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetAlignment': 'prefix': 'PlayerTextDrawGetAlignment' 'body': 'PlayerTextDrawGetAlignment(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewModel': 'prefix': 'PlayerTextDrawGetPreviewModel' 'body': 'PlayerTextDrawGetPreviewModel(${1:playerid}, ${2:PlayerText:textdrawid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewRot': 'prefix': 'PlayerTextDrawGetPreviewRot' 'body': 'PlayerTextDrawGetPreviewRot(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&Float:fRotX}, ${4:&Float:fRotY}, ${5:&Float:fRotZ}, ${6:&Float:fZoom})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'PlayerTextDrawGetPreviewVehCol': 'prefix': 'PlayerTextDrawGetPreviewVehCol' 'body': 'PlayerTextDrawGetPreviewVehCol(${1:playerid}, ${2:PlayerText:textdrawid}, ${3:&color1}, ${4:&color2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValid3DTextLabel': 'prefix': 'IsValid3DTextLabel' 'body': 'IsValid3DTextLabel(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Is3DTextLabelStreamedIn': 'prefix': 'Is3DTextLabelStreamedIn' 'body': 'Is3DTextLabelStreamedIn(${1:playerid}, ${2:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelText': 'prefix': 'Get3DTextLabelText' 'body': 'Get3DTextLabelText(${1:Text3D:id}, ${2:text[]}, ${3:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelColor': 'prefix': 'Get3DTextLabelColor' 'body': 'Get3DTextLabelColor(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelPos': 'prefix': 'Get3DTextLabelPos' 'body': 'Get3DTextLabelPos(${1:Text3D:id}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelDrawDistance': 'prefix': 'Get3DTextLabelDrawDistance' 'body': 'Get3DTextLabelDrawDistance(${1:Text3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelLOS': 'prefix': 'Get3DTextLabelLOS' 'body': 'Get3DTextLabelLOS(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelVirtualWorld': 'prefix': 'Get3DTextLabelVirtualWorld' 'body': 'Get3DTextLabelVirtualWorld(${1:Text3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'Get3DTextLabelAttachedData': 'prefix': 'Get3DTextLabelAttachedData' 'body': 'Get3DTextLabelAttachedData(${1:Text3D:id}, ${2:&attached_playerid}, ${3:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayer3DTextLabel': 'prefix': 'IsValidPlayer3DTextLabel' 'body': 'IsValidPlayer3DTextLabel(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelText': 'prefix': 'GetPlayer3DTextLabelText' 'body': 'GetPlayer3DTextLabelText(${1:playerid}, ${2:PlayerText3D:id}, ${3:text[]}, ${4:len = sizeof(text})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelColor': 'prefix': 'GetPlayer3DTextLabelColor' 'body': 'GetPlayer3DTextLabelColor(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelPos': 'prefix': 'GetPlayer3DTextLabelPos' 'body': 'GetPlayer3DTextLabelPos(${1:playerid}, ${2:PlayerText3D:id}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelDrawDist': 'prefix': 'GetPlayer3DTextLabelDrawDist' 'body': 'GetPlayer3DTextLabelDrawDist(${1:playerid}, ${2:PlayerText3D:id})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelLOS': 'prefix': 'GetPlayer3DTextLabelLOS' 'body': 'GetPlayer3DTextLabelLOS(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelVirtualW': 'prefix': 'GetPlayer3DTextLabelVirtualW' 'body': 'GetPlayer3DTextLabelVirtualW(${1:playerid}, ${2:PlayerText3D:id})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayer3DTextLabelAttached': 'prefix': 'GetPlayer3DTextLabelAttached' 'body': 'GetPlayer3DTextLabelAttached(${1:playerid}, ${2:PlayerText3D:id}, ${3:&attached_playerid}, ${4:&attached_vehicleid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuDisabled': 'prefix': 'IsMenuDisabled' 'body': 'IsMenuDisabled(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsMenuRowDisabled': 'prefix': 'IsMenuRowDisabled' 'body': 'IsMenuRowDisabled(${1:Menu:menuid}, ${2:row})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumns': 'prefix': 'GetMenuColumns' 'body': 'GetMenuColumns(${1:Menu:menuid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItems': 'prefix': 'GetMenuItems' 'body': 'GetMenuItems(${1:Menu:menuid}, ${2:column})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuPos': 'prefix': 'GetMenuPos' 'body': 'GetMenuPos(${1:Menu:menuid}, ${2:&Float:fX}, ${3:&Float:fY})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnWidth': 'prefix': 'GetMenuColumnWidth' 'body': 'GetMenuColumnWidth(${1:Menu:menuid}, ${2:&Float:fColumn1}, ${3:&Float:fColumn2})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuColumnHeader': 'prefix': 'GetMenuColumnHeader' 'body': 'GetMenuColumnHeader(${1:Menu:menuid}, ${2:column}, ${3:header[]}, ${4:len = sizeof(header})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetMenuItem': 'prefix': 'GetMenuItem' 'body': 'GetMenuItem(${1:Menu:menuid}, ${2:column}, ${3:itemid}, ${4:item[]}, ${5:len = sizeof(item})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPickup': 'prefix': 'IsValidPickup' 'body': 'IsValidPickup(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPickupStreamedIn': 'prefix': 'IsPickupStreamedIn' 'body': 'IsPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupPos': 'prefix': 'GetPickupPos' 'body': 'GetPickupPos(${1:pickupid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupModel': 'prefix': 'GetPickupModel' 'body': 'GetPickupModel(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupType': 'prefix': 'GetPickupType' 'body': 'GetPickupType(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPickupVirtualWorld': 'prefix': 'GetPickupVirtualWorld' 'body': 'GetPickupVirtualWorld(${1:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'CreatePlayerPickup': 'prefix': 'CreatePlayerPickup' 'body': 'CreatePlayerPickup(${1:playerid}, ${2:model}, ${3:type}, ${4:Float:X}, ${5:Float:Y}, ${6:Float:Z}, ${7:virtualworld = 0})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'DestroyPlayerPickup': 'prefix': 'DestroyPlayerPickup' 'body': 'DestroyPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsValidPlayerPickup': 'prefix': 'IsValidPlayerPickup' 'body': 'IsValidPlayerPickup(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'IsPlayerPickupStreamedIn': 'prefix': 'IsPlayerPickupStreamedIn' 'body': 'IsPlayerPickupStreamedIn(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupPos': 'prefix': 'GetPlayerPickupPos' 'body': 'GetPlayerPickupPos(${1:playerid}, ${2:pickupid}, ${3:&Float:fX}, ${4:&Float:fY}, ${5:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupModel': 'prefix': 'GetPlayerPickupModel' 'body': 'GetPlayerPickupModel(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupType': 'prefix': 'GetPlayerPickupType' 'body': 'GetPlayerPickupType(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetPlayerPickupVirtualWorld': 'prefix': 'GetPlayerPickupVirtualWorld' 'body': 'GetPlayerPickupVirtualWorld(${1:playerid}, ${2:pickupid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColCount': 'prefix': 'GetColCount' 'body': 'GetColCount()' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereRadius': 'prefix': 'GetColSphereRadius' 'body': 'GetColSphereRadius(${1:modelid})' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetColSphereOffset': 'prefix': 'GetColSphereOffset' 'body': 'GetColSphereOffset(${1:modelid}, ${2:&Float:fX}, ${3:&Float:fY}, ${4:&Float:fZ})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessagef': 'prefix': 'SendClientMessagef' 'body': 'SendClientMessagef(${1:playerid}, ${2:color}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendClientMessageToAllf': 'prefix': 'SendClientMessageToAllf' 'body': 'SendClientMessageToAllf(${1:color}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForPlayerf': 'prefix': 'GameTextForPlayerf' 'body': 'GameTextForPlayerf(${1:playerid}, ${2:displaytime}, ${3:style}, ${4:const message[]}, ${5:{Float}, ${6:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GameTextForAllf': 'prefix': 'GameTextForAllf' 'body': 'GameTextForAllf(${1:displaytime}, ${2:style}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToPlayerf': 'prefix': 'SendPlayerMessageToPlayerf' 'body': 'SendPlayerMessageToPlayerf(${1:playerid}, ${2:senderid}, ${3:const message[]}, ${4:{Float}, ${5:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendPlayerMessageToAllf': 'prefix': 'SendPlayerMessageToAllf' 'body': 'SendPlayerMessageToAllf(${1:senderid}, ${2:const message[]}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRconCommandf': 'prefix': 'SendRconCommandf' 'body': 'SendRconCommandf(${1:const command[]}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetWeaponSlot': 'prefix': 'GetWeaponSlot' 'body': 'GetWeaponSlot(${1:weaponid})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendRPC': 'prefix': 'SendRPC' 'body': 'SendRPC(${1:playerid}, ${2:RPC}, ${3:{Float}, ${4:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'SendData': 'prefix': 'SendData' 'body': 'SendData(${1:playerid}, ${2:{Float}, ${3:_}:...})' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499' 'GetGravity': 'prefix': 'GetGravity' 'body': 'GetGravity()' 'leftLabel': 'Float' 'description': 'Function from: YSF' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=513499'
[ { "context": "a of the body.\n#\n# Notes:\n# None\n#\n# Author:\n# bsensale\n\n# TODO: Figure out how to match up the incoming ", "end": 333, "score": 0.9996605515480042, "start": 325, "tag": "USERNAME", "value": "bsensale" }, { "context": "m}\", \"#{aim}\", \"#{aim}\", \"miss\"]...
node_modules/hubot-darts/src/darts.coffee
shashankredemption/shitpostbot
4
# Description # Have an office dart fight, even when working from home # # Dependencies: # None # # Configuration: # None # # Commands: # hubot shoot target (in the legs/head/body) - Fire's a foam dart at the target # Optionalls attempts to aim for a specific area of the body. # # Notes: # None # # Author: # bsensale # TODO: Figure out how to match up the incoming message with the correct user # by @mention name. My testing has found that its sending in the @mention value # as set in hipchat's settings, but that that text doesn't necessarily match the # value stored in the user hash. :-/ # This method is not used until I can work through how to better find and target # based on the mention_name. userForMentionName = (robot, msg, mentionname) -> robot.logger.debug "Checking mentionname: #{mentionname}" for k of (robot.brain.data.users or { } ) user = robot.brain.data.users[k] robot.logger.debug "user: #{user}" name = user.mention_name robot.logger.debug "Name found: #{name}" if name? and name.toLowerCase() is mentionname.toLowerCase() return user return null module.exports = (robot) -> robot.respond /shoot ((.+)(?: in the )(head|body|legs)?|(.*))/i, (msg) -> victimStr = msg.match[2] ? msg.match[4] # Disable mention name lookups. # if victimStr.charAt(0) is '@' # victim = userForMentionName(robot, msg, victimStr.slice 1) # else users = robot.brain.usersForFuzzyName(victimStr) if users.length > 1 msg.reply "Be more specific; I can't shoot more than one person at once!" return victim = if users.length is 1 then users[0] else null if not victim msg.reply "You want me to shoot someone who doesn't exist. You are strange." return msg.reply "Target acquired." aim = msg.match[3] if not aim aim = msg.random ["head", "body", "legs"] target = msg.random ["#{aim}", "#{aim}", "#{aim}", "#{aim}", "miss"] victimName = victim.name result = (target) -> if target is "miss" "The shot sails safely overhead." else if target is "head" msg.random [ "It hits #{victimName} right in the eye! You monster!", "It bounces right off #{victimName}'s nose.", "It hits #{victimName} in the ear. Why would you do that?", "POW! BANG! #{victimName} is hit right in the kisser!", "Right in the temple. #{victimName} falls limp to the floor." ] else if target is "body" msg.random [ "The shot bounces off #{victimName}'s shoulder.", "It hits #{victimName} right in the chest. #{victimName} has trouble drawing their next breath.", "The dart hits #{victimName} in the stomach and gets lodged in their belly button.", "It hits #{victimName} in the back, causng temporary paralysis.", "The dart bounces off #{victimName}'s left shoulder, spinning them violently around." ] else if target is "legs" msg.random [ "The dart smacks into #{victimName}'s thigh. Charlie Horse!!!", "The dart hits #{victimName} square in the crotch. I need an adult!", "It hits #{victimName} right in the kneecap. What did they owe you money?", "It smacks into #{victimName}'s pinkie toe. They go wee wee wee all the way home!", "The dart hits right on #{victimName}'s shin, knocking them to the ground" ] msg.emote "fires a foam dart at #{victimName}'s #{aim}. #{result target}"
79949
# Description # Have an office dart fight, even when working from home # # Dependencies: # None # # Configuration: # None # # Commands: # hubot shoot target (in the legs/head/body) - Fire's a foam dart at the target # Optionalls attempts to aim for a specific area of the body. # # Notes: # None # # Author: # bsensale # TODO: Figure out how to match up the incoming message with the correct user # by @mention name. My testing has found that its sending in the @mention value # as set in hipchat's settings, but that that text doesn't necessarily match the # value stored in the user hash. :-/ # This method is not used until I can work through how to better find and target # based on the mention_name. userForMentionName = (robot, msg, mentionname) -> robot.logger.debug "Checking mentionname: #{mentionname}" for k of (robot.brain.data.users or { } ) user = robot.brain.data.users[k] robot.logger.debug "user: #{user}" name = user.mention_name robot.logger.debug "Name found: #{name}" if name? and name.toLowerCase() is mentionname.toLowerCase() return user return null module.exports = (robot) -> robot.respond /shoot ((.+)(?: in the )(head|body|legs)?|(.*))/i, (msg) -> victimStr = msg.match[2] ? msg.match[4] # Disable mention name lookups. # if victimStr.charAt(0) is '@' # victim = userForMentionName(robot, msg, victimStr.slice 1) # else users = robot.brain.usersForFuzzyName(victimStr) if users.length > 1 msg.reply "Be more specific; I can't shoot more than one person at once!" return victim = if users.length is 1 then users[0] else null if not victim msg.reply "You want me to shoot someone who doesn't exist. You are strange." return msg.reply "Target acquired." aim = msg.match[3] if not aim aim = msg.random ["head", "body", "legs"] target = msg.random ["#{aim}", "#{aim}", "#{aim}", "#{aim}", "miss"] victimName = <NAME> result = (target) -> if target is "miss" "The shot sails safely overhead." else if target is "head" msg.random [ "It hits #{victimName} right in the eye! You monster!", "It bounces right off #{victimName}'s nose.", "It hits #{victimName} in the ear. Why would you do that?", "POW! BANG! #{victimName} is hit right in the kisser!", "Right in the temple. #{victimName} falls limp to the floor." ] else if target is "body" msg.random [ "The shot bounces off #{victimName}'s shoulder.", "It hits #{victimName} right in the chest. #{victimName} has trouble drawing their next breath.", "The dart hits #{victimName} in the stomach and gets lodged in their belly button.", "It hits #{victimName} in the back, causng temporary paralysis.", "The dart bounces off #{victimName}'s left shoulder, spinning them violently around." ] else if target is "legs" msg.random [ "The dart smacks into #{victimName}'s thigh. <NAME>!!!", "The dart hits #{victimName} square in the crotch. I need an adult!", "It hits #{victimName} right in the kneecap. What did they owe you money?", "It smacks into #{victimName}'s pinkie toe. They go wee wee wee all the way home!", "The dart hits right on #{victimName}'s shin, knocking them to the ground" ] msg.emote "fires a foam dart at #{victimName}'s #{aim}. #{result target}"
true
# Description # Have an office dart fight, even when working from home # # Dependencies: # None # # Configuration: # None # # Commands: # hubot shoot target (in the legs/head/body) - Fire's a foam dart at the target # Optionalls attempts to aim for a specific area of the body. # # Notes: # None # # Author: # bsensale # TODO: Figure out how to match up the incoming message with the correct user # by @mention name. My testing has found that its sending in the @mention value # as set in hipchat's settings, but that that text doesn't necessarily match the # value stored in the user hash. :-/ # This method is not used until I can work through how to better find and target # based on the mention_name. userForMentionName = (robot, msg, mentionname) -> robot.logger.debug "Checking mentionname: #{mentionname}" for k of (robot.brain.data.users or { } ) user = robot.brain.data.users[k] robot.logger.debug "user: #{user}" name = user.mention_name robot.logger.debug "Name found: #{name}" if name? and name.toLowerCase() is mentionname.toLowerCase() return user return null module.exports = (robot) -> robot.respond /shoot ((.+)(?: in the )(head|body|legs)?|(.*))/i, (msg) -> victimStr = msg.match[2] ? msg.match[4] # Disable mention name lookups. # if victimStr.charAt(0) is '@' # victim = userForMentionName(robot, msg, victimStr.slice 1) # else users = robot.brain.usersForFuzzyName(victimStr) if users.length > 1 msg.reply "Be more specific; I can't shoot more than one person at once!" return victim = if users.length is 1 then users[0] else null if not victim msg.reply "You want me to shoot someone who doesn't exist. You are strange." return msg.reply "Target acquired." aim = msg.match[3] if not aim aim = msg.random ["head", "body", "legs"] target = msg.random ["#{aim}", "#{aim}", "#{aim}", "#{aim}", "miss"] victimName = PI:NAME:<NAME>END_PI result = (target) -> if target is "miss" "The shot sails safely overhead." else if target is "head" msg.random [ "It hits #{victimName} right in the eye! You monster!", "It bounces right off #{victimName}'s nose.", "It hits #{victimName} in the ear. Why would you do that?", "POW! BANG! #{victimName} is hit right in the kisser!", "Right in the temple. #{victimName} falls limp to the floor." ] else if target is "body" msg.random [ "The shot bounces off #{victimName}'s shoulder.", "It hits #{victimName} right in the chest. #{victimName} has trouble drawing their next breath.", "The dart hits #{victimName} in the stomach and gets lodged in their belly button.", "It hits #{victimName} in the back, causng temporary paralysis.", "The dart bounces off #{victimName}'s left shoulder, spinning them violently around." ] else if target is "legs" msg.random [ "The dart smacks into #{victimName}'s thigh. PI:NAME:<NAME>END_PI!!!", "The dart hits #{victimName} square in the crotch. I need an adult!", "It hits #{victimName} right in the kneecap. What did they owe you money?", "It smacks into #{victimName}'s pinkie toe. They go wee wee wee all the way home!", "The dart hits right on #{victimName}'s shin, knocking them to the ground" ] msg.emote "fires a foam dart at #{victimName}'s #{aim}. #{result target}"
[ { "context": "is file is part of the ChinesePuzzle package.\n\n(c) Mathieu Ledru\n\nFor the full copyright and license information, ", "end": 70, "score": 0.9998461008071899, "start": 57, "tag": "NAME", "value": "Mathieu Ledru" } ]
Common/Bin/Data/coffee/Menu/MenuLabelContainer.coffee
matyo91/ChinesePuzzle
1
### This file is part of the ChinesePuzzle package. (c) Mathieu Ledru For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.MenuLabelContainer = cpz.MenuBox.extend( _container: null _margin: null ctor: -> @_super() @_container = null initWithConfAndContentSizeAndFntFile: (conf, size, fntFile) -> return false unless @initWithConfAndContentSize(conf, size) @_container = new cpz.MenuLabel() @_container.initWithContentSizeAndFntFile(size, fntFile) @_container.setAnchorPoint(cc.p(0.5, 0.5)) @addChild(@_container) @_margin = cc.size(0, 0) return true getString: -> @_container.getString() setString: (str) -> @_container.setString(str) @ getWidth: -> @_container.getWidth() setWidth: (width) -> @_container.setWidth(width) @ setAlignment: (alignment) -> @_container.setAlignment(alignment) @ getMargin: -> @_margin setMargin: (margin) -> @_margin = margin @layout() @ layout: (anim = true) -> @_super(anim) size = @getContentSize() if(@_container) @_container.setPosition(cc.p(size.width / 2, size.height / 2)) @_container.setContentSize(cc.size(size.width - 2 * @_margin.width, size.height - 2 * @_margin.height)) @_container.setWidth(size.width - 2 * @_margin.width) onTouchBegan: (touch, event) -> return false if @_super(touch, event) return @_container.onTouchBegan(touch, event) onTouchMoved: (touch, event) -> @_super(touch, event) @_container.onTouchMoved(touch, event) onTouchEnded: (touch, event) -> @_super(touch, event) @_container.onTouchEnded(touch, event) onTouchCancelled: (touch, event) -> @_super(touch, event) @_container.onTouchCancelled(touch, event) )
142418
### This file is part of the ChinesePuzzle package. (c) <NAME> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.MenuLabelContainer = cpz.MenuBox.extend( _container: null _margin: null ctor: -> @_super() @_container = null initWithConfAndContentSizeAndFntFile: (conf, size, fntFile) -> return false unless @initWithConfAndContentSize(conf, size) @_container = new cpz.MenuLabel() @_container.initWithContentSizeAndFntFile(size, fntFile) @_container.setAnchorPoint(cc.p(0.5, 0.5)) @addChild(@_container) @_margin = cc.size(0, 0) return true getString: -> @_container.getString() setString: (str) -> @_container.setString(str) @ getWidth: -> @_container.getWidth() setWidth: (width) -> @_container.setWidth(width) @ setAlignment: (alignment) -> @_container.setAlignment(alignment) @ getMargin: -> @_margin setMargin: (margin) -> @_margin = margin @layout() @ layout: (anim = true) -> @_super(anim) size = @getContentSize() if(@_container) @_container.setPosition(cc.p(size.width / 2, size.height / 2)) @_container.setContentSize(cc.size(size.width - 2 * @_margin.width, size.height - 2 * @_margin.height)) @_container.setWidth(size.width - 2 * @_margin.width) onTouchBegan: (touch, event) -> return false if @_super(touch, event) return @_container.onTouchBegan(touch, event) onTouchMoved: (touch, event) -> @_super(touch, event) @_container.onTouchMoved(touch, event) onTouchEnded: (touch, event) -> @_super(touch, event) @_container.onTouchEnded(touch, event) onTouchCancelled: (touch, event) -> @_super(touch, event) @_container.onTouchCancelled(touch, event) )
true
### This file is part of the ChinesePuzzle package. (c) PI:NAME:<NAME>END_PI For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.MenuLabelContainer = cpz.MenuBox.extend( _container: null _margin: null ctor: -> @_super() @_container = null initWithConfAndContentSizeAndFntFile: (conf, size, fntFile) -> return false unless @initWithConfAndContentSize(conf, size) @_container = new cpz.MenuLabel() @_container.initWithContentSizeAndFntFile(size, fntFile) @_container.setAnchorPoint(cc.p(0.5, 0.5)) @addChild(@_container) @_margin = cc.size(0, 0) return true getString: -> @_container.getString() setString: (str) -> @_container.setString(str) @ getWidth: -> @_container.getWidth() setWidth: (width) -> @_container.setWidth(width) @ setAlignment: (alignment) -> @_container.setAlignment(alignment) @ getMargin: -> @_margin setMargin: (margin) -> @_margin = margin @layout() @ layout: (anim = true) -> @_super(anim) size = @getContentSize() if(@_container) @_container.setPosition(cc.p(size.width / 2, size.height / 2)) @_container.setContentSize(cc.size(size.width - 2 * @_margin.width, size.height - 2 * @_margin.height)) @_container.setWidth(size.width - 2 * @_margin.width) onTouchBegan: (touch, event) -> return false if @_super(touch, event) return @_container.onTouchBegan(touch, event) onTouchMoved: (touch, event) -> @_super(touch, event) @_container.onTouchMoved(touch, event) onTouchEnded: (touch, event) -> @_super(touch, event) @_container.onTouchEnded(touch, event) onTouchCancelled: (touch, event) -> @_super(touch, event) @_container.onTouchCancelled(touch, event) )
[ { "context": " beforeEach -> \n room.user.say 'charlie', 'hubot vsts projec'\n\n it 'should rep", "end": 486, "score": 0.9992239475250244, "start": 479, "tag": "NAME", "value": "charlie" }, { "context": "ect(room.messages).to.eql [\n ['...
test/vsts-slack-test.coffee
Mimeo/Hubot-Slack-VSTS
0
Helper = require 'hubot-test-helper' chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect helper = new Helper('./../src/vsts-slack.coffee') describe 'vsts-slack', -> room = null beforeEach -> room = helper.createRoom() afterEach -> room.destroy() context 'negative tests:', -> context 'user misspells project', -> beforeEach -> room.user.say 'charlie', 'hubot vsts projec' it 'should reply with nothing', -> expect(room.messages).to.eql [ ['charlie', 'hubot vsts projec'] ] context 'user requests projects but env vars not present', -> beforeEach -> room.user.say 'charlie', 'hubot vsts projects' it 'should return an error', -> expect(room.messages).to.eql [ ['charlie', 'hubot vsts projects'] ['hubot', 'VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set'] ['hubot', 'VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set'] ]
33091
Helper = require 'hubot-test-helper' chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect helper = new Helper('./../src/vsts-slack.coffee') describe 'vsts-slack', -> room = null beforeEach -> room = helper.createRoom() afterEach -> room.destroy() context 'negative tests:', -> context 'user misspells project', -> beforeEach -> room.user.say '<NAME>', 'hubot vsts projec' it 'should reply with nothing', -> expect(room.messages).to.eql [ ['<NAME>', 'hubot vsts projec'] ] context 'user requests projects but env vars not present', -> beforeEach -> room.user.say '<NAME>', 'hubot vsts projects' it 'should return an error', -> expect(room.messages).to.eql [ ['<NAME>', 'hubot vsts projects'] ['hubot', 'VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set'] ['hubot', 'VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set'] ]
true
Helper = require 'hubot-test-helper' chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect helper = new Helper('./../src/vsts-slack.coffee') describe 'vsts-slack', -> room = null beforeEach -> room = helper.createRoom() afterEach -> room.destroy() context 'negative tests:', -> context 'user misspells project', -> beforeEach -> room.user.say 'PI:NAME:<NAME>END_PI', 'hubot vsts projec' it 'should reply with nothing', -> expect(room.messages).to.eql [ ['PI:NAME:<NAME>END_PI', 'hubot vsts projec'] ] context 'user requests projects but env vars not present', -> beforeEach -> room.user.say 'PI:NAME:<NAME>END_PI', 'hubot vsts projects' it 'should return an error', -> expect(room.messages).to.eql [ ['PI:NAME:<NAME>END_PI', 'hubot vsts projects'] ['hubot', 'VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set'] ['hubot', 'VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set'] ]
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission ", "end": 18, "score": 0.9030064344406128, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-stream2-large-read-stall.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. # If everything aligns so that you do a read(n) of exactly the # remaining buffer, then make sure that 'end' still emits. push = -> return if pushes > PUSHCOUNT if pushes++ is PUSHCOUNT console.error " push(EOF)" return r.push(null) console.error " push #%d", pushes setTimeout push if r.push(new Buffer(PUSHSIZE)) return common = require("../common.js") assert = require("assert") READSIZE = 100 PUSHSIZE = 20 PUSHCOUNT = 1000 HWM = 50 Readable = require("stream").Readable r = new Readable(highWaterMark: HWM) rs = r._readableState r._read = push r.on "readable", -> console.error ">> readable" loop console.error " > read(%d)", READSIZE ret = r.read(READSIZE) console.error " < %j (%d remain)", ret and ret.length, rs.length break unless ret and ret.length is READSIZE console.error "<< after read()", ret and ret.length, rs.needReadable, rs.length return endEmitted = false r.on "end", -> endEmitted = true console.error "end" return pushes = 0 # start the flow ret = r.read(0) process.on "exit", -> assert.equal pushes, PUSHCOUNT + 1 assert endEmitted return
225400
# 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. # If everything aligns so that you do a read(n) of exactly the # remaining buffer, then make sure that 'end' still emits. push = -> return if pushes > PUSHCOUNT if pushes++ is PUSHCOUNT console.error " push(EOF)" return r.push(null) console.error " push #%d", pushes setTimeout push if r.push(new Buffer(PUSHSIZE)) return common = require("../common.js") assert = require("assert") READSIZE = 100 PUSHSIZE = 20 PUSHCOUNT = 1000 HWM = 50 Readable = require("stream").Readable r = new Readable(highWaterMark: HWM) rs = r._readableState r._read = push r.on "readable", -> console.error ">> readable" loop console.error " > read(%d)", READSIZE ret = r.read(READSIZE) console.error " < %j (%d remain)", ret and ret.length, rs.length break unless ret and ret.length is READSIZE console.error "<< after read()", ret and ret.length, rs.needReadable, rs.length return endEmitted = false r.on "end", -> endEmitted = true console.error "end" return pushes = 0 # start the flow ret = r.read(0) process.on "exit", -> assert.equal pushes, PUSHCOUNT + 1 assert endEmitted 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. # If everything aligns so that you do a read(n) of exactly the # remaining buffer, then make sure that 'end' still emits. push = -> return if pushes > PUSHCOUNT if pushes++ is PUSHCOUNT console.error " push(EOF)" return r.push(null) console.error " push #%d", pushes setTimeout push if r.push(new Buffer(PUSHSIZE)) return common = require("../common.js") assert = require("assert") READSIZE = 100 PUSHSIZE = 20 PUSHCOUNT = 1000 HWM = 50 Readable = require("stream").Readable r = new Readable(highWaterMark: HWM) rs = r._readableState r._read = push r.on "readable", -> console.error ">> readable" loop console.error " > read(%d)", READSIZE ret = r.read(READSIZE) console.error " < %j (%d remain)", ret and ret.length, rs.length break unless ret and ret.length is READSIZE console.error "<< after read()", ret and ret.length, rs.needReadable, rs.length return endEmitted = false r.on "end", -> endEmitted = true console.error "end" return pushes = 0 # start the flow ret = r.read(0) process.on "exit", -> assert.equal pushes, PUSHCOUNT + 1 assert endEmitted return
[ { "context": "ageRateLimit', ->\n beforeEach ->\n @clientKey = uuid.v1()\n @client = redis.createClient @clientKey\n c", "end": 242, "score": 0.9056974649429321, "start": 233, "tag": "KEY", "value": "uuid.v1()" }, { "context": "-electric'\n auth:\n uuid: 'el...
test/enforce-message-rate-limit-spec.coffee
octoblu/meshblu-core-task-enforce-message-rate-limit
0
_ = require 'lodash' redis = require 'fakeredis' uuid = require 'uuid' EnforceMessageRateLimit = require '../' MeshbluCoreCache = require 'meshblu-core-cache' describe 'EnforceMessageRateLimit', -> beforeEach -> @clientKey = uuid.v1() @client = redis.createClient @clientKey cache = new MeshbluCoreCache client: redis.createClient @clientKey startTime = Date.now() FakeDate = now: -> return startTime @sut = new EnforceMessageRateLimit {cache: cache, Date: FakeDate} @request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: {} rawData: '{}' describe '->do', -> context 'when given a valid message', -> beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should have no keys in redis', (done) -> @client.keys '*', (error, result) -> expect(result.length).to.equal 0 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set low and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit/2, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set high and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse
154710
_ = require 'lodash' redis = require 'fakeredis' uuid = require 'uuid' EnforceMessageRateLimit = require '../' MeshbluCoreCache = require 'meshblu-core-cache' describe 'EnforceMessageRateLimit', -> beforeEach -> @clientKey = <KEY> @client = redis.createClient @clientKey cache = new MeshbluCoreCache client: redis.createClient @clientKey startTime = Date.now() FakeDate = now: -> return startTime @sut = new EnforceMessageRateLimit {cache: cache, Date: FakeDate} @request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: {} rawData: '{}' describe '->do', -> context 'when given a valid message', -> beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should have no keys in redis', (done) -> @client.keys '*', (error, result) -> expect(result.length).to.equal 0 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set low and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit/2, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set high and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse
true
_ = require 'lodash' redis = require 'fakeredis' uuid = require 'uuid' EnforceMessageRateLimit = require '../' MeshbluCoreCache = require 'meshblu-core-cache' describe 'EnforceMessageRateLimit', -> beforeEach -> @clientKey = PI:KEY:<KEY>END_PI @client = redis.createClient @clientKey cache = new MeshbluCoreCache client: redis.createClient @clientKey startTime = Date.now() FakeDate = now: -> return startTime @sut = new EnforceMessageRateLimit {cache: cache, Date: FakeDate} @request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: {} rawData: '{}' describe '->do', -> context 'when given a valid message', -> beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should have no keys in redis', (done) -> @client.keys '*', (error, result) -> expect(result.length).to.equal 0 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set low and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit/2, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when the rate is set high and messaged again', -> beforeEach (done) -> @client.hset @sut.rateLimitChecker.getMinuteKey(), 'electric-eels', @sut.rateLimitChecker.msgRateLimit, done beforeEach (done) -> @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse context 'when given another message with an "as" in auth', -> beforeEach (done) -> @request = metadata: responseId: 'its-electric' auth: uuid: 'atomic-clams' as: 'electric-eels' messageType: 'received' options: {} rawData: '{}' @sut.do @request, (error, @response) => done error it 'should return a 429', -> expectedResponse = metadata: responseId: 'its-electric' code: 429 status: 'Too Many Requests' expect(@response).to.deep.equal expectedResponse
[ { "context": "#\n# Ethan Mick\n# 2015\n#\nTask = require '../models/task'\n\ncreate ", "end": 14, "score": 0.9997628927230835, "start": 4, "tag": "NAME", "value": "Ethan Mick" } ]
lib/routes/task.coffee
ethanmick/future-server
0
# # Ethan Mick # 2015 # Task = require '../models/task' create = (req, reply)-> task = new Task(req.payload) task.saveQ().then -> console.log req.server.app.scheduler.queue.enq req.server.app.scheduler.queue.enq(task) if task.soon() reply(name: task.name) .done() get = (req, reply)-> Task.findOneQ(name: req.params.id).then (task)-> return reply(error: 'Not Found!') unless task reply(task.toObject()) .done() del = (req, reply)-> name = req.params.id Task.removeQ(name: name).then -> reply(deleted: name) .done() module.exports = [ { method: 'POST' path: '/v1/task' handler: create } { method: 'GET' path: '/v1/task/{id}' handler: get } { method: 'DELETE' path: '/v1/task/{id}' handler: del } ]
14909
# # <NAME> # 2015 # Task = require '../models/task' create = (req, reply)-> task = new Task(req.payload) task.saveQ().then -> console.log req.server.app.scheduler.queue.enq req.server.app.scheduler.queue.enq(task) if task.soon() reply(name: task.name) .done() get = (req, reply)-> Task.findOneQ(name: req.params.id).then (task)-> return reply(error: 'Not Found!') unless task reply(task.toObject()) .done() del = (req, reply)-> name = req.params.id Task.removeQ(name: name).then -> reply(deleted: name) .done() module.exports = [ { method: 'POST' path: '/v1/task' handler: create } { method: 'GET' path: '/v1/task/{id}' handler: get } { method: 'DELETE' path: '/v1/task/{id}' handler: del } ]
true
# # PI:NAME:<NAME>END_PI # 2015 # Task = require '../models/task' create = (req, reply)-> task = new Task(req.payload) task.saveQ().then -> console.log req.server.app.scheduler.queue.enq req.server.app.scheduler.queue.enq(task) if task.soon() reply(name: task.name) .done() get = (req, reply)-> Task.findOneQ(name: req.params.id).then (task)-> return reply(error: 'Not Found!') unless task reply(task.toObject()) .done() del = (req, reply)-> name = req.params.id Task.removeQ(name: name).then -> reply(deleted: name) .done() module.exports = [ { method: 'POST' path: '/v1/task' handler: create } { method: 'GET' path: '/v1/task/{id}' handler: get } { method: 'DELETE' path: '/v1/task/{id}' handler: del } ]
[ { "context": "ee: Github pull-request class\n#\n# Copyright © 2012 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Initiate class\nclass Pr", "end": 81, "score": 0.9998677372932434, "start": 62, "tag": "NAME", "value": "Pavan Kumar Sunkara" }, { "context": "\n\n # List comments on ...
src/octonode/pr.coffee
silverbux/octonode2
0
# # pr.coffee: Github pull-request class # # Copyright © 2012 Pavan Kumar Sunkara. All rights reserved # # Initiate class class Pr constructor: (@repo, @number, @client) -> # Get a single pull request # '/repos/pksunkara/hub/pulls/37' GET info: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr info error")) else cb null, b, h # Update a pull request # '/repos/pksunkara/hub/pulls/37' PATCH update: (obj, cb) -> @client.post "/repos/#{@repo}/pulls/#{@number}", obj, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr update error")) else cb null, b, h # Close a pull request close: (cb) -> @update state: 'closed', cb # Get if a pull request has been merged # '/repos/pksunkara/hub/pulls/37/merge' GET merged: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/merge", (err, s, b, h) -> return cb null, false if err and err.message is 'null' cb null, s is 204, h # Merge a pull request # '/repos/pksunkara/hub/pulls/37/merge' PUT merge: (msg, cb) -> commit = commit_message: msg @client.put "/repos/#{@repo}/pulls/#{@number}/merge", commit, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr merge error")) else cb null, b, h # List commits on a pull request # '/repos/pksunkara/hub/pulls/37/commits' GET commits: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/commits", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr commits error")) else cb null, b, h # List comments on a pull request # '/repos/pksunkara/hub/pulls/37/comments' GET comments: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/comments", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr comments error")) else cb null, b, h # List files in pull request # '/repos/pksunkara/hub/pulls/37/files' GET files: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/files", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr files error")) else cb null, b, h # Export module module.exports = Pr
118708
# # pr.coffee: Github pull-request class # # Copyright © 2012 <NAME>. All rights reserved # # Initiate class class Pr constructor: (@repo, @number, @client) -> # Get a single pull request # '/repos/pksunkara/hub/pulls/37' GET info: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr info error")) else cb null, b, h # Update a pull request # '/repos/pksunkara/hub/pulls/37' PATCH update: (obj, cb) -> @client.post "/repos/#{@repo}/pulls/#{@number}", obj, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr update error")) else cb null, b, h # Close a pull request close: (cb) -> @update state: 'closed', cb # Get if a pull request has been merged # '/repos/pksunkara/hub/pulls/37/merge' GET merged: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/merge", (err, s, b, h) -> return cb null, false if err and err.message is 'null' cb null, s is 204, h # Merge a pull request # '/repos/pksunkara/hub/pulls/37/merge' PUT merge: (msg, cb) -> commit = commit_message: msg @client.put "/repos/#{@repo}/pulls/#{@number}/merge", commit, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr merge error")) else cb null, b, h # List commits on a pull request # '/repos/pksunkara/hub/pulls/37/commits' GET commits: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/commits", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr commits error")) else cb null, b, h # List comments on a pull request # '/repos/pksunkara/hub/pulls/37/comments' GET comments: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/comments", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr comments error")) else cb null, b, h # List files in pull request # '/repos/pksunkara/hub/pulls/37/files' GET files: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/files", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr files error")) else cb null, b, h # Export module module.exports = Pr
true
# # pr.coffee: Github pull-request class # # Copyright © 2012 PI:NAME:<NAME>END_PI. All rights reserved # # Initiate class class Pr constructor: (@repo, @number, @client) -> # Get a single pull request # '/repos/pksunkara/hub/pulls/37' GET info: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr info error")) else cb null, b, h # Update a pull request # '/repos/pksunkara/hub/pulls/37' PATCH update: (obj, cb) -> @client.post "/repos/#{@repo}/pulls/#{@number}", obj, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr update error")) else cb null, b, h # Close a pull request close: (cb) -> @update state: 'closed', cb # Get if a pull request has been merged # '/repos/pksunkara/hub/pulls/37/merge' GET merged: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/merge", (err, s, b, h) -> return cb null, false if err and err.message is 'null' cb null, s is 204, h # Merge a pull request # '/repos/pksunkara/hub/pulls/37/merge' PUT merge: (msg, cb) -> commit = commit_message: msg @client.put "/repos/#{@repo}/pulls/#{@number}/merge", commit, (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr merge error")) else cb null, b, h # List commits on a pull request # '/repos/pksunkara/hub/pulls/37/commits' GET commits: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/commits", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr commits error")) else cb null, b, h # List comments on a pull request # '/repos/pksunkara/hub/pulls/37/comments' GET comments: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/comments", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr comments error")) else cb null, b, h # List files in pull request # '/repos/pksunkara/hub/pulls/37/files' GET files: (cb) -> @client.get "/repos/#{@repo}/pulls/#{@number}/files", (err, s, b, h) -> return cb(err) if err if s isnt 200 then cb(new Error("Pr files error")) else cb null, b, h # Export module module.exports = Pr
[ { "context": "en @capitalize(key) else key\n macKey = \"#{prefix}#{altKey}\"\n output[key] =\n if attributes[mac", "end": 6659, "score": 0.9004649519920349, "start": 6639, "tag": "KEY", "value": "\"#{prefix}#{altKey}\"" } ]
src/util.coffee
neosavvyinc/MacGyver
1
## ## Util module ## ## Contains various miscellaneous utility functions and extensions. ## # Expose an object with a bunch of utility functions on it. angular.module("Mac.Util", []).factory "util", [ "$filter" ( $filter ) -> # Underscore function section ArrayProto = Array.prototype ObjProto = Object.prototype FuncProto = Function.prototype toString = ObjProto.toString nativeIsArray = Array.isArray _inflectionConstants: uncountables: [ "sheep", "fish", "moose", "series", "species", "money", "rice", "information", "info", "equipment", "min" ] irregulars: child: "children" man: "men" woman: "women" person: "people" ox: "oxen" goose: "geese" pluralizers: [ [/(quiz)$/i, "$1zes" ] [/([m|l])ouse$/i, "$1ice" ] [/(matr|vert|ind)(ix|ex)$/i, "$1ices" ] [/(x|ch|ss|sh)$/i, "$1es" ] [/([^aeiouy]|qu)y$/i, "$1ies" ] [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"] [/sis$/i, "ses" ] [/([ti])um$/i, "$1a" ] [/(buffal|tomat)o$/i, "$1oes" ] [/(bu)s$/i, "$1ses" ] [/(alias|status)$/i, "$1es" ] [/(octop|vir)us$/i, "$1i" ] [/(ax|test)is$/i, "$1es" ] [/x$/i, "xes" ] [/s$/i, "s" ] [/$/, "s" ] ] ### @name pluralize @description Pluralize string based on the count @param {String} string String to pluralize @param {Integer} count Object counts @param {Boolean} includeCount Include the number or not (default false) @returns {String} Pluralized string based on the count ### pluralize: (string, count, includeCount = false) -> # If our string has no length, return without further processing return string unless string?.trim().length > 0 # If the user is expecting count to be anything other # than the default, check if it is actually a number # If not, return an empty string if includeCount and isNaN +count return "" # Manually set our default here count = 2 unless count? {pluralizers, uncountables, irregulars} = @_inflectionConstants word = string.split(/\s/).pop() isUppercase = word.toUpperCase() is word lowercaseWord = word.toLowerCase() pluralizedWord = if count is 1 or uncountables.indexOf(lowercaseWord) >= 0 then word else null unless pluralizedWord? pluralizedWord = irregulars[lowercaseWord] if irregulars[lowercaseWord]? unless pluralizedWord? for pluralizer in pluralizers when pluralizer[0].test lowercaseWord pluralizedWord = word.replace pluralizer[0], pluralizer[1] break pluralizedWord or = word pluralizedWord = pluralizedWord.toUpperCase() if isUppercase pluralizedString = string[0...-word.length] + pluralizedWord if includeCount then "#{$filter("number") count} #{pluralizedString}" else pluralizedString capitalize: (string) -> str = String(string) or "" return str.charAt(0).toUpperCase() + str[1..] uncapitalize: (string) -> str = String(string) or "" return str.charAt(0).toLowerCase() + str[1..] toCamelCase: (string) -> string.trim().replace /[-_\s]+(.)?/g, (match, c) -> c.toUpperCase() toSnakeCase: (string) -> string.trim(). replace(/([a-z\d])([A-Z]+)/g, "$1_$2"). replace(/[-\s]+/g, "_"). toLowerCase() convertKeysToCamelCase: (object) -> result = {} for own key, value of object key = @toCamelCase key value = @convertKeysToCamelCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result convertKeysToSnakeCase: (object) -> result = {} for own key, value of object key = @toSnakeCase key value = @convertKeysToSnakeCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result isArray: nativeIsArray or (obj) -> toString.call(obj) is "[object Array]" _urlRegex: /(?:(?:(http[s]{0,1}:\/\/)(?:(www|[\d\w\-]+)\.){0,1})|(www|[\d\w\-]+)\.)([\d\w\-]+)\.([A-Za-z]{2,6})(:[\d]*){0,1}(\/?[\d\w\-\?\,\'\/\\\+&amp;%\$#!\=~\.]*){0,1}/i validateUrl: (url) -> match = @_urlRegex.exec url if match? match = { url: match[0] protocol: match[1] or "http://" subdomain: match[2] or match[3] name: match[4] domain: match[5] port: match[6] path: match[7] or "/" } # Recreate the full url match["url"] = match.url match validateEmail: (email) -> emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ emailRegex.test email # credits: http://www.netlobo.com/url_query_string_javascript.html getQueryString: (url, name = "") -> name = name.replace(/[[]/,"\[").replace(/[]]/,"\]") regexS = "[\?&]"+name+"=([^&#]*)" regex = new RegExp regexS results = regex.exec url if results? then results[1] else "" parseUrlPath: (fullPath) -> urlComponents = fullPath.split "?" pathComponents = urlComponents[0].split("/") path = pathComponents[0...pathComponents.length-1].join("/") verb = pathComponents[pathComponents.length-1] queries = {} # Check if querystring exists if urlComponents.length > 1 queryStrings = urlComponents[urlComponents.length-1] for queryString in queryStrings.split("&") values = queryString.split "=" queries[values[0]] = if values[1]? then values[1] else "" return {fullPath, path, pathComponents, verb, queries} ## ## @name ## extendAttributes ## ## @description ## Extend default values with attributes ## ## @param {String} prefix Prefix of all attributes ## @param {Object} defaults Default set of attributes ## @param {Object} attributes User set attributes ## extendAttributes: (prefix = "", defaults, attributes) -> output = {} for own key, value of defaults altKey = if prefix then @capitalize(key) else key macKey = "#{prefix}#{altKey}" output[key] = if attributes[macKey]? attributes[macKey] or true else value # Convert to true boolean if passing in boolean string if output[key] in ["true", "false"] output[key] = output[key] is "true" # Convert to integer or numbers from strings else if output[key]?.length > 0 and not isNaN +output[key] output[key] = +output[key] return output ]
158844
## ## Util module ## ## Contains various miscellaneous utility functions and extensions. ## # Expose an object with a bunch of utility functions on it. angular.module("Mac.Util", []).factory "util", [ "$filter" ( $filter ) -> # Underscore function section ArrayProto = Array.prototype ObjProto = Object.prototype FuncProto = Function.prototype toString = ObjProto.toString nativeIsArray = Array.isArray _inflectionConstants: uncountables: [ "sheep", "fish", "moose", "series", "species", "money", "rice", "information", "info", "equipment", "min" ] irregulars: child: "children" man: "men" woman: "women" person: "people" ox: "oxen" goose: "geese" pluralizers: [ [/(quiz)$/i, "$1zes" ] [/([m|l])ouse$/i, "$1ice" ] [/(matr|vert|ind)(ix|ex)$/i, "$1ices" ] [/(x|ch|ss|sh)$/i, "$1es" ] [/([^aeiouy]|qu)y$/i, "$1ies" ] [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"] [/sis$/i, "ses" ] [/([ti])um$/i, "$1a" ] [/(buffal|tomat)o$/i, "$1oes" ] [/(bu)s$/i, "$1ses" ] [/(alias|status)$/i, "$1es" ] [/(octop|vir)us$/i, "$1i" ] [/(ax|test)is$/i, "$1es" ] [/x$/i, "xes" ] [/s$/i, "s" ] [/$/, "s" ] ] ### @name pluralize @description Pluralize string based on the count @param {String} string String to pluralize @param {Integer} count Object counts @param {Boolean} includeCount Include the number or not (default false) @returns {String} Pluralized string based on the count ### pluralize: (string, count, includeCount = false) -> # If our string has no length, return without further processing return string unless string?.trim().length > 0 # If the user is expecting count to be anything other # than the default, check if it is actually a number # If not, return an empty string if includeCount and isNaN +count return "" # Manually set our default here count = 2 unless count? {pluralizers, uncountables, irregulars} = @_inflectionConstants word = string.split(/\s/).pop() isUppercase = word.toUpperCase() is word lowercaseWord = word.toLowerCase() pluralizedWord = if count is 1 or uncountables.indexOf(lowercaseWord) >= 0 then word else null unless pluralizedWord? pluralizedWord = irregulars[lowercaseWord] if irregulars[lowercaseWord]? unless pluralizedWord? for pluralizer in pluralizers when pluralizer[0].test lowercaseWord pluralizedWord = word.replace pluralizer[0], pluralizer[1] break pluralizedWord or = word pluralizedWord = pluralizedWord.toUpperCase() if isUppercase pluralizedString = string[0...-word.length] + pluralizedWord if includeCount then "#{$filter("number") count} #{pluralizedString}" else pluralizedString capitalize: (string) -> str = String(string) or "" return str.charAt(0).toUpperCase() + str[1..] uncapitalize: (string) -> str = String(string) or "" return str.charAt(0).toLowerCase() + str[1..] toCamelCase: (string) -> string.trim().replace /[-_\s]+(.)?/g, (match, c) -> c.toUpperCase() toSnakeCase: (string) -> string.trim(). replace(/([a-z\d])([A-Z]+)/g, "$1_$2"). replace(/[-\s]+/g, "_"). toLowerCase() convertKeysToCamelCase: (object) -> result = {} for own key, value of object key = @toCamelCase key value = @convertKeysToCamelCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result convertKeysToSnakeCase: (object) -> result = {} for own key, value of object key = @toSnakeCase key value = @convertKeysToSnakeCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result isArray: nativeIsArray or (obj) -> toString.call(obj) is "[object Array]" _urlRegex: /(?:(?:(http[s]{0,1}:\/\/)(?:(www|[\d\w\-]+)\.){0,1})|(www|[\d\w\-]+)\.)([\d\w\-]+)\.([A-Za-z]{2,6})(:[\d]*){0,1}(\/?[\d\w\-\?\,\'\/\\\+&amp;%\$#!\=~\.]*){0,1}/i validateUrl: (url) -> match = @_urlRegex.exec url if match? match = { url: match[0] protocol: match[1] or "http://" subdomain: match[2] or match[3] name: match[4] domain: match[5] port: match[6] path: match[7] or "/" } # Recreate the full url match["url"] = match.url match validateEmail: (email) -> emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ emailRegex.test email # credits: http://www.netlobo.com/url_query_string_javascript.html getQueryString: (url, name = "") -> name = name.replace(/[[]/,"\[").replace(/[]]/,"\]") regexS = "[\?&]"+name+"=([^&#]*)" regex = new RegExp regexS results = regex.exec url if results? then results[1] else "" parseUrlPath: (fullPath) -> urlComponents = fullPath.split "?" pathComponents = urlComponents[0].split("/") path = pathComponents[0...pathComponents.length-1].join("/") verb = pathComponents[pathComponents.length-1] queries = {} # Check if querystring exists if urlComponents.length > 1 queryStrings = urlComponents[urlComponents.length-1] for queryString in queryStrings.split("&") values = queryString.split "=" queries[values[0]] = if values[1]? then values[1] else "" return {fullPath, path, pathComponents, verb, queries} ## ## @name ## extendAttributes ## ## @description ## Extend default values with attributes ## ## @param {String} prefix Prefix of all attributes ## @param {Object} defaults Default set of attributes ## @param {Object} attributes User set attributes ## extendAttributes: (prefix = "", defaults, attributes) -> output = {} for own key, value of defaults altKey = if prefix then @capitalize(key) else key macKey = <KEY> output[key] = if attributes[macKey]? attributes[macKey] or true else value # Convert to true boolean if passing in boolean string if output[key] in ["true", "false"] output[key] = output[key] is "true" # Convert to integer or numbers from strings else if output[key]?.length > 0 and not isNaN +output[key] output[key] = +output[key] return output ]
true
## ## Util module ## ## Contains various miscellaneous utility functions and extensions. ## # Expose an object with a bunch of utility functions on it. angular.module("Mac.Util", []).factory "util", [ "$filter" ( $filter ) -> # Underscore function section ArrayProto = Array.prototype ObjProto = Object.prototype FuncProto = Function.prototype toString = ObjProto.toString nativeIsArray = Array.isArray _inflectionConstants: uncountables: [ "sheep", "fish", "moose", "series", "species", "money", "rice", "information", "info", "equipment", "min" ] irregulars: child: "children" man: "men" woman: "women" person: "people" ox: "oxen" goose: "geese" pluralizers: [ [/(quiz)$/i, "$1zes" ] [/([m|l])ouse$/i, "$1ice" ] [/(matr|vert|ind)(ix|ex)$/i, "$1ices" ] [/(x|ch|ss|sh)$/i, "$1es" ] [/([^aeiouy]|qu)y$/i, "$1ies" ] [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"] [/sis$/i, "ses" ] [/([ti])um$/i, "$1a" ] [/(buffal|tomat)o$/i, "$1oes" ] [/(bu)s$/i, "$1ses" ] [/(alias|status)$/i, "$1es" ] [/(octop|vir)us$/i, "$1i" ] [/(ax|test)is$/i, "$1es" ] [/x$/i, "xes" ] [/s$/i, "s" ] [/$/, "s" ] ] ### @name pluralize @description Pluralize string based on the count @param {String} string String to pluralize @param {Integer} count Object counts @param {Boolean} includeCount Include the number or not (default false) @returns {String} Pluralized string based on the count ### pluralize: (string, count, includeCount = false) -> # If our string has no length, return without further processing return string unless string?.trim().length > 0 # If the user is expecting count to be anything other # than the default, check if it is actually a number # If not, return an empty string if includeCount and isNaN +count return "" # Manually set our default here count = 2 unless count? {pluralizers, uncountables, irregulars} = @_inflectionConstants word = string.split(/\s/).pop() isUppercase = word.toUpperCase() is word lowercaseWord = word.toLowerCase() pluralizedWord = if count is 1 or uncountables.indexOf(lowercaseWord) >= 0 then word else null unless pluralizedWord? pluralizedWord = irregulars[lowercaseWord] if irregulars[lowercaseWord]? unless pluralizedWord? for pluralizer in pluralizers when pluralizer[0].test lowercaseWord pluralizedWord = word.replace pluralizer[0], pluralizer[1] break pluralizedWord or = word pluralizedWord = pluralizedWord.toUpperCase() if isUppercase pluralizedString = string[0...-word.length] + pluralizedWord if includeCount then "#{$filter("number") count} #{pluralizedString}" else pluralizedString capitalize: (string) -> str = String(string) or "" return str.charAt(0).toUpperCase() + str[1..] uncapitalize: (string) -> str = String(string) or "" return str.charAt(0).toLowerCase() + str[1..] toCamelCase: (string) -> string.trim().replace /[-_\s]+(.)?/g, (match, c) -> c.toUpperCase() toSnakeCase: (string) -> string.trim(). replace(/([a-z\d])([A-Z]+)/g, "$1_$2"). replace(/[-\s]+/g, "_"). toLowerCase() convertKeysToCamelCase: (object) -> result = {} for own key, value of object key = @toCamelCase key value = @convertKeysToCamelCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result convertKeysToSnakeCase: (object) -> result = {} for own key, value of object key = @toSnakeCase key value = @convertKeysToSnakeCase value if typeof value is "object" and value?.constructor isnt Array result[key] = value result isArray: nativeIsArray or (obj) -> toString.call(obj) is "[object Array]" _urlRegex: /(?:(?:(http[s]{0,1}:\/\/)(?:(www|[\d\w\-]+)\.){0,1})|(www|[\d\w\-]+)\.)([\d\w\-]+)\.([A-Za-z]{2,6})(:[\d]*){0,1}(\/?[\d\w\-\?\,\'\/\\\+&amp;%\$#!\=~\.]*){0,1}/i validateUrl: (url) -> match = @_urlRegex.exec url if match? match = { url: match[0] protocol: match[1] or "http://" subdomain: match[2] or match[3] name: match[4] domain: match[5] port: match[6] path: match[7] or "/" } # Recreate the full url match["url"] = match.url match validateEmail: (email) -> emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ emailRegex.test email # credits: http://www.netlobo.com/url_query_string_javascript.html getQueryString: (url, name = "") -> name = name.replace(/[[]/,"\[").replace(/[]]/,"\]") regexS = "[\?&]"+name+"=([^&#]*)" regex = new RegExp regexS results = regex.exec url if results? then results[1] else "" parseUrlPath: (fullPath) -> urlComponents = fullPath.split "?" pathComponents = urlComponents[0].split("/") path = pathComponents[0...pathComponents.length-1].join("/") verb = pathComponents[pathComponents.length-1] queries = {} # Check if querystring exists if urlComponents.length > 1 queryStrings = urlComponents[urlComponents.length-1] for queryString in queryStrings.split("&") values = queryString.split "=" queries[values[0]] = if values[1]? then values[1] else "" return {fullPath, path, pathComponents, verb, queries} ## ## @name ## extendAttributes ## ## @description ## Extend default values with attributes ## ## @param {String} prefix Prefix of all attributes ## @param {Object} defaults Default set of attributes ## @param {Object} attributes User set attributes ## extendAttributes: (prefix = "", defaults, attributes) -> output = {} for own key, value of defaults altKey = if prefix then @capitalize(key) else key macKey = PI:KEY:<KEY>END_PI output[key] = if attributes[macKey]? attributes[macKey] or true else value # Convert to true boolean if passing in boolean string if output[key] in ["true", "false"] output[key] = output[key] is "true" # Convert to integer or numbers from strings else if output[key]?.length > 0 and not isNaN +output[key] output[key] = +output[key] return output ]
[ { "context": "\n JST['nodes/operands/basic_block']\n name: @name\n\n titleizeInstructions: (previousInstruction", "end": 817, "score": 0.6111352443695068, "start": 817, "tag": "NAME", "value": "" } ]
lib/furnace-xray/app/assets/javascripts/lib/nodes/basic_block.js.coffee
evilmartians/furnace-xray
4
class @BasicBlockNode extends Node constructor: (data, map) -> super @functions = Object.extended() update: (data, map) -> @name = data['name'] @reassign @instructionIds, data['instruction_ids'], (removed, added) => removed.each (id) => @locate(id, map).unlinkBlock(@) added.each (id) => @locate(id, map).linkBlock(@) @instructionIds = data['instruction_ids'] @instructions = @instructionIds.map (id) => @locate(id, map) linkFunction: (f) -> @functions[f.id] = f unlinkFunction: (f) -> delete @functions[f.id] attachedFunctions: -> @functions title: (previousInstructions) -> JST['nodes/block'] name: @name instructions: @titleizeInstructions(previousInstructions) operandTitle: -> JST['nodes/operands/basic_block'] name: @name titleizeInstructions: (previousInstructions) -> unless previousInstructions result = "" result += JST['nodes/diff/unchanged_line'] line: x.title() for x in @instructions result else result = "" removed = Object.extended() added = Object.extended() changed = Object.extended() unchanged = Object.extended() for cs, i in @instructions previous = previousInstructions.find (ps) -> ps.id == cs.id currentTitle = cs.title() if previous && previous.title == currentTitle unchanged[i] = previous.title previous.newPosition = i else if previous changed[i] = [previous.title, currentTitle] previous.newPosition = i else added[i] = currentTitle for ps, i in previousInstructions if !ps.newPosition? position = 0 while --i >= 0 if previousInstructions[i].newPosition? position = previousInstructions[i].newPosition+1 break removed[position] ||= [] removed[position].push ps.title [@instructions.length, previousInstructions.length].max().times (i) -> if removed[i] result += JST['nodes/diff/removed_line'](line: l) for l in removed[i] result += JST['nodes/diff/added_line'](line: added[i]) if added[i] result += JST['nodes/diff/changed_line'](before: changed[i][0], after:changed[i][1]) if changed[i] result += JST['nodes/diff/unchanged_line'](line: unchanged[i]) if unchanged[i] result references: -> ids = @instructions.last()?.operands.findAll((x) -> x instanceof BasicBlockNode).map((x) -> x.id) (ids || []).exclude((x) => x == @id)
202261
class @BasicBlockNode extends Node constructor: (data, map) -> super @functions = Object.extended() update: (data, map) -> @name = data['name'] @reassign @instructionIds, data['instruction_ids'], (removed, added) => removed.each (id) => @locate(id, map).unlinkBlock(@) added.each (id) => @locate(id, map).linkBlock(@) @instructionIds = data['instruction_ids'] @instructions = @instructionIds.map (id) => @locate(id, map) linkFunction: (f) -> @functions[f.id] = f unlinkFunction: (f) -> delete @functions[f.id] attachedFunctions: -> @functions title: (previousInstructions) -> JST['nodes/block'] name: @name instructions: @titleizeInstructions(previousInstructions) operandTitle: -> JST['nodes/operands/basic_block'] name:<NAME> @name titleizeInstructions: (previousInstructions) -> unless previousInstructions result = "" result += JST['nodes/diff/unchanged_line'] line: x.title() for x in @instructions result else result = "" removed = Object.extended() added = Object.extended() changed = Object.extended() unchanged = Object.extended() for cs, i in @instructions previous = previousInstructions.find (ps) -> ps.id == cs.id currentTitle = cs.title() if previous && previous.title == currentTitle unchanged[i] = previous.title previous.newPosition = i else if previous changed[i] = [previous.title, currentTitle] previous.newPosition = i else added[i] = currentTitle for ps, i in previousInstructions if !ps.newPosition? position = 0 while --i >= 0 if previousInstructions[i].newPosition? position = previousInstructions[i].newPosition+1 break removed[position] ||= [] removed[position].push ps.title [@instructions.length, previousInstructions.length].max().times (i) -> if removed[i] result += JST['nodes/diff/removed_line'](line: l) for l in removed[i] result += JST['nodes/diff/added_line'](line: added[i]) if added[i] result += JST['nodes/diff/changed_line'](before: changed[i][0], after:changed[i][1]) if changed[i] result += JST['nodes/diff/unchanged_line'](line: unchanged[i]) if unchanged[i] result references: -> ids = @instructions.last()?.operands.findAll((x) -> x instanceof BasicBlockNode).map((x) -> x.id) (ids || []).exclude((x) => x == @id)
true
class @BasicBlockNode extends Node constructor: (data, map) -> super @functions = Object.extended() update: (data, map) -> @name = data['name'] @reassign @instructionIds, data['instruction_ids'], (removed, added) => removed.each (id) => @locate(id, map).unlinkBlock(@) added.each (id) => @locate(id, map).linkBlock(@) @instructionIds = data['instruction_ids'] @instructions = @instructionIds.map (id) => @locate(id, map) linkFunction: (f) -> @functions[f.id] = f unlinkFunction: (f) -> delete @functions[f.id] attachedFunctions: -> @functions title: (previousInstructions) -> JST['nodes/block'] name: @name instructions: @titleizeInstructions(previousInstructions) operandTitle: -> JST['nodes/operands/basic_block'] name:PI:NAME:<NAME>END_PI @name titleizeInstructions: (previousInstructions) -> unless previousInstructions result = "" result += JST['nodes/diff/unchanged_line'] line: x.title() for x in @instructions result else result = "" removed = Object.extended() added = Object.extended() changed = Object.extended() unchanged = Object.extended() for cs, i in @instructions previous = previousInstructions.find (ps) -> ps.id == cs.id currentTitle = cs.title() if previous && previous.title == currentTitle unchanged[i] = previous.title previous.newPosition = i else if previous changed[i] = [previous.title, currentTitle] previous.newPosition = i else added[i] = currentTitle for ps, i in previousInstructions if !ps.newPosition? position = 0 while --i >= 0 if previousInstructions[i].newPosition? position = previousInstructions[i].newPosition+1 break removed[position] ||= [] removed[position].push ps.title [@instructions.length, previousInstructions.length].max().times (i) -> if removed[i] result += JST['nodes/diff/removed_line'](line: l) for l in removed[i] result += JST['nodes/diff/added_line'](line: added[i]) if added[i] result += JST['nodes/diff/changed_line'](before: changed[i][0], after:changed[i][1]) if changed[i] result += JST['nodes/diff/unchanged_line'](line: unchanged[i]) if unchanged[i] result references: -> ids = @instructions.last()?.operands.findAll((x) -> x instanceof BasicBlockNode).map((x) -> x.id) (ids || []).exclude((x) => x == @id)
[ { "context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2", "end": 414, "score": 0.9786924719810486, "start": 409, "tag": "NAME", "value": "I.B.M" } ]
lib-src/coffee/www/index.coffee
pmuellr/nodprof
6
# Licensed under the Apache License. See footer for details. utils = require "../common/utils" logger = require "../common/logger" controllers = require "./controllers" #------------------------------------------------------------------------------- amod = angular.module "nodprof", [] controllers amod #------------------------------------------------------------------------------- # Copyright 2013 I.B.M. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
193208
# Licensed under the Apache License. See footer for details. utils = require "../common/utils" logger = require "../common/logger" controllers = require "./controllers" #------------------------------------------------------------------------------- amod = angular.module "nodprof", [] controllers amod #------------------------------------------------------------------------------- # Copyright 2013 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. utils = require "../common/utils" logger = require "../common/logger" controllers = require "./controllers" #------------------------------------------------------------------------------- amod = angular.module "nodprof", [] controllers amod #------------------------------------------------------------------------------- # Copyright 2013 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
[ { "context": "ust a PDF\"\n ,\n metaData:\n author: \"Michael Müller\"\n title: \"Testreport\"\n , (error, pdf) -", "end": 2379, "score": 0.9998369216918945, "start": 2365, "tag": "NAME", "value": "Michael Müller" }, { "context": "ust a PDF\"\n ,\n me...
test/test.coffee
konsorten/jade-reporting
5
report = require "../dist/module.js" path = require "path" test = require "tape" tapSpec = require "tap-spec" report.checkDependencies null, (installed) -> test.createStream() .pipe(tapSpec()) .pipe(process.stdout) test 'report.generate(template, output[, data, config, callback]) throws an error when executing without template', (t) -> t.plan(3) t.throws -> report.generate(null, "Error.pdf") , "Error for null value thrown" t.throws -> report.generate(undefined, "Error.pdf") , "Error for undefinied value thrown" t.throws -> report.generate("", "Error.pdf") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executing without output file', (t) -> t.plan(3) t.throws -> report.generate("p Text", null) , "Error for null value thrown" t.throws -> report.generate("p Text", undefined) , "Error for undefinied value thrown" t.throws -> report.generate("p Text", "") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executables are not installed', (t) -> t.plan(2) report.generate("p Text", "Error.pdf", null, executables: wkhtmltopdf: "invalidwkhtmltopdf" , (error, pdf) -> t.assert error, "Error for wkhtmltopdf thrown" ) report.generate("p Text", "Error.pdf", null, executables: pdftk: "invalidpdftk" , (error, pdf) -> t.assert error, "Error for pdftk thrown" ) unless installed console.log "Missing dependencies. Aborting test..." return test 'report.generate(template, output[, data, config, callback]) throws an error when executing with invalid config object', (t) -> t.plan(2) t.throws -> report.generate("p Text", "Error.pdf", null, undefinedProperty: "shoudthrow" ) , "Error for undefined value thrown" t.throws -> report.generate("p Text", "Error.pdf", null, stylesheet: true ) , "Error for invalid type thrown" test "generates simple pdf from jade string", (t) -> t.plan(2) _start = Date.now() report.generate("h1 Report from string\np This is a string", "Jade Simple.pdf", subject: "Just a PDF" , metaData: author: "Michael Müller" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates simple pdf without letterhead from file", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "simple.jade"), "Jade Simple from File.pdf", subject: "Just a PDF" , metaData: author: "Michael Müller" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates complex pdf with letterhead", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "complex.jade"), "Jade Complex with Letterhead.pdf", subject: "Just A Report" tvshows: "Doctor Who": station: "BBC" rating: "Geronimo!" "Person of Interest": station: "CBS" rating: "Great" "The Mentalist": station: "CBS" rating: "Great" "The Simpsons": station: "FOX" rating: "Great" "Family Guy": station: "FOX" rating: "Great" "True Blood": station: "HBO" rating: "Bad" "Desperate Housewifes": station: "ABC" rating: "Bad" , metaData: author: "Michael Müller" title: "Testreport" letterhead:"test/letterhead.pdf" margin: left: 20 top: 50 bottom: 50 , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" )
29863
report = require "../dist/module.js" path = require "path" test = require "tape" tapSpec = require "tap-spec" report.checkDependencies null, (installed) -> test.createStream() .pipe(tapSpec()) .pipe(process.stdout) test 'report.generate(template, output[, data, config, callback]) throws an error when executing without template', (t) -> t.plan(3) t.throws -> report.generate(null, "Error.pdf") , "Error for null value thrown" t.throws -> report.generate(undefined, "Error.pdf") , "Error for undefinied value thrown" t.throws -> report.generate("", "Error.pdf") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executing without output file', (t) -> t.plan(3) t.throws -> report.generate("p Text", null) , "Error for null value thrown" t.throws -> report.generate("p Text", undefined) , "Error for undefinied value thrown" t.throws -> report.generate("p Text", "") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executables are not installed', (t) -> t.plan(2) report.generate("p Text", "Error.pdf", null, executables: wkhtmltopdf: "invalidwkhtmltopdf" , (error, pdf) -> t.assert error, "Error for wkhtmltopdf thrown" ) report.generate("p Text", "Error.pdf", null, executables: pdftk: "invalidpdftk" , (error, pdf) -> t.assert error, "Error for pdftk thrown" ) unless installed console.log "Missing dependencies. Aborting test..." return test 'report.generate(template, output[, data, config, callback]) throws an error when executing with invalid config object', (t) -> t.plan(2) t.throws -> report.generate("p Text", "Error.pdf", null, undefinedProperty: "shoudthrow" ) , "Error for undefined value thrown" t.throws -> report.generate("p Text", "Error.pdf", null, stylesheet: true ) , "Error for invalid type thrown" test "generates simple pdf from jade string", (t) -> t.plan(2) _start = Date.now() report.generate("h1 Report from string\np This is a string", "Jade Simple.pdf", subject: "Just a PDF" , metaData: author: "<NAME>" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates simple pdf without letterhead from file", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "simple.jade"), "Jade Simple from File.pdf", subject: "Just a PDF" , metaData: author: "<NAME>" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates complex pdf with letterhead", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "complex.jade"), "Jade Complex with Letterhead.pdf", subject: "Just A Report" tvshows: "Doctor Who": station: "BBC" rating: "Geronimo!" "Person of Interest": station: "CBS" rating: "Great" "The Mentalist": station: "CBS" rating: "Great" "The Simpsons": station: "FOX" rating: "Great" "Family Guy": station: "FOX" rating: "Great" "True Blood": station: "HBO" rating: "Bad" "Desperate Housewifes": station: "ABC" rating: "Bad" , metaData: author: "<NAME>" title: "Testreport" letterhead:"test/letterhead.pdf" margin: left: 20 top: 50 bottom: 50 , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" )
true
report = require "../dist/module.js" path = require "path" test = require "tape" tapSpec = require "tap-spec" report.checkDependencies null, (installed) -> test.createStream() .pipe(tapSpec()) .pipe(process.stdout) test 'report.generate(template, output[, data, config, callback]) throws an error when executing without template', (t) -> t.plan(3) t.throws -> report.generate(null, "Error.pdf") , "Error for null value thrown" t.throws -> report.generate(undefined, "Error.pdf") , "Error for undefinied value thrown" t.throws -> report.generate("", "Error.pdf") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executing without output file', (t) -> t.plan(3) t.throws -> report.generate("p Text", null) , "Error for null value thrown" t.throws -> report.generate("p Text", undefined) , "Error for undefinied value thrown" t.throws -> report.generate("p Text", "") , "Error for empty value thrown" test 'report.generate(template, output[, data, config, callback]) throws an error when executables are not installed', (t) -> t.plan(2) report.generate("p Text", "Error.pdf", null, executables: wkhtmltopdf: "invalidwkhtmltopdf" , (error, pdf) -> t.assert error, "Error for wkhtmltopdf thrown" ) report.generate("p Text", "Error.pdf", null, executables: pdftk: "invalidpdftk" , (error, pdf) -> t.assert error, "Error for pdftk thrown" ) unless installed console.log "Missing dependencies. Aborting test..." return test 'report.generate(template, output[, data, config, callback]) throws an error when executing with invalid config object', (t) -> t.plan(2) t.throws -> report.generate("p Text", "Error.pdf", null, undefinedProperty: "shoudthrow" ) , "Error for undefined value thrown" t.throws -> report.generate("p Text", "Error.pdf", null, stylesheet: true ) , "Error for invalid type thrown" test "generates simple pdf from jade string", (t) -> t.plan(2) _start = Date.now() report.generate("h1 Report from string\np This is a string", "Jade Simple.pdf", subject: "Just a PDF" , metaData: author: "PI:NAME:<NAME>END_PI" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates simple pdf without letterhead from file", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "simple.jade"), "Jade Simple from File.pdf", subject: "Just a PDF" , metaData: author: "PI:NAME:<NAME>END_PI" title: "Testreport" , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" ) test "generates complex pdf with letterhead", (t) -> t.plan(2) _start = Date.now() report.generate(path.join(__dirname, "complex.jade"), "Jade Complex with Letterhead.pdf", subject: "Just A Report" tvshows: "Doctor Who": station: "BBC" rating: "Geronimo!" "Person of Interest": station: "CBS" rating: "Great" "The Mentalist": station: "CBS" rating: "Great" "The Simpsons": station: "FOX" rating: "Great" "Family Guy": station: "FOX" rating: "Great" "True Blood": station: "HBO" rating: "Bad" "Desperate Housewifes": station: "ABC" rating: "Bad" , metaData: author: "PI:NAME:<NAME>END_PI" title: "Testreport" letterhead:"test/letterhead.pdf" margin: left: 20 top: 50 bottom: 50 , (error, pdf) -> t.error error, "No error occurred" _end = Date.now() t.assert pdf, "PDF File created: " + pdf + " in " + (_end-_start) + "ms" )
[ { "context": " = form.lastName\n\t\temail = form.email\n\t\tpassword = form.password\n\n\t\t# Try to authenticate if form and fields are v", "end": 450, "score": 0.9922892451286316, "start": 437, "tag": "PASSWORD", "value": "form.password" }, { "context": "hen ->\n\t\t\t\temail = ema...
js/controllers/modal/signup.coffee
SwarmCorp/razzledazzle
0
window.app.controller 'modalSignupController', ($scope, $modal, $modalInstance, User) -> # Loading indicator to show/hide spinner $scope.loading = false # Initially signup form isn't submitted $scope.form = {} $scope.formSubmitted = false # Submit signup form $scope.signup = -> $scope.formSubmitted = true form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = form.password # Try to authenticate if form and fields are valid if form.$valid || (firstName.$valid && lastName.$valid && email.$valid && $scope.passwordsMatch()) $scope.formSubmitted = false $scope.loading = true User.create email.$viewValue, password.$viewValue .then -> email = email.$viewValue password = password.$viewValue firstName = firstName.$viewValue lastName = lastName.$viewValue User.login email, password, true .then -> User.update first_name: firstName last_name: lastName email: email wallet: null .then -> $scope.loading = false $modalInstance.close() .then null, (reason) -> $scope.loading = false switch reason.code when 'INVALID_EMAIL' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Invalid email.' when 'EMAIL_TAKEN' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Email address is already in use.' # Check fields validity (except password) $scope.hasError = (field) -> form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = form.password if (field.$dirty && field.$invalid) || ( ($scope.formSubmitted || $scope.formSubmitted) && field.$invalid) email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage firstName.errorMessage = if firstName.$invalid && !firstName.customError then 'First name is required.' else firstName.errorMessage lastName.errorMessage = if lastName.$invalid && !lastName.customError then 'Last name is required.' else lastName.errorMessage email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage return true # Check password validity $scope.passwordsMatch = -> password = $scope.form.signup.password passwordConfirmation = $scope.form.signup.passwordConfirm password.$setValidity 'password', true passwordConfirmation.$setValidity 'passwordConfirmation', true if $scope.formSubmitted if password.$pristine || passwordConfirmation.$pristine || password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'password', false passwordConfirmation.$setValidity 'incorrect', false if password.$dirty && password.$viewValue != passwordConfirmation.$viewValue password.$setValidity 'incorrect', true passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true else if password.$dirty && passwordConfirmation.$dirty && password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'incorrect', false passwordConfirmation.$setValidity 'incorrect', false passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true $scope.resetPasswordValidity = -> $scope.form.signup.password.$setValidity 'incorrect', true $scope.form.signup.password.customError = false $scope.login = -> $modalInstance.close() $modal.open templateUrl: 'partials/app/modal/login.html', controller: 'modalLoginController' $scope.loginWithFacebook = -> User.facebookLogin() .then -> $modalInstance.close()
83725
window.app.controller 'modalSignupController', ($scope, $modal, $modalInstance, User) -> # Loading indicator to show/hide spinner $scope.loading = false # Initially signup form isn't submitted $scope.form = {} $scope.formSubmitted = false # Submit signup form $scope.signup = -> $scope.formSubmitted = true form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = <PASSWORD> # Try to authenticate if form and fields are valid if form.$valid || (firstName.$valid && lastName.$valid && email.$valid && $scope.passwordsMatch()) $scope.formSubmitted = false $scope.loading = true User.create email.$viewValue, password.$viewValue .then -> email = email.$viewValue password = <PASSWORD>.$viewValue firstName = firstName.$viewValue lastName = lastName.$viewValue User.login email, password, true .then -> User.update first_name: <NAME> last_name: <NAME> email: email wallet: null .then -> $scope.loading = false $modalInstance.close() .then null, (reason) -> $scope.loading = false switch reason.code when 'INVALID_EMAIL' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Invalid email.' when 'EMAIL_TAKEN' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Email address is already in use.' # Check fields validity (except password) $scope.hasError = (field) -> form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = <PASSWORD> if (field.$dirty && field.$invalid) || ( ($scope.formSubmitted || $scope.formSubmitted) && field.$invalid) email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage firstName.errorMessage = if firstName.$invalid && !firstName.customError then 'First name is required.' else firstName.errorMessage lastName.errorMessage = if lastName.$invalid && !lastName.customError then 'Last name is required.' else lastName.errorMessage email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage return true # Check password validity $scope.passwordsMatch = -> password = $scope.form.signup.password passwordConfirmation = $scope.form.signup.passwordConfirm password.$setValidity 'password', true passwordConfirmation.$setValidity 'passwordConfirmation', true if $scope.formSubmitted if password.$pristine || passwordConfirmation.$pristine || password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'password', false passwordConfirmation.$setValidity 'incorrect', false if password.$dirty && password.$viewValue != passwordConfirmation.$viewValue password.$setValidity 'incorrect', true passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true else if password.$dirty && passwordConfirmation.$dirty && password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'incorrect', false passwordConfirmation.$setValidity 'incorrect', false passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true $scope.resetPasswordValidity = -> $scope.form.signup.password.$setValidity 'incorrect', true $scope.form.signup.password.customError = false $scope.login = -> $modalInstance.close() $modal.open templateUrl: 'partials/app/modal/login.html', controller: 'modalLoginController' $scope.loginWithFacebook = -> User.facebookLogin() .then -> $modalInstance.close()
true
window.app.controller 'modalSignupController', ($scope, $modal, $modalInstance, User) -> # Loading indicator to show/hide spinner $scope.loading = false # Initially signup form isn't submitted $scope.form = {} $scope.formSubmitted = false # Submit signup form $scope.signup = -> $scope.formSubmitted = true form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = PI:PASSWORD:<PASSWORD>END_PI # Try to authenticate if form and fields are valid if form.$valid || (firstName.$valid && lastName.$valid && email.$valid && $scope.passwordsMatch()) $scope.formSubmitted = false $scope.loading = true User.create email.$viewValue, password.$viewValue .then -> email = email.$viewValue password = PI:PASSWORD:<PASSWORD>END_PI.$viewValue firstName = firstName.$viewValue lastName = lastName.$viewValue User.login email, password, true .then -> User.update first_name: PI:NAME:<NAME>END_PI last_name: PI:NAME:<NAME>END_PI email: email wallet: null .then -> $scope.loading = false $modalInstance.close() .then null, (reason) -> $scope.loading = false switch reason.code when 'INVALID_EMAIL' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Invalid email.' when 'EMAIL_TAKEN' email.$setValidity 'email', false email.customError = true email.errorMessage = 'Email address is already in use.' # Check fields validity (except password) $scope.hasError = (field) -> form = $scope.form.signup firstName = form.firstName lastName = form.lastName email = form.email password = PI:PASSWORD:<PASSWORD>END_PI if (field.$dirty && field.$invalid) || ( ($scope.formSubmitted || $scope.formSubmitted) && field.$invalid) email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage firstName.errorMessage = if firstName.$invalid && !firstName.customError then 'First name is required.' else firstName.errorMessage lastName.errorMessage = if lastName.$invalid && !lastName.customError then 'Last name is required.' else lastName.errorMessage email.errorMessage = if email.$invalid && !email.customError then 'Valid email is required.' else email.errorMessage password.errorMessage = if password.$invalid && !password.customError then 'Password is required.' else password.errorMessage return true # Check password validity $scope.passwordsMatch = -> password = $scope.form.signup.password passwordConfirmation = $scope.form.signup.passwordConfirm password.$setValidity 'password', true passwordConfirmation.$setValidity 'passwordConfirmation', true if $scope.formSubmitted if password.$pristine || passwordConfirmation.$pristine || password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'password', false passwordConfirmation.$setValidity 'incorrect', false if password.$dirty && password.$viewValue != passwordConfirmation.$viewValue password.$setValidity 'incorrect', true passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true else if password.$dirty && passwordConfirmation.$dirty && password.$viewValue != passwordConfirmation.$viewValue if password.$pristine then password.$setValidity 'incorrect', false passwordConfirmation.$setValidity 'incorrect', false passwordConfirmation.errorMessage = 'Passwords must match.' return false else return true $scope.resetPasswordValidity = -> $scope.form.signup.password.$setValidity 'incorrect', true $scope.form.signup.password.customError = false $scope.login = -> $modalInstance.close() $modal.open templateUrl: 'partials/app/modal/login.html', controller: 'modalLoginController' $scope.loginWithFacebook = -> User.facebookLogin() .then -> $modalInstance.close()
[ { "context": "rn('some code')\n\n process.env.TEST_USERNAME = 'testusername'\n process.env.TEST_PASSWORD = 'testpassword'\n\n", "end": 641, "score": 0.9986116886138916, "start": 629, "tag": "USERNAME", "value": "testusername" }, { "context": "= 'testusername'\n process.env.T...
spec/adapters/authorizer_spec.coffee
dnesteryuk/hubot-torrent
2
nock = require('nock') Authorizer = require('../../lib/hubot-torrent/adapters/authorizer') describe 'Adapter.Authorizer', -> beforeEach -> @granter = name: -> 'TestTorrent' requiredEnvVars: -> ['TEST_USERNAME', 'TEST_PASSWORD'] authorizeOptions: -> host: 'google.com' port: 80 method: 'POST' path: '/login' headers: 'Content-Type': 'application/x-www-form-urlencoded' authorizeData: -> 'test=1' parseAuthCode: -> spyOn(@granter, 'parseAuthCode').andReturn('some code') process.env.TEST_USERNAME = 'testusername' process.env.TEST_PASSWORD = 'testpassword' nock.disableNetConnect() describe 'initialize', -> beforeEach -> @errorMsg = 'To use TestTorrent adapter you need to define credentials to the service.' + " Please, add following environment variables to ~/.bashrc file\n" + "export TEST_USERNAME=\"your value\"\n" + "export TEST_PASSWORD=\"your value\"" describe 'when there are required data', -> it 'does not raise any error', -> new Authorizer(@granter) describe 'when there is not username', -> beforeEach -> delete process.env['TEST_USERNAME'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe 'when there is not password', -> beforeEach -> delete process.env['TEST_PASSWORD'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe '#authorize', -> beforeEach -> @mock = nock( 'http://google.com' { reqheaders: 'Content-Type': 'application/x-www-form-urlencoded' 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0' } ) .post( '/login' {test: 1} ) @authorizer = new Authorizer(@granter) describe 'on successful authorization', -> beforeEach -> @mock.reply( 201 'Hello World!' ) it 'sends the response to the authorize granter', (done) -> @authorizer.authorize( => args = @granter.parseAuthCode.calls[0].args[0] expect(args.statusCode).toEqual(201) done() ) it 'stores the authorization data', (done) -> @authorizer.authorize( => expect(@authorizer.authorizeData()).toEqual( 'some code' ) done() ) describe 'on failure', -> beforeEach -> @mock.reply( 501 'something went wrong' ) xit 'throws an error', -> @authorizer.authorize()
11198
nock = require('nock') Authorizer = require('../../lib/hubot-torrent/adapters/authorizer') describe 'Adapter.Authorizer', -> beforeEach -> @granter = name: -> 'TestTorrent' requiredEnvVars: -> ['TEST_USERNAME', 'TEST_PASSWORD'] authorizeOptions: -> host: 'google.com' port: 80 method: 'POST' path: '/login' headers: 'Content-Type': 'application/x-www-form-urlencoded' authorizeData: -> 'test=1' parseAuthCode: -> spyOn(@granter, 'parseAuthCode').andReturn('some code') process.env.TEST_USERNAME = 'testusername' process.env.TEST_PASSWORD = '<PASSWORD>' nock.disableNetConnect() describe 'initialize', -> beforeEach -> @errorMsg = 'To use TestTorrent adapter you need to define credentials to the service.' + " Please, add following environment variables to ~/.bashrc file\n" + "export TEST_USERNAME=\"your value\"\n" + "export TEST_PASSWORD=\"<PASSWORD>\"" describe 'when there are required data', -> it 'does not raise any error', -> new Authorizer(@granter) describe 'when there is not username', -> beforeEach -> delete process.env['TEST_USERNAME'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe 'when there is not password', -> beforeEach -> delete process.env['TEST_PASSWORD'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe '#authorize', -> beforeEach -> @mock = nock( 'http://google.com' { reqheaders: 'Content-Type': 'application/x-www-form-urlencoded' 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0' } ) .post( '/login' {test: 1} ) @authorizer = new Authorizer(@granter) describe 'on successful authorization', -> beforeEach -> @mock.reply( 201 'Hello World!' ) it 'sends the response to the authorize granter', (done) -> @authorizer.authorize( => args = @granter.parseAuthCode.calls[0].args[0] expect(args.statusCode).toEqual(201) done() ) it 'stores the authorization data', (done) -> @authorizer.authorize( => expect(@authorizer.authorizeData()).toEqual( 'some code' ) done() ) describe 'on failure', -> beforeEach -> @mock.reply( 501 'something went wrong' ) xit 'throws an error', -> @authorizer.authorize()
true
nock = require('nock') Authorizer = require('../../lib/hubot-torrent/adapters/authorizer') describe 'Adapter.Authorizer', -> beforeEach -> @granter = name: -> 'TestTorrent' requiredEnvVars: -> ['TEST_USERNAME', 'TEST_PASSWORD'] authorizeOptions: -> host: 'google.com' port: 80 method: 'POST' path: '/login' headers: 'Content-Type': 'application/x-www-form-urlencoded' authorizeData: -> 'test=1' parseAuthCode: -> spyOn(@granter, 'parseAuthCode').andReturn('some code') process.env.TEST_USERNAME = 'testusername' process.env.TEST_PASSWORD = 'PI:PASSWORD:<PASSWORD>END_PI' nock.disableNetConnect() describe 'initialize', -> beforeEach -> @errorMsg = 'To use TestTorrent adapter you need to define credentials to the service.' + " Please, add following environment variables to ~/.bashrc file\n" + "export TEST_USERNAME=\"your value\"\n" + "export TEST_PASSWORD=\"PI:PASSWORD:<PASSWORD>END_PI\"" describe 'when there are required data', -> it 'does not raise any error', -> new Authorizer(@granter) describe 'when there is not username', -> beforeEach -> delete process.env['TEST_USERNAME'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe 'when there is not password', -> beforeEach -> delete process.env['TEST_PASSWORD'] it 'raises an error about missed data', (done) -> try new Authorizer(@granter) catch e expect(e).toEqual(@errorMsg) done() describe '#authorize', -> beforeEach -> @mock = nock( 'http://google.com' { reqheaders: 'Content-Type': 'application/x-www-form-urlencoded' 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0' } ) .post( '/login' {test: 1} ) @authorizer = new Authorizer(@granter) describe 'on successful authorization', -> beforeEach -> @mock.reply( 201 'Hello World!' ) it 'sends the response to the authorize granter', (done) -> @authorizer.authorize( => args = @granter.parseAuthCode.calls[0].args[0] expect(args.statusCode).toEqual(201) done() ) it 'stores the authorization data', (done) -> @authorizer.authorize( => expect(@authorizer.authorizeData()).toEqual( 'some code' ) done() ) describe 'on failure', -> beforeEach -> @mock.reply( 501 'something went wrong' ) xit 'throws an error', -> @authorizer.authorize()
[ { "context": "'\n },\n 'id': '6096360202846601376',\n 'token': 'ceec931a-c131-11e5-87c1-0c51b7557be8',\n 'name': 'Wf", "end": 194, "score": 0.6056936979293823, "start": 192, "tag": "KEY", "value": "ce" }, { "context": " },\n 'id': '6096360202846601376',\n 'token': 'ceec931a-c1...
client/mocks/mock.collaborationchannel.coffee
ezgikaysi/koding
1
module.exports = { 'watchers': {}, 'bongo_': { 'instanceId': '497eefa0616721b4a084cb188feb4f8c', 'constructorName': 'SocialChannel' }, 'id': '6096360202846601376', 'token': 'ceec931a-c131-11e5-87c1-0c51b7557be8', 'name': 'Wf2J0yS5BUqQ9rE9', 'creatorId': '2', 'groupName': 'turunc-gokhan', 'purpose': '___collaborativeSession.', 'typeConstant': 'collaboration', 'privacyConstant': 'private', 'metaBits': 0, 'payload': null, 'createdAt': '2016-01-22T19:58:57.39535886+02:00', 'updatedAt': '2016-01-22T19:58:57.39535886+02:00', 'deletedAt': '0001-01-01T00:00:00Z', '_id': '6096360202846601376', 'isParticipant': true, 'accountOldId': '569e54e73577d1b63864cc9f', 'participantCount': 1, 'participantsPreview': [ { '_id': '569e54e73577d1b63864cc9f', 'constructorName': 'JAccount' } ], 'unreadCount': 0, 'lastMessage': { 'watchers': { 'repliesCount': [ null ] }, 'bongo_': { 'instanceId': 'd547aba21f9ea74abe43d0004f97c7ef', 'constructorName': 'SocialMessage' }, 'id': '6096360203282809762', 'token': 'cefde74e-c131-11e5-8c3f-b2d1f85e946b', 'body': 'has started the session', 'slug': '', 'typeConstant': 'system', 'accountId': '2', 'initialChannelId': '6096360202846601376', 'metaBits': 0, 'createdAt': '2016-01-22T17:58:57.505Z', 'updatedAt': '2016-01-22T17:58:57.505Z', 'deletedAt': '0001-01-01T00:00:00.000Z', 'payload': { 'initialParticipants': [], 'systemType': 'initiate' }, '_id': '6096360203282809762', 'account': { '_id': '569e54e73577d1b63864cc9f', 'constructorName': 'JAccount' }, 'replyIds': {}, 'replies': [], 'repliesCount': 0, 'isFollowed': false, 'integration': null, 'interactions': { 'like': { 'isInteracted': false, 'actorsPreview': [], 'actorsCount': 0 } } }, 'replies': [] }
191553
module.exports = { 'watchers': {}, 'bongo_': { 'instanceId': '497eefa0616721b4a084cb188feb4f8c', 'constructorName': 'SocialChannel' }, 'id': '6096360202846601376', 'token': '<KEY> <PASSWORD>', 'name': 'Wf2J0yS5BUqQ9rE9', 'creatorId': '2', 'groupName': 'turunc-gokhan', 'purpose': '___collaborativeSession.', 'typeConstant': 'collaboration', 'privacyConstant': 'private', 'metaBits': 0, 'payload': null, 'createdAt': '2016-01-22T19:58:57.39535886+02:00', 'updatedAt': '2016-01-22T19:58:57.39535886+02:00', 'deletedAt': '0001-01-01T00:00:00Z', '_id': '6096360202846601376', 'isParticipant': true, 'accountOldId': '<KEY>', 'participantCount': 1, 'participantsPreview': [ { '_id': '569e54e73577d1b63864cc9f', 'constructorName': 'JAccount' } ], 'unreadCount': 0, 'lastMessage': { 'watchers': { 'repliesCount': [ null ] }, 'bongo_': { 'instanceId': 'd547aba21f9ea74abe43d0004f97c7ef', 'constructorName': 'SocialMessage' }, 'id': '6096360203282809762', 'token': '<PASSWORD>', 'body': 'has started the session', 'slug': '', 'typeConstant': 'system', 'accountId': '2', 'initialChannelId': '6096360202846601376', 'metaBits': 0, 'createdAt': '2016-01-22T17:58:57.505Z', 'updatedAt': '2016-01-22T17:58:57.505Z', 'deletedAt': '0001-01-01T00:00:00.000Z', 'payload': { 'initialParticipants': [], 'systemType': 'initiate' }, '_id': '6096360203282809762', 'account': { '_id': '<KEY>', 'constructorName': 'JAccount' }, 'replyIds': {}, 'replies': [], 'repliesCount': 0, 'isFollowed': false, 'integration': null, 'interactions': { 'like': { 'isInteracted': false, 'actorsPreview': [], 'actorsCount': 0 } } }, 'replies': [] }
true
module.exports = { 'watchers': {}, 'bongo_': { 'instanceId': '497eefa0616721b4a084cb188feb4f8c', 'constructorName': 'SocialChannel' }, 'id': '6096360202846601376', 'token': 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', 'name': 'Wf2J0yS5BUqQ9rE9', 'creatorId': '2', 'groupName': 'turunc-gokhan', 'purpose': '___collaborativeSession.', 'typeConstant': 'collaboration', 'privacyConstant': 'private', 'metaBits': 0, 'payload': null, 'createdAt': '2016-01-22T19:58:57.39535886+02:00', 'updatedAt': '2016-01-22T19:58:57.39535886+02:00', 'deletedAt': '0001-01-01T00:00:00Z', '_id': '6096360202846601376', 'isParticipant': true, 'accountOldId': 'PI:KEY:<KEY>END_PI', 'participantCount': 1, 'participantsPreview': [ { '_id': '569e54e73577d1b63864cc9f', 'constructorName': 'JAccount' } ], 'unreadCount': 0, 'lastMessage': { 'watchers': { 'repliesCount': [ null ] }, 'bongo_': { 'instanceId': 'd547aba21f9ea74abe43d0004f97c7ef', 'constructorName': 'SocialMessage' }, 'id': '6096360203282809762', 'token': 'PI:PASSWORD:<PASSWORD>END_PI', 'body': 'has started the session', 'slug': '', 'typeConstant': 'system', 'accountId': '2', 'initialChannelId': '6096360202846601376', 'metaBits': 0, 'createdAt': '2016-01-22T17:58:57.505Z', 'updatedAt': '2016-01-22T17:58:57.505Z', 'deletedAt': '0001-01-01T00:00:00.000Z', 'payload': { 'initialParticipants': [], 'systemType': 'initiate' }, '_id': '6096360203282809762', 'account': { '_id': 'PI:KEY:<KEY>END_PI', 'constructorName': 'JAccount' }, 'replyIds': {}, 'replies': [], 'repliesCount': 0, 'isFollowed': false, 'integration': null, 'interactions': { 'like': { 'isInteracted': false, 'actorsPreview': [], 'actorsCount': 0 } } }, 'replies': [] }
[ { "context": "hen return statement contains assignment\n# @author Ilya Volodin\n###\n'use strict'\n\n#------------------------------", "end": 98, "score": 0.9997566342353821, "start": 86, "tag": "NAME", "value": "Ilya Volodin" } ]
src/rules/no-return-assign.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag when return statement contains assignment # @author Ilya Volodin ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/ #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow assignment operators in `return` statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-return-assign' schema: [enum: ['except-parens', 'always']] create: (context) -> always = (context.options[0] or 'except-parens') isnt 'except-parens' sourceCode = context.getSourceCode() AssignmentExpression: (node) -> return if not always and astUtils.isParenthesised sourceCode, node currentChild = node {parent} = currentChild # Find ReturnStatement or ArrowFunctionExpression in ancestors. while parent and not SENTINEL_TYPE.test parent.type currentChild = parent {parent} = parent # Reports. if parent and parent.type is 'ReturnStatement' context.report node: parent message: 'Return statement should not contain assignment.' else if currentChild.returns context.report node: currentChild message: 'Implicit return statement should not contain assignment.' # else if ( # parent and # parent.type is 'ArrowFunctionExpression' and # parent.body is currentChild # ) # context.report # node: parent # message: 'Arrow function should not return assignment.'
203036
###* # @fileoverview Rule to flag when return statement contains assignment # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/ #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow assignment operators in `return` statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-return-assign' schema: [enum: ['except-parens', 'always']] create: (context) -> always = (context.options[0] or 'except-parens') isnt 'except-parens' sourceCode = context.getSourceCode() AssignmentExpression: (node) -> return if not always and astUtils.isParenthesised sourceCode, node currentChild = node {parent} = currentChild # Find ReturnStatement or ArrowFunctionExpression in ancestors. while parent and not SENTINEL_TYPE.test parent.type currentChild = parent {parent} = parent # Reports. if parent and parent.type is 'ReturnStatement' context.report node: parent message: 'Return statement should not contain assignment.' else if currentChild.returns context.report node: currentChild message: 'Implicit return statement should not contain assignment.' # else if ( # parent and # parent.type is 'ArrowFunctionExpression' and # parent.body is currentChild # ) # context.report # node: parent # message: 'Arrow function should not return assignment.'
true
###* # @fileoverview Rule to flag when return statement contains assignment # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/ #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow assignment operators in `return` statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-return-assign' schema: [enum: ['except-parens', 'always']] create: (context) -> always = (context.options[0] or 'except-parens') isnt 'except-parens' sourceCode = context.getSourceCode() AssignmentExpression: (node) -> return if not always and astUtils.isParenthesised sourceCode, node currentChild = node {parent} = currentChild # Find ReturnStatement or ArrowFunctionExpression in ancestors. while parent and not SENTINEL_TYPE.test parent.type currentChild = parent {parent} = parent # Reports. if parent and parent.type is 'ReturnStatement' context.report node: parent message: 'Return statement should not contain assignment.' else if currentChild.returns context.report node: currentChild message: 'Implicit return statement should not contain assignment.' # else if ( # parent and # parent.type is 'ArrowFunctionExpression' and # parent.body is currentChild # ) # context.report # node: parent # message: 'Arrow function should not return assignment.'
[ { "context": "est\n checkHttp: (opt={}, cb) ->\n opt.user ?= \"admin\"\n opt.pass ?= \"admin\"\n opt.port ?= 80\n o", "end": 918, "score": 0.9848883152008057, "start": 913, "tag": "USERNAME", "value": "admin" }, { "context": ", cb) ->\n opt.user ?= \"admin\"\n opt....
lib/main.coffee
contra/hackery
1
request = require 'request' ftp = require 'jsftp' ping = require 'ping' portscanner = require 'portscanner' async = require 'async' hackery = # Networking stuff ping: ping.sys.probe scan: (host, port, cb) -> portscanner.checkPortStatus port, host, (err, res) -> cb !err and res isnt 'closed' scanAll: (host, ports, cb) -> it = (port, cb) -> hackery.scan host, port, cb async.filter ports, it, cb scanRange: (host, start, finish, cb) -> hackery.scanAll host, [start..finish], cb # FTP Stuff ftp: ftp checkFtp: (opt={}, cb) -> opt.user ?= "Anonymous" opt.pass ?= "" conn = new ftp host: opt.host port: opt.port conn.auth opt.user, opt.pass, (err, res) -> conn.features ?= [] conn.authorized ?= !err cb conn.authorized, conn.features, conn # HTTP Stuff http: request checkHttp: (opt={}, cb) -> opt.user ?= "admin" opt.pass ?= "admin" opt.port ?= 80 opt.host = "http://#{opt.user}:#{opt.pass}@#{opt.host}:#{opt.port}" request opt.host, (err, res, body) -> return cb err if err? return cb null, body module.exports = hackery
179301
request = require 'request' ftp = require 'jsftp' ping = require 'ping' portscanner = require 'portscanner' async = require 'async' hackery = # Networking stuff ping: ping.sys.probe scan: (host, port, cb) -> portscanner.checkPortStatus port, host, (err, res) -> cb !err and res isnt 'closed' scanAll: (host, ports, cb) -> it = (port, cb) -> hackery.scan host, port, cb async.filter ports, it, cb scanRange: (host, start, finish, cb) -> hackery.scanAll host, [start..finish], cb # FTP Stuff ftp: ftp checkFtp: (opt={}, cb) -> opt.user ?= "Anonymous" opt.pass ?= "" conn = new ftp host: opt.host port: opt.port conn.auth opt.user, opt.pass, (err, res) -> conn.features ?= [] conn.authorized ?= !err cb conn.authorized, conn.features, conn # HTTP Stuff http: request checkHttp: (opt={}, cb) -> opt.user ?= "admin" opt.pass ?= "<PASSWORD>" opt.port ?= 80 opt.host = "http://#{opt.user}:#{opt.pass}@#{opt.host}:#{opt.port}" request opt.host, (err, res, body) -> return cb err if err? return cb null, body module.exports = hackery
true
request = require 'request' ftp = require 'jsftp' ping = require 'ping' portscanner = require 'portscanner' async = require 'async' hackery = # Networking stuff ping: ping.sys.probe scan: (host, port, cb) -> portscanner.checkPortStatus port, host, (err, res) -> cb !err and res isnt 'closed' scanAll: (host, ports, cb) -> it = (port, cb) -> hackery.scan host, port, cb async.filter ports, it, cb scanRange: (host, start, finish, cb) -> hackery.scanAll host, [start..finish], cb # FTP Stuff ftp: ftp checkFtp: (opt={}, cb) -> opt.user ?= "Anonymous" opt.pass ?= "" conn = new ftp host: opt.host port: opt.port conn.auth opt.user, opt.pass, (err, res) -> conn.features ?= [] conn.authorized ?= !err cb conn.authorized, conn.features, conn # HTTP Stuff http: request checkHttp: (opt={}, cb) -> opt.user ?= "admin" opt.pass ?= "PI:PASSWORD:<PASSWORD>END_PI" opt.port ?= 80 opt.host = "http://#{opt.user}:#{opt.pass}@#{opt.host}:#{opt.port}" request opt.host, (err, res, body) -> return cb err if err? return cb null, body module.exports = hackery
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9994208812713623, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-tty-wrap.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") TTY = process.binding("tty_wrap").TTY isTTY = process.binding("tty_wrap").isTTY if isTTY(1) is false console.error "fd 1 is not a tty. skipping test." process.exit 0 handle = new TTY(1) callbacks = 0 req1 = handle.writeBuffer(Buffer("hello world\n")) req1.oncomplete = -> callbacks++ return req2 = handle.writeBuffer(Buffer("hello world\n")) req2.oncomplete = -> callbacks++ return process.on "exit", -> assert.equal 2, callbacks return
36944
# 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") TTY = process.binding("tty_wrap").TTY isTTY = process.binding("tty_wrap").isTTY if isTTY(1) is false console.error "fd 1 is not a tty. skipping test." process.exit 0 handle = new TTY(1) callbacks = 0 req1 = handle.writeBuffer(Buffer("hello world\n")) req1.oncomplete = -> callbacks++ return req2 = handle.writeBuffer(Buffer("hello world\n")) req2.oncomplete = -> callbacks++ return process.on "exit", -> assert.equal 2, callbacks 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") TTY = process.binding("tty_wrap").TTY isTTY = process.binding("tty_wrap").isTTY if isTTY(1) is false console.error "fd 1 is not a tty. skipping test." process.exit 0 handle = new TTY(1) callbacks = 0 req1 = handle.writeBuffer(Buffer("hello world\n")) req1.oncomplete = -> callbacks++ return req2 = handle.writeBuffer(Buffer("hello world\n")) req2.oncomplete = -> callbacks++ return process.on "exit", -> assert.equal 2, callbacks return
[ { "context": "hbluHttp\n uuid: '1234'\n token: 'tok3n'\n server: 'google.co'\n port: 55", "end": 418, "score": 0.9973215460777283, "start": 413, "tag": "PASSWORD", "value": "tok3n" }, { "context": "t token', ->\n expect(@sut.token).to.equal ...
node_modules/passport-octoblu/node_modules/meshblu-http/test/meshblu-http-spec.coffee
ratokeshi/endo-google-cloud-platform
0
MeshbluHttp = require '../src/meshblu-http' describe 'MeshbluHttp', -> describe '->constructor', -> describe 'default', -> beforeEach -> @sut = new MeshbluHttp it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'https://meshblu.octoblu.com:443' describe 'with options', -> beforeEach -> @sut = new MeshbluHttp uuid: '1234' token: 'tok3n' server: 'google.co' port: 555 protocol: 'ldap' it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ldap://google.co:555' it 'should set the protocol', -> expect(@sut.protocol).to.equal 'ldap' it 'should set uuid', -> expect(@sut.uuid).to.equal '1234' it 'should set token', -> expect(@sut.token).to.equal 'tok3n' it 'should set server', -> expect(@sut.server).to.equal 'google.co' it 'should set port', -> expect(@sut.port).to.equal 555 describe 'with other options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'ftp' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ftp://halo:400' describe 'with websocket protocol options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'websocket' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://halo:400' describe 'without a protocol on a specific port', -> beforeEach -> @sut = new MeshbluHttp server: 'localhost' port: 3000 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://localhost:3000' describe '->device', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.device 'the-uuuuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/the-uuuuid' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe '->devices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, null, foo: 'bar' @sut.devices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe '->generateAndStoreToken', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {foo: 'bar'} @sut.generateAndStoreToken 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error(), statusCode: 201 @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {error: 'something wrong'} @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a bad error code is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 400, "Device not found" @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Device not found" describe '->mydevices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.mydevices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error(), {statusCode: 404} @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, error: 'something wrong' @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, "Something went wrong" @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Something went wrong" describe '->message', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a message', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message devices: 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: {} it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {baconFat: true, lasers: false}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-baconFat': true 'x-meshblu-lasers': false describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {forwardedFor: ['some-real-device']}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-forwardedFor': '["some-real-device"]' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, {statusCode: 500}, error: 'something wrong' @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe '->register', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 201, null @sut.register {uuid: 'howdy', token: 'sweet'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.post on the device', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' describe 'with an invalid device', -> beforeEach (done) -> @request.post = sinon.stub().yields new Error('unable to register device'), statusCode: 500, null @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to register device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.post = sinon.stub().yields null, {statusCode: 200}, error: new Error('body error') @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error statusCode', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 500, 'plain body error' @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'plain body error' describe '->resetToken', -> beforeEach -> @request = post: sinon.stub() @sut = new MeshbluHttp {}, request: @request describe 'when called with a uuid', -> beforeEach -> @sut.resetToken 'some-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-uuid/token' describe 'when called with a different-uuid', -> beforeEach -> @sut.resetToken 'some-other-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-other-uuid/token' describe 'when request yields a new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-uuid', token: 'my-new-token' @sut.resetToken 'the-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-uuid', token: 'my-new-token' describe 'when request yields a different new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-other-uuid', token: 'my-other-new-token' @sut.resetToken 'the-other-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-other-uuid', token: 'my-other-new-token' describe 'when request yields a 401 response code', -> beforeEach (done) -> @request.post.yields null, {statusCode: 401}, error: 'unauthorized' @sut.resetToken 'uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'unauthorized' describe 'when request yields an error', -> beforeEach (done) -> @request.post.yields new Error('oh snap'), null @sut.resetToken 'the-other-uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'oh snap' describe '->revokeToken', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, null @sut.revokeToken 'uuid', 'taken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens/taken' it 'should not have an error', -> expect(@error).to.not.exist describe 'when an error happens', -> beforeEach (done) -> @request.del.yields new Error(), {} @sut.revokeToken 'invalid-uuid', 'tekken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tekken' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, {error: 'something wrong'} @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error statusCode is returned', -> beforeEach (done) -> @request.del.yields null, {statusCode: 400}, 'something wrong' @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error.message).to.deep.equal 'something wrong' describe '->setPrivateKey', -> beforeEach -> @nodeRSA = {} @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @sut.setPrivateKey 'data' it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should set', -> expect(@sut.privateKey).to.exist describe '->generateKeyPair', -> beforeEach -> @nodeRSA = exportKey: sinon.stub().returns '' generateKeyPair: sinon.spy() @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @result = @sut.generateKeyPair() it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should get a privateKey', -> expect(@result.privateKey).to.exist it 'should get a publicKey', -> expect(@result.publicKey).to.exist describe '->sign', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = sign: sinon.stub().returns 'abcd' it 'should sign', -> expect(@sut.sign('1234')).to.equal 'abcd' describe '->unregister', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 200}, null @sut.unregister {uuid: 'howdy', token: 'sweet'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.del on the device', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.del = sinon.stub().yields new Error('unable to delete device'), {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to delete device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, error: new Error('body error') @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'Device not found' describe '->update', -> beforeEach -> @request = {} @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with a uuid, params, and metadata', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, {'wears-hats': 'sometimes'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' expect(@request.patch.getCall(0).args[1].headers).to.deep.equal 'x-meshblu-wears-hats': 'sometimes' describe 'with an invalid device', -> beforeEach (done) -> @request.patch = sinon.stub().yields new Error('unable to update device'), null, null @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->updateDangerously', -> beforeEach -> @request = put: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.put = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.updateDangerously 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.put on the device', -> expect(@request.put).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.put = sinon.stub().yields new Error('unable to update device'), null, null @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.put = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->verify', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = verify: sinon.stub().returns true it 'should sign', -> expect(@sut.verify('1234', 'bbb')).to.be.true describe '->whoami', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe '->publicKey', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe '->createSubscription', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, null options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'broadcast' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/broadcast' expect(@request.post).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'received' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/received' expect(@request.post).to.have.been.calledWith url describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'nvm' @sut.createSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe '->deleteSubscription', -> beforeEach -> @request = delete: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'facebook' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/facebook' expect(@request.delete).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'twitter' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/twitter' expect(@request.delete).to.have.been.calledWith url it 'should not yield an error', -> expect(@error).to.not.exist describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe 'when something went wrong, but who knows what?', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 472}, null options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'Unknown Error Occurred'
30280
MeshbluHttp = require '../src/meshblu-http' describe 'MeshbluHttp', -> describe '->constructor', -> describe 'default', -> beforeEach -> @sut = new MeshbluHttp it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'https://meshblu.octoblu.com:443' describe 'with options', -> beforeEach -> @sut = new MeshbluHttp uuid: '1234' token: '<PASSWORD>' server: 'google.co' port: 555 protocol: 'ldap' it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ldap://google.co:555' it 'should set the protocol', -> expect(@sut.protocol).to.equal 'ldap' it 'should set uuid', -> expect(@sut.uuid).to.equal '1234' it 'should set token', -> expect(@sut.token).to.equal '<PASSWORD>' it 'should set server', -> expect(@sut.server).to.equal 'google.co' it 'should set port', -> expect(@sut.port).to.equal 555 describe 'with other options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'ftp' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ftp://halo:400' describe 'with websocket protocol options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'websocket' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://halo:400' describe 'without a protocol on a specific port', -> beforeEach -> @sut = new MeshbluHttp server: 'localhost' port: 3000 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://localhost:3000' describe '->device', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.device 'the-uuuuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/the-uuuuid' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe '->devices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, null, foo: 'bar' @sut.devices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe '->generateAndStoreToken', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {foo: 'bar'} @sut.generateAndStoreToken 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error(), statusCode: 201 @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {error: 'something wrong'} @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a bad error code is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 400, "Device not found" @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Device not found" describe '->mydevices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.mydevices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error(), {statusCode: 404} @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, error: 'something wrong' @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, "Something went wrong" @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Something went wrong" describe '->message', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a message', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message devices: 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: {} it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {baconFat: true, lasers: false}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-baconFat': true 'x-meshblu-lasers': false describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {forwardedFor: ['some-real-device']}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-forwardedFor': '["some-real-device"]' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, {statusCode: 500}, error: 'something wrong' @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe '->register', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 201, null @sut.register {uuid: 'howdy', token: '<KEY>'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.post on the device', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' describe 'with an invalid device', -> beforeEach (done) -> @request.post = sinon.stub().yields new Error('unable to register device'), statusCode: 500, null @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to register device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.post = sinon.stub().yields null, {statusCode: 200}, error: new Error('body error') @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error statusCode', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 500, 'plain body error' @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'plain body error' describe '->resetToken', -> beforeEach -> @request = post: sinon.stub() @sut = new MeshbluHttp {}, request: @request describe 'when called with a uuid', -> beforeEach -> @sut.resetToken 'some-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-uuid/token' describe 'when called with a different-uuid', -> beforeEach -> @sut.resetToken 'some-other-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-other-uuid/token' describe 'when request yields a new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-uuid', token: 'my-new-token' @sut.resetToken 'the-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-uuid', token: 'my-new-token' describe 'when request yields a different new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-other-uuid', token: 'my-other-new-token' @sut.resetToken 'the-other-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-other-uuid', token: 'my-other-new-token' describe 'when request yields a 401 response code', -> beforeEach (done) -> @request.post.yields null, {statusCode: 401}, error: 'unauthorized' @sut.resetToken 'uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'unauthorized' describe 'when request yields an error', -> beforeEach (done) -> @request.post.yields new Error('oh snap'), null @sut.resetToken 'the-other-uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'oh snap' describe '->revokeToken', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, null @sut.revokeToken 'uuid', 'taken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens/taken' it 'should not have an error', -> expect(@error).to.not.exist describe 'when an error happens', -> beforeEach (done) -> @request.del.yields new Error(), {} @sut.revokeToken 'invalid-uuid', 'tekken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tekken' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, {error: 'something wrong'} @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error statusCode is returned', -> beforeEach (done) -> @request.del.yields null, {statusCode: 400}, 'something wrong' @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error.message).to.deep.equal 'something wrong' describe '->setPrivateKey', -> beforeEach -> @nodeRSA = {} @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @sut.setPrivateKey 'data' it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should set', -> expect(@sut.privateKey).to.exist describe '->generateKeyPair', -> beforeEach -> @nodeRSA = exportKey: sinon.stub().returns '' generateKeyPair: sinon.spy() @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @result = @sut.generateKeyPair() it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should get a privateKey', -> expect(@result.privateKey).to.exist it 'should get a publicKey', -> expect(@result.publicKey).to.exist describe '->sign', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = sign: sinon.stub().returns 'abcd' it 'should sign', -> expect(@sut.sign('1234')).to.equal 'abcd' describe '->unregister', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 200}, null @sut.unregister {uuid: 'howdy', token: 'sweet'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.del on the device', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.del = sinon.stub().yields new Error('unable to delete device'), {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to delete device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, error: new Error('body error') @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'Device not found' describe '->update', -> beforeEach -> @request = {} @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with a uuid, params, and metadata', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, {'wears-hats': 'sometimes'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' expect(@request.patch.getCall(0).args[1].headers).to.deep.equal 'x-meshblu-wears-hats': 'sometimes' describe 'with an invalid device', -> beforeEach (done) -> @request.patch = sinon.stub().yields new Error('unable to update device'), null, null @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->updateDangerously', -> beforeEach -> @request = put: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.put = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.updateDangerously 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.put on the device', -> expect(@request.put).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.put = sinon.stub().yields new Error('unable to update device'), null, null @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.put = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->verify', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = verify: sinon.stub().returns true it 'should sign', -> expect(@sut.verify('1234', 'bbb')).to.be.true describe '->whoami', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe '->publicKey', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe '->createSubscription', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, null options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'broadcast' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/broadcast' expect(@request.post).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'received' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/received' expect(@request.post).to.have.been.calledWith url describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'nvm' @sut.createSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe '->deleteSubscription', -> beforeEach -> @request = delete: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'facebook' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/facebook' expect(@request.delete).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'twitter' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/twitter' expect(@request.delete).to.have.been.calledWith url it 'should not yield an error', -> expect(@error).to.not.exist describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe 'when something went wrong, but who knows what?', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 472}, null options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'Unknown Error Occurred'
true
MeshbluHttp = require '../src/meshblu-http' describe 'MeshbluHttp', -> describe '->constructor', -> describe 'default', -> beforeEach -> @sut = new MeshbluHttp it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'https://meshblu.octoblu.com:443' describe 'with options', -> beforeEach -> @sut = new MeshbluHttp uuid: '1234' token: 'PI:PASSWORD:<PASSWORD>END_PI' server: 'google.co' port: 555 protocol: 'ldap' it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ldap://google.co:555' it 'should set the protocol', -> expect(@sut.protocol).to.equal 'ldap' it 'should set uuid', -> expect(@sut.uuid).to.equal '1234' it 'should set token', -> expect(@sut.token).to.equal 'PI:PASSWORD:<PASSWORD>END_PI' it 'should set server', -> expect(@sut.server).to.equal 'google.co' it 'should set port', -> expect(@sut.port).to.equal 555 describe 'with other options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'ftp' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'ftp://halo:400' describe 'with websocket protocol options', -> beforeEach -> @sut = new MeshbluHttp protocol: 'websocket' server: 'halo' port: 400 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://halo:400' describe 'without a protocol on a specific port', -> beforeEach -> @sut = new MeshbluHttp server: 'localhost' port: 3000 it 'should set urlBase', -> expect(@sut.urlBase).to.equal 'http://localhost:3000' describe '->device', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.device 'the-uuuuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/the-uuuuid' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.device 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/invalid-uuid' it 'should callback with an error', -> expect(@error).to.exist describe '->devices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, null, foo: 'bar' @sut.devices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.devices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' it 'should callback with an error', -> expect(@error).to.exist describe '->generateAndStoreToken', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {foo: 'bar'} @sut.generateAndStoreToken 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error(), statusCode: 201 @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 201, {error: 'something wrong'} @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error).to.exist describe 'when a bad error code is returned', -> beforeEach (done) -> @request.post.yields null, statusCode: 400, "Device not found" @sut.generateAndStoreToken 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Device not found" describe '->mydevices', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid query', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.mydevices type: 'octoblu:test', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices', qs: type: 'octoblu:test' json: true it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error(), {statusCode: 404} @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, error: 'something wrong' @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 404}, "Something went wrong" @sut.mydevices 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/mydevices' it 'should callback with an error', -> expect(@error.message).to.deep.equal "Something went wrong" describe '->message', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a message', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message devices: 'uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: {} it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {baconFat: true, lasers: false}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-baconFat': true 'x-meshblu-lasers': false describe 'with a message with metadata', -> beforeEach (done) -> @request.post.yields null, null, foo: 'bar' @sut.message {devices: 'uuid'}, {forwardedFor: ['some-real-device']}, (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages', json: devices: 'uuid' headers: 'x-meshblu-forwardedFor': '["some-real-device"]' describe 'when an error happens', -> beforeEach (done) -> @request.post.yields new Error @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.post.yields null, {statusCode: 500}, error: 'something wrong' @sut.message test: 'invalid-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/messages' it 'should callback with an error', -> expect(@error).to.exist describe '->register', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 201, null @sut.register {uuid: 'howdy', token: 'PI:KEY:<KEY>END_PI'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.post on the device', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices' describe 'with an invalid device', -> beforeEach (done) -> @request.post = sinon.stub().yields new Error('unable to register device'), statusCode: 500, null @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to register device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.post = sinon.stub().yields null, {statusCode: 200}, error: new Error('body error') @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error statusCode', -> beforeEach (done) -> @request.post = sinon.stub().yields null, statusCode: 500, 'plain body error' @sut.register {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'plain body error' describe '->resetToken', -> beforeEach -> @request = post: sinon.stub() @sut = new MeshbluHttp {}, request: @request describe 'when called with a uuid', -> beforeEach -> @sut.resetToken 'some-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-uuid/token' describe 'when called with a different-uuid', -> beforeEach -> @sut.resetToken 'some-other-uuid' it 'should call post on request', -> expect(@request.post).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/some-other-uuid/token' describe 'when request yields a new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-uuid', token: 'my-new-token' @sut.resetToken 'the-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-uuid', token: 'my-new-token' describe 'when request yields a different new token', -> beforeEach (done) -> @request.post.yields null, {statusCode: 201}, uuid: 'the-other-uuid', token: 'my-other-new-token' @sut.resetToken 'the-other-uuid', (error, @result) => done() it 'should call the callback with the uuid and new token', -> expect(@result).to.deep.equal uuid: 'the-other-uuid', token: 'my-other-new-token' describe 'when request yields a 401 response code', -> beforeEach (done) -> @request.post.yields null, {statusCode: 401}, error: 'unauthorized' @sut.resetToken 'uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'unauthorized' describe 'when request yields an error', -> beforeEach (done) -> @request.post.yields new Error('oh snap'), null @sut.resetToken 'the-other-uuid', (@error) => done() it 'should call the callback with the error', -> expect(@error.message).to.equal 'oh snap' describe '->revokeToken', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a valid uuid', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, null @sut.revokeToken 'uuid', 'taken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/uuid/tokens/taken' it 'should not have an error', -> expect(@error).to.not.exist describe 'when an error happens', -> beforeEach (done) -> @request.del.yields new Error(), {} @sut.revokeToken 'invalid-uuid', 'tekken', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tekken' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.del.yields null, statusCode: 204, {error: 'something wrong'} @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error statusCode is returned', -> beforeEach (done) -> @request.del.yields null, {statusCode: 400}, 'something wrong' @sut.revokeToken 'invalid-uuid', 'tkoen', (@error, @body) => done() it 'should call del', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/invalid-uuid/tokens/tkoen' it 'should callback with an error', -> expect(@error.message).to.deep.equal 'something wrong' describe '->setPrivateKey', -> beforeEach -> @nodeRSA = {} @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @sut.setPrivateKey 'data' it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should set', -> expect(@sut.privateKey).to.exist describe '->generateKeyPair', -> beforeEach -> @nodeRSA = exportKey: sinon.stub().returns '' generateKeyPair: sinon.spy() @NodeRSA = sinon.spy => @nodeRSA @sut = new MeshbluHttp {}, NodeRSA: @NodeRSA @result = @sut.generateKeyPair() it 'should new NodeRSA', -> expect(@NodeRSA).to.have.been.calledWithNew it 'should get a privateKey', -> expect(@result.privateKey).to.exist it 'should get a publicKey', -> expect(@result.publicKey).to.exist describe '->sign', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = sign: sinon.stub().returns 'abcd' it 'should sign', -> expect(@sut.sign('1234')).to.equal 'abcd' describe '->unregister', -> beforeEach -> @request = del: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'with a device', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 200}, null @sut.unregister {uuid: 'howdy', token: 'sweet'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.del on the device', -> expect(@request.del).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.del = sinon.stub().yields new Error('unable to delete device'), {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to delete device' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, error: new Error('body error') @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'body error' describe 'when request returns an error in the body', -> beforeEach (done) -> @request.del = sinon.stub().yields null, {statusCode: 404}, "Device not found" @sut.unregister {uuid: 'NOPE', token: 'NO'}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'Device not found' describe '->update', -> beforeEach -> @request = {} @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with a uuid, params, and metadata', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.update 'howdy', {sam: 'I am'}, {'wears-hats': 'sometimes'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.patch on the device', -> expect(@request.patch).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' expect(@request.patch.getCall(0).args[1].headers).to.deep.equal 'x-meshblu-wears-hats': 'sometimes' describe 'with an invalid device', -> beforeEach (done) -> @request.patch = sinon.stub().yields new Error('unable to update device'), null, null @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.patch = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.update 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->updateDangerously', -> beforeEach -> @request = put: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {uuid: 'uuid', token: 'token'}, @dependencies describe 'with a uuid and params', -> beforeEach (done) -> @request.put = sinon.stub().yields null, statusCode: 204, uuid: 'howdy' @sut.updateDangerously 'howdy', {sam: 'I am'}, (@error) => done() it 'should not have an error', -> expect(@error).to.not.exist it 'should call request.put on the device', -> expect(@request.put).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/devices/howdy' describe 'with an invalid device', -> beforeEach (done) -> @request.put = sinon.stub().yields new Error('unable to update device'), null, null @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error.message).to.equal 'unable to update device' describe 'when request returns an error in the body with a statusCode', -> beforeEach (done) -> @request.put = sinon.stub().yields null, {statusCode: 422}, error: 'body error' @sut.updateDangerously 'NOPE', {}, (@error) => done() it 'should have an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.equal 'body error' describe '->verify', -> beforeEach -> @sut = new MeshbluHttp {} @sut.privateKey = verify: sinon.stub().returns true it 'should sign', -> expect(@sut.verify('1234', 'bbb')).to.be.true describe '->whoami', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.whoami (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/v2/whoami' it 'should callback with an error', -> expect(@error).to.exist describe '->publicKey', -> beforeEach -> @request = get: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.get.yields null, {statusCode: 200}, foo: 'bar' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should call callback', -> expect(@body).to.deep.equal foo: 'bar' describe 'when an error happens', -> beforeEach (done) -> @request.get.yields new Error @dependencies = request: @request @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe 'when a meshblu error body is returned', -> beforeEach (done) -> @request.get.yields null, {statusCode: 500}, error: 'something wrong' @sut.publicKey 'my-uuid', (@error, @body) => done() it 'should call get', -> expect(@request.get).to.have.been.calledWith 'https://meshblu.octoblu.com:443/devices/my-uuid/publickey' it 'should callback with an error', -> expect(@error).to.exist describe '->createSubscription', -> beforeEach -> @request = post: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, null options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'broadcast' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/broadcast' expect(@request.post).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'received' @sut.createSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/received' expect(@request.post).to.have.been.calledWith url describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.post.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'nvm' @sut.createSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe '->deleteSubscription', -> beforeEach -> @request = delete: sinon.stub() @dependencies = request: @request @sut = new MeshbluHttp {}, @dependencies describe 'when given a valid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-uuid' emitterId: 'device-uuid' type: 'facebook' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-uuid/subscriptions/device-uuid/facebook' expect(@request.delete).to.have.been.calledWith url describe 'when given an invalid uuid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 204}, {} options = subscriberId: 'my-invalid-uuid' emitterId: 'device-uuid' type: 'twitter' @sut.deleteSubscription options, (@error, @body) => done() it 'should call post', -> url = 'https://meshblu.octoblu.com:443/v2/devices/my-invalid-uuid/subscriptions/device-uuid/twitter' expect(@request.delete).to.have.been.calledWith url it 'should not yield an error', -> expect(@error).to.not.exist describe 'when given an valid uuid that meshblu thinks is invalid', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 422}, {error: 'message'} options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'message' describe 'when something went wrong, but who knows what?', -> beforeEach (done) -> @request.delete.yields null, {statusCode: 472}, null options = subscriberId: 'my-other-uuid' emitterId: 'device-uuid' type: 'knull' @sut.deleteSubscription options, (@error, @body) => done() it 'should yield an error', -> expect(=> throw @error).to.throw 'Unknown Error Occurred'
[ { "context": " ->\n selectAll = [\n 'notes'\n 'active'\n 'firstName'\n 'lastName'\n 'company'\n 'position'\n ", "end": 149, "score": 0.9753308892250061, "start": 140, "tag": "NAME", "value": "firstName" }, { "context": "= [\n 'notes'\n 'active'\n 'first...
example/data/contact_data.coffee
jamesknelson/angular-deputy
1
mod = angular.module 'memamug.data.contact', [] mod.factory 'Contact', ["Deputy", (Deputy) -> selectAll = [ 'notes' 'active' 'firstName' 'lastName' 'company' 'position' 'birthday' 'source' cards: [ 'answer' 'active' question: ['question'] ] ] new Deputy 'Contact', readOnly: [ 'linkedinId' 'facebookId' ] compute: firstName: [cards: ['answer', question: ['question']], (cards) -> # TODO: think of another way to do this. This will probably be awfully # slow, but trying to keep two separate pieces of data in different # resources in sync with every change also blows. ] lastName: [ ] company: [ ] position: [ ] birthday: [ ] source: ['linkedinId', 'facebookId', (linkedinId, facebookId) -> ] references: [ { hasMany: 'photos', service: 'Photo', dependent: 'destroy' } { hasMany: 'cards', service: 'Card', dependent: 'destroy' } ] index: [ 'source' 'active' ['source', 'active'] ] endpoints: get: select: selectAll list: select: selectAll patch: true delete: true findBySource: true findByActive: true findBySourceAndActive: true ]
10407
mod = angular.module 'memamug.data.contact', [] mod.factory 'Contact', ["Deputy", (Deputy) -> selectAll = [ 'notes' 'active' '<NAME>' '<NAME>' 'company' 'position' 'birthday' 'source' cards: [ 'answer' 'active' question: ['question'] ] ] new Deputy 'Contact', readOnly: [ 'linkedinId' 'facebookId' ] compute: firstName: [cards: ['answer', question: ['question']], (cards) -> # TODO: think of another way to do this. This will probably be awfully # slow, but trying to keep two separate pieces of data in different # resources in sync with every change also blows. ] lastName: [ ] company: [ ] position: [ ] birthday: [ ] source: ['linkedinId', 'facebookId', (linkedinId, facebookId) -> ] references: [ { hasMany: 'photos', service: 'Photo', dependent: 'destroy' } { hasMany: 'cards', service: 'Card', dependent: 'destroy' } ] index: [ 'source' 'active' ['source', 'active'] ] endpoints: get: select: selectAll list: select: selectAll patch: true delete: true findBySource: true findByActive: true findBySourceAndActive: true ]
true
mod = angular.module 'memamug.data.contact', [] mod.factory 'Contact', ["Deputy", (Deputy) -> selectAll = [ 'notes' 'active' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'company' 'position' 'birthday' 'source' cards: [ 'answer' 'active' question: ['question'] ] ] new Deputy 'Contact', readOnly: [ 'linkedinId' 'facebookId' ] compute: firstName: [cards: ['answer', question: ['question']], (cards) -> # TODO: think of another way to do this. This will probably be awfully # slow, but trying to keep two separate pieces of data in different # resources in sync with every change also blows. ] lastName: [ ] company: [ ] position: [ ] birthday: [ ] source: ['linkedinId', 'facebookId', (linkedinId, facebookId) -> ] references: [ { hasMany: 'photos', service: 'Photo', dependent: 'destroy' } { hasMany: 'cards', service: 'Card', dependent: 'destroy' } ] index: [ 'source' 'active' ['source', 'active'] ] endpoints: get: select: selectAll list: select: selectAll patch: true delete: true findBySource: true findByActive: true findBySourceAndActive: true ]
[ { "context": "else 'https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo'\n\t\t@type = if @options.type then @options.type el", "end": 410, "score": 0.9997280836105347, "start": 370, "tag": "KEY", "value": "NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo" }, { ...
modules/HTTPRequest.coffee
sseira/Framer--HTTPRequest
0
# HTTPRequest wrapper class # accepts url, type, callback, content_type, response_type, body, & access_token # based on type, sends a GET or POST request # class HTTPRequest constructor: (@options={}) -> default_callback = (data) -> print data console.log data @url = if @options.url then @options.url else 'https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo' @type = if @options.type then @options.type else 'GET' @callback = if @options.callback then @options.callback else default_callback @content_type = if @options.content_type then @options.content_type else 'application/json' @response_type = if @options.response_type then @options.response_type else 'json' @body = if @options.body then JSON.stringify(@options.body) else null @access_token = if @options.access_token then @options.access_token else 'SUPER_SECRET_TOKEN' console.log(@content_type) r = new XMLHttpRequest r.open @type, @url, true r.responseType = @response_type if @access_token r.setRequestHeader('Authorization', 'Bearer ' + @access_token); r.setRequestHeader("Content-type", @content_type) callback = @callback r.onreadystatechange = -> if (r.readyState == XMLHttpRequest.DONE) if (r.status >= 200 && r.status <= 206) # Reference for status codes -> https://www.w3schools.com/tags/ref_httpmessages.asp data = r.response callback(data) else console.log "Error #{r.status}" callback({error: r, data: r.response}) r.send(@body) module.exports = HTTPRequest
1002
# HTTPRequest wrapper class # accepts url, type, callback, content_type, response_type, body, & access_token # based on type, sends a GET or POST request # class HTTPRequest constructor: (@options={}) -> default_callback = (data) -> print data console.log data @url = if @options.url then @options.url else 'https://api.nasa.gov/planetary/apod?api_key=<KEY>' @type = if @options.type then @options.type else 'GET' @callback = if @options.callback then @options.callback else default_callback @content_type = if @options.content_type then @options.content_type else 'application/json' @response_type = if @options.response_type then @options.response_type else 'json' @body = if @options.body then JSON.stringify(@options.body) else null @access_token = if @options.access_token then @options.access_token else '<PASSWORD>' console.log(@content_type) r = new XMLHttpRequest r.open @type, @url, true r.responseType = @response_type if @access_token r.setRequestHeader('Authorization', 'Bearer ' + @access_token); r.setRequestHeader("Content-type", @content_type) callback = @callback r.onreadystatechange = -> if (r.readyState == XMLHttpRequest.DONE) if (r.status >= 200 && r.status <= 206) # Reference for status codes -> https://www.w3schools.com/tags/ref_httpmessages.asp data = r.response callback(data) else console.log "Error #{r.status}" callback({error: r, data: r.response}) r.send(@body) module.exports = HTTPRequest
true
# HTTPRequest wrapper class # accepts url, type, callback, content_type, response_type, body, & access_token # based on type, sends a GET or POST request # class HTTPRequest constructor: (@options={}) -> default_callback = (data) -> print data console.log data @url = if @options.url then @options.url else 'https://api.nasa.gov/planetary/apod?api_key=PI:KEY:<KEY>END_PI' @type = if @options.type then @options.type else 'GET' @callback = if @options.callback then @options.callback else default_callback @content_type = if @options.content_type then @options.content_type else 'application/json' @response_type = if @options.response_type then @options.response_type else 'json' @body = if @options.body then JSON.stringify(@options.body) else null @access_token = if @options.access_token then @options.access_token else 'PI:PASSWORD:<PASSWORD>END_PI' console.log(@content_type) r = new XMLHttpRequest r.open @type, @url, true r.responseType = @response_type if @access_token r.setRequestHeader('Authorization', 'Bearer ' + @access_token); r.setRequestHeader("Content-type", @content_type) callback = @callback r.onreadystatechange = -> if (r.readyState == XMLHttpRequest.DONE) if (r.status >= 200 && r.status <= 206) # Reference for status codes -> https://www.w3schools.com/tags/ref_httpmessages.asp data = r.response callback(data) else console.log "Error #{r.status}" callback({error: r, data: r.response}) r.send(@body) module.exports = HTTPRequest
[ { "context": "confirmPassword', 'Passwords do not match').equals req.body.password\n \n errors = req.validationErro", "end": 2610, "score": 0.6305769681930542, "start": 2607, "tag": "PASSWORD", "value": "req" }, { "context": "ssword', 'Passwords do not match').equals req.body.p...
controllers/user.coffee
bedrockdata/stormchaser
1
_ = require 'lodash' async = require 'async' crypto = require 'crypto' nodemailer = require 'nodemailer' passport = require 'passport' User = require '../models/user' Stream = require '../models/stream' DataType = require '../models/data_type' class UserController constructor: (@api) -> getAll: (req, res) -> User.find({}).then (err, users) -> res.json arguments .catch (err) -> throw new Error err getStream: (req, res) -> res.json ok: true getStreams: (req, res) -> query = user: req.user.username Stream.find(query).then (streams) -> res.json streams getDataTypes: (req, res) -> query = user: req.user.username DataType.find(query).then (types) -> res.json types getUser: (req, res) -> res.json username: req.user?.username getGithubOrgs: (req, res) => if req.user.githubOrgs res.json req.user.githubOrgs else @api.userOrgs req.user, (orgs) -> query = _id: req.user._id update = $set: githubOrgs: orgs User.update query, update, {upsert: false}, (err, results) -> console.log "UPDATED", query, update, err, results res.json orgs ###* # POST /login # Sign in using email and password. ### postLogin: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password cannot be blank').notEmpty() errors = req.validationErrors() if errors req.flash 'errors', errors res.redirect('/login') else passport.authenticate 'local', (err, user, info) -> if err return next(err) if user req.logIn user, (err) -> if err next(err) else req.flash 'success', msg: 'Success! You are logged in.' res.redirect req.session.returnTo or '/' else req.flash 'errors', msg: info.message res.redirect('/login') ###* # GET /logout # Log out. ### logout: (req, res) -> req.logout() res.redirect '/' ###* # GET /signup # Signup page. ### getSignup: (req, res) -> if req.user res.redirect('/') else res.render 'account/signup', title: 'Create Account' ###* # POST /signup # Create a new local account. ### postSignup: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/signup') user = new User email: req.body.email password: req.body.password query = email: req.body.email User.findOne query, (err, existingUser) -> if existingUser req.flash 'errors', msg: 'Account with that email address already exists.' res.redirect '/signup' else user.save (err) -> if err return next err req.logIn user, (err) -> if err next err else res.redirect '/' ###* # GET /account # Profile page. ### getAccount: (req, res) -> res.render 'account/profile', title: 'Account Management' ###* # POST /account/profile # Update profile information. ### postUpdateProfile: (req, res, next) -> User.findById req.user.id, (err, user) -> if err return next(err) user.email = req.body.email or '' user.profile.name = req.body.name or '' user.profile.gender = req.body.gender or '' user.profile.website = req.body.website or '' user.profile.location = req.body.location or '' user.save (err) -> if err return next(err) req.flash 'success', msg: 'Profile information updated.' res.redirect '/account' ###* # POST /account/password # Update current password. ### postUpdatePassword: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/account') User.findById req.user.id, (err, user) -> if err return next(err) user.password = req.body.password user.save (err) -> if err return next(err) req.flash 'success', msg: 'Password has been changed.' res.redirect '/account' ###* # POST /account/delete # Delete user account. ### postDeleteAccount: (req, res, next) -> query = _id: req.user.id User.remove query, (err) -> if err return next(err) req.logout() req.flash 'info', msg: 'Your account has been deleted.' res.redirect '/' ###* # GET /account/unlink/:provider # Unlink OAuth provider. ### getOauthUnlink: (req, res, next) -> provider = req.params.provider User.findById req.user.id, (err, user) -> if err return next(err) user[provider] = undefined user.tokens = _.reject user.tokens, (token) -> token.kind == provider user.save (err) -> if err return next(err) req.flash 'info', msg: provider + ' account has been unlinked.' res.redirect '/account' ###* # GET /reset/:token # Reset Password page. ### getReset: (req, res) -> if req.isAuthenticated() return res.redirect('/') User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('/forgot') res.render 'account/reset', title: 'Password Reset' ###* # POST /reset/:token # Process the reset password request. ### postReset: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long.').len 4 req.assert('confirm', 'Passwords must match.').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('back') async.waterfall [ (done) -> User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('back') user.password = req.body.password user.resetPasswordToken = undefined user.resetPasswordExpires = undefined user.save (err) -> if err return next(err) req.logIn user, (err) -> done err, user (user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: secrets.sendgrid.password) mailOptions = to: user.email from: 'hackathon@starter.com' subject: 'Your Hackathon Starter password has been changed' text: 'Hello,\n\n' + 'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n' transporter.sendMail mailOptions, (err) -> req.flash 'success', msg: 'Success! Your password has been changed.' done err ], (err) -> if err return next(err) res.redirect '/' ###* # GET /forgot # Forgot Password page. ### getForgot: (req, res) -> if req.isAuthenticated() return res.redirect('/') res.render 'account/forgot', title: 'Forgot Password' ###* # POST /forgot # Create a random token, then the send user an email with a reset link. ### postForgot: (req, res, next) -> req.assert('email', 'Please enter a valid email address.').isEmail() errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/forgot') async.waterfall [ (done) -> crypto.randomBytes 16, (err, buf) -> token = buf.toString('hex') done err, token (token, done) -> User.findOne { email: req.body.email.toLowerCase() }, (err, user) -> if !user req.flash 'errors', msg: 'No account with that email address exists.' return res.redirect('/forgot') user.resetPasswordToken = token user.resetPasswordExpires = Date.now() + 3600000 # 1 hour user.save (err) -> done err, token, user (token, user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: secrets.sendgrid.password) mailOptions = to: user.email from: 'hackathon@starter.com' subject: 'Reset your password on Hackathon Starter' text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' + 'Please click on the following link, or paste this into your browser to complete the process:\n\n' + 'http://' + req.headers.host + '/reset/' + token + '\n\n' + 'If you did not request this, please ignore this email and your password will remain unchanged.\n' transporter.sendMail mailOptions, (err) -> req.flash 'info', msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' done err, 'done' ], (err) -> if err return next(err) res.redirect '/forgot' module.exports = UserController
161004
_ = require 'lodash' async = require 'async' crypto = require 'crypto' nodemailer = require 'nodemailer' passport = require 'passport' User = require '../models/user' Stream = require '../models/stream' DataType = require '../models/data_type' class UserController constructor: (@api) -> getAll: (req, res) -> User.find({}).then (err, users) -> res.json arguments .catch (err) -> throw new Error err getStream: (req, res) -> res.json ok: true getStreams: (req, res) -> query = user: req.user.username Stream.find(query).then (streams) -> res.json streams getDataTypes: (req, res) -> query = user: req.user.username DataType.find(query).then (types) -> res.json types getUser: (req, res) -> res.json username: req.user?.username getGithubOrgs: (req, res) => if req.user.githubOrgs res.json req.user.githubOrgs else @api.userOrgs req.user, (orgs) -> query = _id: req.user._id update = $set: githubOrgs: orgs User.update query, update, {upsert: false}, (err, results) -> console.log "UPDATED", query, update, err, results res.json orgs ###* # POST /login # Sign in using email and password. ### postLogin: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password cannot be blank').notEmpty() errors = req.validationErrors() if errors req.flash 'errors', errors res.redirect('/login') else passport.authenticate 'local', (err, user, info) -> if err return next(err) if user req.logIn user, (err) -> if err next(err) else req.flash 'success', msg: 'Success! You are logged in.' res.redirect req.session.returnTo or '/' else req.flash 'errors', msg: info.message res.redirect('/login') ###* # GET /logout # Log out. ### logout: (req, res) -> req.logout() res.redirect '/' ###* # GET /signup # Signup page. ### getSignup: (req, res) -> if req.user res.redirect('/') else res.render 'account/signup', title: 'Create Account' ###* # POST /signup # Create a new local account. ### postSignup: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals <PASSWORD>.body<PASSWORD>.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/signup') user = new User email: req.body.email password: <PASSWORD> query = email: req.body.email User.findOne query, (err, existingUser) -> if existingUser req.flash 'errors', msg: 'Account with that email address already exists.' res.redirect '/signup' else user.save (err) -> if err return next err req.logIn user, (err) -> if err next err else res.redirect '/' ###* # GET /account # Profile page. ### getAccount: (req, res) -> res.render 'account/profile', title: 'Account Management' ###* # POST /account/profile # Update profile information. ### postUpdateProfile: (req, res, next) -> User.findById req.user.id, (err, user) -> if err return next(err) user.email = req.body.email or '' user.profile.name = req.body.name or '' user.profile.gender = req.body.gender or '' user.profile.website = req.body.website or '' user.profile.location = req.body.location or '' user.save (err) -> if err return next(err) req.flash 'success', msg: 'Profile information updated.' res.redirect '/account' ###* # POST /account/password # Update current password. ### postUpdatePassword: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/account') User.findById req.user.id, (err, user) -> if err return next(err) user.password = <PASSWORD> user.save (err) -> if err return next(err) req.flash 'success', msg: 'Password has been changed.' res.redirect '/account' ###* # POST /account/delete # Delete user account. ### postDeleteAccount: (req, res, next) -> query = _id: req.user.id User.remove query, (err) -> if err return next(err) req.logout() req.flash 'info', msg: 'Your account has been deleted.' res.redirect '/' ###* # GET /account/unlink/:provider # Unlink OAuth provider. ### getOauthUnlink: (req, res, next) -> provider = req.params.provider User.findById req.user.id, (err, user) -> if err return next(err) user[provider] = undefined user.tokens = _.reject user.tokens, (token) -> token.kind == provider user.save (err) -> if err return next(err) req.flash 'info', msg: provider + ' account has been unlinked.' res.redirect '/account' ###* # GET /reset/:token # Reset Password page. ### getReset: (req, res) -> if req.isAuthenticated() return res.redirect('/') User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('/forgot') res.render 'account/reset', title: 'Password Reset' ###* # POST /reset/:token # Process the reset password request. ### postReset: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long.').len 4 req.assert('confirm', 'Passwords must match.').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('back') async.waterfall [ (done) -> User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('back') user.password = <PASSWORD> user.resetPasswordToken = <PASSWORD> user.resetPasswordExpires = <PASSWORD> user.save (err) -> if err return next(err) req.logIn user, (err) -> done err, user (user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: <PASSWORD>) mailOptions = to: user.email from: '<EMAIL>' subject: 'Your Hackathon Starter password has been changed' text: 'Hello,\n\n' + 'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n' transporter.sendMail mailOptions, (err) -> req.flash 'success', msg: 'Success! Your password has been changed.' done err ], (err) -> if err return next(err) res.redirect '/' ###* # GET /forgot # Forgot Password page. ### getForgot: (req, res) -> if req.isAuthenticated() return res.redirect('/') res.render 'account/forgot', title: 'Forgot Password' ###* # POST /forgot # Create a random token, then the send user an email with a reset link. ### postForgot: (req, res, next) -> req.assert('email', 'Please enter a valid email address.').isEmail() errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/forgot') async.waterfall [ (done) -> crypto.randomBytes 16, (err, buf) -> token = buf.toString('hex') done err, token (token, done) -> User.findOne { email: req.body.email.toLowerCase() }, (err, user) -> if !user req.flash 'errors', msg: 'No account with that email address exists.' return res.redirect('/forgot') user.resetPasswordToken = <PASSWORD> user.resetPasswordExpires = Date.now() + 3600000 # 1 hour user.save (err) -> done err, token, user (token, user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: <PASSWORD>) mailOptions = to: user.email from: '<EMAIL>' subject: 'Reset your password on Hackathon Starter' text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' + 'Please click on the following link, or paste this into your browser to complete the process:\n\n' + 'http://' + req.headers.host + '/reset/' + token + '\n\n' + 'If you did not request this, please ignore this email and your password will remain unchanged.\n' transporter.sendMail mailOptions, (err) -> req.flash 'info', msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' done err, 'done' ], (err) -> if err return next(err) res.redirect '/forgot' module.exports = UserController
true
_ = require 'lodash' async = require 'async' crypto = require 'crypto' nodemailer = require 'nodemailer' passport = require 'passport' User = require '../models/user' Stream = require '../models/stream' DataType = require '../models/data_type' class UserController constructor: (@api) -> getAll: (req, res) -> User.find({}).then (err, users) -> res.json arguments .catch (err) -> throw new Error err getStream: (req, res) -> res.json ok: true getStreams: (req, res) -> query = user: req.user.username Stream.find(query).then (streams) -> res.json streams getDataTypes: (req, res) -> query = user: req.user.username DataType.find(query).then (types) -> res.json types getUser: (req, res) -> res.json username: req.user?.username getGithubOrgs: (req, res) => if req.user.githubOrgs res.json req.user.githubOrgs else @api.userOrgs req.user, (orgs) -> query = _id: req.user._id update = $set: githubOrgs: orgs User.update query, update, {upsert: false}, (err, results) -> console.log "UPDATED", query, update, err, results res.json orgs ###* # POST /login # Sign in using email and password. ### postLogin: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password cannot be blank').notEmpty() errors = req.validationErrors() if errors req.flash 'errors', errors res.redirect('/login') else passport.authenticate 'local', (err, user, info) -> if err return next(err) if user req.logIn user, (err) -> if err next(err) else req.flash 'success', msg: 'Success! You are logged in.' res.redirect req.session.returnTo or '/' else req.flash 'errors', msg: info.message res.redirect('/login') ###* # GET /logout # Log out. ### logout: (req, res) -> req.logout() res.redirect '/' ###* # GET /signup # Signup page. ### getSignup: (req, res) -> if req.user res.redirect('/') else res.render 'account/signup', title: 'Create Account' ###* # POST /signup # Create a new local account. ### postSignup: (req, res, next) -> req.assert('email', 'Email is not valid').isEmail() req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals PI:PASSWORD:<PASSWORD>END_PI.bodyPI:PASSWORD:<PASSWORD>END_PI.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/signup') user = new User email: req.body.email password: PI:PASSWORD:<PASSWORD>END_PI query = email: req.body.email User.findOne query, (err, existingUser) -> if existingUser req.flash 'errors', msg: 'Account with that email address already exists.' res.redirect '/signup' else user.save (err) -> if err return next err req.logIn user, (err) -> if err next err else res.redirect '/' ###* # GET /account # Profile page. ### getAccount: (req, res) -> res.render 'account/profile', title: 'Account Management' ###* # POST /account/profile # Update profile information. ### postUpdateProfile: (req, res, next) -> User.findById req.user.id, (err, user) -> if err return next(err) user.email = req.body.email or '' user.profile.name = req.body.name or '' user.profile.gender = req.body.gender or '' user.profile.website = req.body.website or '' user.profile.location = req.body.location or '' user.save (err) -> if err return next(err) req.flash 'success', msg: 'Profile information updated.' res.redirect '/account' ###* # POST /account/password # Update current password. ### postUpdatePassword: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long').len 4 req.assert('confirmPassword', 'Passwords do not match').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/account') User.findById req.user.id, (err, user) -> if err return next(err) user.password = PI:PASSWORD:<PASSWORD>END_PI user.save (err) -> if err return next(err) req.flash 'success', msg: 'Password has been changed.' res.redirect '/account' ###* # POST /account/delete # Delete user account. ### postDeleteAccount: (req, res, next) -> query = _id: req.user.id User.remove query, (err) -> if err return next(err) req.logout() req.flash 'info', msg: 'Your account has been deleted.' res.redirect '/' ###* # GET /account/unlink/:provider # Unlink OAuth provider. ### getOauthUnlink: (req, res, next) -> provider = req.params.provider User.findById req.user.id, (err, user) -> if err return next(err) user[provider] = undefined user.tokens = _.reject user.tokens, (token) -> token.kind == provider user.save (err) -> if err return next(err) req.flash 'info', msg: provider + ' account has been unlinked.' res.redirect '/account' ###* # GET /reset/:token # Reset Password page. ### getReset: (req, res) -> if req.isAuthenticated() return res.redirect('/') User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('/forgot') res.render 'account/reset', title: 'Password Reset' ###* # POST /reset/:token # Process the reset password request. ### postReset: (req, res, next) -> req.assert('password', 'Password must be at least 4 characters long.').len 4 req.assert('confirm', 'Passwords must match.').equals req.body.password errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('back') async.waterfall [ (done) -> User.findOne(resetPasswordToken: req.params.token).where('resetPasswordExpires').gt(Date.now()).exec (err, user) -> if !user req.flash 'errors', msg: 'Password reset token is invalid or has expired.' return res.redirect('back') user.password = PI:PASSWORD:<PASSWORD>END_PI user.resetPasswordToken = PI:PASSWORD:<PASSWORD>END_PI user.resetPasswordExpires = PI:PASSWORD:<PASSWORD>END_PI user.save (err) -> if err return next(err) req.logIn user, (err) -> done err, user (user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: PI:PASSWORD:<PASSWORD>END_PI) mailOptions = to: user.email from: 'PI:EMAIL:<EMAIL>END_PI' subject: 'Your Hackathon Starter password has been changed' text: 'Hello,\n\n' + 'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n' transporter.sendMail mailOptions, (err) -> req.flash 'success', msg: 'Success! Your password has been changed.' done err ], (err) -> if err return next(err) res.redirect '/' ###* # GET /forgot # Forgot Password page. ### getForgot: (req, res) -> if req.isAuthenticated() return res.redirect('/') res.render 'account/forgot', title: 'Forgot Password' ###* # POST /forgot # Create a random token, then the send user an email with a reset link. ### postForgot: (req, res, next) -> req.assert('email', 'Please enter a valid email address.').isEmail() errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect('/forgot') async.waterfall [ (done) -> crypto.randomBytes 16, (err, buf) -> token = buf.toString('hex') done err, token (token, done) -> User.findOne { email: req.body.email.toLowerCase() }, (err, user) -> if !user req.flash 'errors', msg: 'No account with that email address exists.' return res.redirect('/forgot') user.resetPasswordToken = PI:PASSWORD:<PASSWORD>END_PI user.resetPasswordExpires = Date.now() + 3600000 # 1 hour user.save (err) -> done err, token, user (token, user, done) -> transporter = nodemailer.createTransport( service: 'SendGrid' auth: user: secrets.sendgrid.user pass: PI:PASSWORD:<PASSWORD>END_PI) mailOptions = to: user.email from: 'PI:EMAIL:<EMAIL>END_PI' subject: 'Reset your password on Hackathon Starter' text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' + 'Please click on the following link, or paste this into your browser to complete the process:\n\n' + 'http://' + req.headers.host + '/reset/' + token + '\n\n' + 'If you did not request this, please ignore this email and your password will remain unchanged.\n' transporter.sendMail mailOptions, (err) -> req.flash 'info', msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' done err, 'done' ], (err) -> if err return next(err) res.redirect '/forgot' module.exports = UserController
[ { "context": "/expanded state on desktops\n store_state_key: 'mmstate'\n disable_animation_on: ['small'] # Disable an", "end": 466, "score": 0.8187145590782166, "start": 459, "tag": "KEY", "value": "mmstate" }, { "context": " FastClick plugin\n # # (see https://github.com/ft...
Public/javascripts/sources/app.coffee
mollid/admin
0
# ------------------------------------------------------------------- # app.coffee # # Default app settings SETTINGS_DEFAULTS = is_mobile: false resize_delay: 400 # resize event delay (milliseconds) stored_values_prefix: 'pa_' # prefix for strored values in the localStorage and cookies main_menu: accordion: true animation_speed: 250 # milliseconds store_state: true # Remember collapsed/expanded state on desktops store_state_key: 'mmstate' disable_animation_on: ['small'] # Disable animation on specified screen sizes for the perfomance reason. Possible values: 'small', 'tablet', 'desktop' dropdown_close_delay: 300 # milliseconds detect_active: true, detect_active_predicate: (href, url) -> return (href is url) consts: COLORS: ['#71c73e', '#77b7c5', '#d54848', '#6c42e5', '#e8e64e', '#dd56e6', '#ecad3f', '#618b9d', '#b68b68', '#36a766', '#3156be', '#00b3ff', '#646464', '#a946e8', '#9d9d9d'] ### * @class PixelAdminApp ### PixelAdminApp = -> @init = [] # Initialization stack @plugins = {} # Plugins list @settings = {} # Settings @localStorageSupported = if typeof(window.Storage) isnt "undefined" then true else false @ ### * Start application. Method takes an array of initializers and a settings object(that overrides default settings). * * @param {Array} suffix * @param {Object} settings * @return this ### PixelAdminApp.prototype.start = (init=[], settings={}) -> window.onload = => $('html').addClass('pxajs') if init.length > 0 $.merge(@init, init) # Extend settings @settings = $.extend(true, {}, SETTINGS_DEFAULTS, settings || {}) # Detect device @settings.is_mobile = /iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()); # # If mobile than enable FastClick plugin # # (see https://github.com/ftlabs/fastclick) if @settings.is_mobile FastClick.attach(document.body) if FastClick # Run initializers $.proxy(initilizer, @)() for initilizer in @init $(window).trigger("pa.loaded") # Trigger resize event $(window).resize() @ ### * Add initializer to the stack. * * @param {Function} callback ### PixelAdminApp.prototype.addInitializer = (callback) -> @init.push(callback) ### * Initialize plugin and add it to the plugins list. * * @param {String} plugin_name * @param {Instance} plugin ### PixelAdminApp.prototype.initPlugin = (plugin_name, plugin) -> @plugins[plugin_name] = plugin plugin.init() if plugin.init ### * Save value in the localStorage/Cookies. * * @param {String} key * @param {String} value * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValue = (key, value, use_cookies=false) -> if @localStorageSupported and not use_cookies try window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Save key/value pairs in the localStorage/Cookies. * * @param {Object} pairs * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValues = (pairs, use_cookies=false) -> if @localStorageSupported and not use_cookies try for key, value of pairs window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 for key, value of pairs document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Get value from the localStorage/Cookies. * * @param {String} key * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValue = (key, use_cookies=false, deflt=null) -> if @localStorageSupported and not use_cookies try r = window.localStorage.getItem(@settings.stored_values_prefix + key) return (if r then r else deflt) catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') return v if k is (@settings.stored_values_prefix + key) return deflt ### * Get values from the localStorage/Cookies. * * @param {Array} keys * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValues = (keys, use_cookies=false, deflt=null) -> result = {} result[key] = deflt for key in keys if @localStorageSupported and not use_cookies try for key in keys r = window.localStorage.getItem(@settings.stored_values_prefix + key) result[key] = r if r return result catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') result[key] = v if k is (@settings.stored_values_prefix + key) result # Create application PixelAdminApp.Constructor = PixelAdminApp; window.PixelAdmin = new PixelAdminApp;
125175
# ------------------------------------------------------------------- # app.coffee # # Default app settings SETTINGS_DEFAULTS = is_mobile: false resize_delay: 400 # resize event delay (milliseconds) stored_values_prefix: 'pa_' # prefix for strored values in the localStorage and cookies main_menu: accordion: true animation_speed: 250 # milliseconds store_state: true # Remember collapsed/expanded state on desktops store_state_key: '<KEY>' disable_animation_on: ['small'] # Disable animation on specified screen sizes for the perfomance reason. Possible values: 'small', 'tablet', 'desktop' dropdown_close_delay: 300 # milliseconds detect_active: true, detect_active_predicate: (href, url) -> return (href is url) consts: COLORS: ['#71c73e', '#77b7c5', '#d54848', '#6c42e5', '#e8e64e', '#dd56e6', '#ecad3f', '#618b9d', '#b68b68', '#36a766', '#3156be', '#00b3ff', '#646464', '#a946e8', '#9d9d9d'] ### * @class PixelAdminApp ### PixelAdminApp = -> @init = [] # Initialization stack @plugins = {} # Plugins list @settings = {} # Settings @localStorageSupported = if typeof(window.Storage) isnt "undefined" then true else false @ ### * Start application. Method takes an array of initializers and a settings object(that overrides default settings). * * @param {Array} suffix * @param {Object} settings * @return this ### PixelAdminApp.prototype.start = (init=[], settings={}) -> window.onload = => $('html').addClass('pxajs') if init.length > 0 $.merge(@init, init) # Extend settings @settings = $.extend(true, {}, SETTINGS_DEFAULTS, settings || {}) # Detect device @settings.is_mobile = /iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()); # # If mobile than enable FastClick plugin # # (see https://github.com/ftlabs/fastclick) if @settings.is_mobile FastClick.attach(document.body) if FastClick # Run initializers $.proxy(initilizer, @)() for initilizer in @init $(window).trigger("pa.loaded") # Trigger resize event $(window).resize() @ ### * Add initializer to the stack. * * @param {Function} callback ### PixelAdminApp.prototype.addInitializer = (callback) -> @init.push(callback) ### * Initialize plugin and add it to the plugins list. * * @param {String} plugin_name * @param {Instance} plugin ### PixelAdminApp.prototype.initPlugin = (plugin_name, plugin) -> @plugins[plugin_name] = plugin plugin.init() if plugin.init ### * Save value in the localStorage/Cookies. * * @param {String} key * @param {String} value * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValue = (key, value, use_cookies=false) -> if @localStorageSupported and not use_cookies try window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Save key/value pairs in the localStorage/Cookies. * * @param {Object} pairs * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValues = (pairs, use_cookies=false) -> if @localStorageSupported and not use_cookies try for key, value of pairs window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 for key, value of pairs document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Get value from the localStorage/Cookies. * * @param {String} key * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValue = (key, use_cookies=false, deflt=null) -> if @localStorageSupported and not use_cookies try r = window.localStorage.getItem(@settings.stored_values_prefix + key) return (if r then r else deflt) catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') return v if k is (@settings.stored_values_prefix + key) return deflt ### * Get values from the localStorage/Cookies. * * @param {Array} keys * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValues = (keys, use_cookies=false, deflt=null) -> result = {} result[key] = deflt for key in keys if @localStorageSupported and not use_cookies try for key in keys r = window.localStorage.getItem(@settings.stored_values_prefix + key) result[key] = r if r return result catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') result[key] = v if k is (@settings.stored_values_prefix + key) result # Create application PixelAdminApp.Constructor = PixelAdminApp; window.PixelAdmin = new PixelAdminApp;
true
# ------------------------------------------------------------------- # app.coffee # # Default app settings SETTINGS_DEFAULTS = is_mobile: false resize_delay: 400 # resize event delay (milliseconds) stored_values_prefix: 'pa_' # prefix for strored values in the localStorage and cookies main_menu: accordion: true animation_speed: 250 # milliseconds store_state: true # Remember collapsed/expanded state on desktops store_state_key: 'PI:KEY:<KEY>END_PI' disable_animation_on: ['small'] # Disable animation on specified screen sizes for the perfomance reason. Possible values: 'small', 'tablet', 'desktop' dropdown_close_delay: 300 # milliseconds detect_active: true, detect_active_predicate: (href, url) -> return (href is url) consts: COLORS: ['#71c73e', '#77b7c5', '#d54848', '#6c42e5', '#e8e64e', '#dd56e6', '#ecad3f', '#618b9d', '#b68b68', '#36a766', '#3156be', '#00b3ff', '#646464', '#a946e8', '#9d9d9d'] ### * @class PixelAdminApp ### PixelAdminApp = -> @init = [] # Initialization stack @plugins = {} # Plugins list @settings = {} # Settings @localStorageSupported = if typeof(window.Storage) isnt "undefined" then true else false @ ### * Start application. Method takes an array of initializers and a settings object(that overrides default settings). * * @param {Array} suffix * @param {Object} settings * @return this ### PixelAdminApp.prototype.start = (init=[], settings={}) -> window.onload = => $('html').addClass('pxajs') if init.length > 0 $.merge(@init, init) # Extend settings @settings = $.extend(true, {}, SETTINGS_DEFAULTS, settings || {}) # Detect device @settings.is_mobile = /iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()); # # If mobile than enable FastClick plugin # # (see https://github.com/ftlabs/fastclick) if @settings.is_mobile FastClick.attach(document.body) if FastClick # Run initializers $.proxy(initilizer, @)() for initilizer in @init $(window).trigger("pa.loaded") # Trigger resize event $(window).resize() @ ### * Add initializer to the stack. * * @param {Function} callback ### PixelAdminApp.prototype.addInitializer = (callback) -> @init.push(callback) ### * Initialize plugin and add it to the plugins list. * * @param {String} plugin_name * @param {Instance} plugin ### PixelAdminApp.prototype.initPlugin = (plugin_name, plugin) -> @plugins[plugin_name] = plugin plugin.init() if plugin.init ### * Save value in the localStorage/Cookies. * * @param {String} key * @param {String} value * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValue = (key, value, use_cookies=false) -> if @localStorageSupported and not use_cookies try window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Save key/value pairs in the localStorage/Cookies. * * @param {Object} pairs * @param {Boolean} use_cookies ### PixelAdminApp.prototype.storeValues = (pairs, use_cookies=false) -> if @localStorageSupported and not use_cookies try for key, value of pairs window.localStorage.setItem(@settings.stored_values_prefix + key, value) return catch e 1 for key, value of pairs document.cookie = @settings.stored_values_prefix + key + '=' + escape(value) ### * Get value from the localStorage/Cookies. * * @param {String} key * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValue = (key, use_cookies=false, deflt=null) -> if @localStorageSupported and not use_cookies try r = window.localStorage.getItem(@settings.stored_values_prefix + key) return (if r then r else deflt) catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') return v if k is (@settings.stored_values_prefix + key) return deflt ### * Get values from the localStorage/Cookies. * * @param {Array} keys * @param {Boolean} use_cookies ### PixelAdminApp.prototype.getStoredValues = (keys, use_cookies=false, deflt=null) -> result = {} result[key] = deflt for key in keys if @localStorageSupported and not use_cookies try for key in keys r = window.localStorage.getItem(@settings.stored_values_prefix + key) result[key] = r if r return result catch e 1 cookies = document.cookie.split(';') for cookie in cookies pos = cookie.indexOf('=') k = cookie.substr(0, pos).replace(/^\s+|\s+$/g, '') v = cookie.substr(pos + 1).replace(/^\s+|\s+$/g, '') result[key] = v if k is (@settings.stored_values_prefix + key) result # Create application PixelAdminApp.Constructor = PixelAdminApp; window.PixelAdmin = new PixelAdminApp;
[ { "context": "#\n knockback.js 0.19.1\n Copyright (c) 2011-2014 Kevin Malakoff.\n License: MIT (http://www.opensource.org/licens", "end": 67, "score": 0.9998106360435486, "start": 53, "tag": "NAME", "value": "Kevin Malakoff" }, { "context": "ses/mit-license.php)\n Source: https:...
src/core/statistics.coffee
metacommunications/knockback
0
### knockback.js 0.19.1 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### {_} = kb = require './kb' # kb.Statistics is an optional components that is useful for measuring your application's performance. You can record all of the Backbone.Events that have triggered ko.observable subscription updates and the memory footprint (instance count-only) of your ViewModels and collection observables. # # kb.Statistics is not included in `knockback.js` nor `knockback-core.js` so you need to manually include it from the `lib` directory. # module.exports = class kb.Statistics constructor: -> @model_events_tracker = [] @registered_tracker = {} # Clear the tracked model events (but keep the registered objects intact) clear: -> @model_events_tracker = [] ############################### # Registered Events ############################### # Register a model event addModelEvent: (event) -> @model_events_tracker.push(event) # A debug helper to summarize the registered events in human-readable form modelEventsStatsString: -> stats_string = '' stats_string += "Total Count: #{@model_events_tracker.length}" event_groups = _.groupBy(@model_events_tracker, (test) -> return "event name: '#{test.name}', attribute name: '#{test.key}'") for key, value of event_groups stats_string += "\n #{key}, count: #{value.length}" return stats_string ############################### # Registered Observables and View Models ############################### # Register an object by key register: (key, obj) -> @registeredTracker(key).push(obj) # Unregister an object by key unregister: (key, obj) -> type_tracker = @registeredTracker(key) index = _.indexOf(type_tracker, obj) console?.log("kb.Statistics: failed to unregister type: #{key}") if index < 0 type_tracker.splice(index, 1) # @return [Integer] the number of registered objects by type registeredCount: (type) -> return @registeredTracker(type).length if type count = 0 count += type_tracker.length for type, type_tracker of @registered_tracker[type] return count # A debug helper to summarize the current registered objects by key # # @param [String] success_message a message to return if there are no registered objects # @return [String] a human readable string summarizing the currently registered objects or success_message registeredStatsString: (success_message) -> stats_string = '' for type, type_tracker of @registered_tracker continue unless type_tracker.length stats_string += '\n ' if written stats_string += "#{if type then type else 'No Name'}: #{type_tracker.length}" written = true return if stats_string then stats_string else success_message # @private registeredTracker: (key) -> return @registered_tracker[key] if @registered_tracker.hasOwnProperty(key) type_tracker = []; @registered_tracker[key] = type_tracker return type_tracker @eventsStats: (obj, key) -> stats = {count: 0} events = obj._events or obj._callbacks or {} for key in (if key then [key] else _.keys(events)) when node = events[key] if _.isArray(node) stats[key] = _.compact(node).length else stats[key] = 0; tail = node.tail stats[key]++ while ((node = node.next) isnt tail) stats.count += stats[key] return stats
22171
### knockback.js 0.19.1 Copyright (c) 2011-2014 <NAME>. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### {_} = kb = require './kb' # kb.Statistics is an optional components that is useful for measuring your application's performance. You can record all of the Backbone.Events that have triggered ko.observable subscription updates and the memory footprint (instance count-only) of your ViewModels and collection observables. # # kb.Statistics is not included in `knockback.js` nor `knockback-core.js` so you need to manually include it from the `lib` directory. # module.exports = class kb.Statistics constructor: -> @model_events_tracker = [] @registered_tracker = {} # Clear the tracked model events (but keep the registered objects intact) clear: -> @model_events_tracker = [] ############################### # Registered Events ############################### # Register a model event addModelEvent: (event) -> @model_events_tracker.push(event) # A debug helper to summarize the registered events in human-readable form modelEventsStatsString: -> stats_string = '' stats_string += "Total Count: #{@model_events_tracker.length}" event_groups = _.groupBy(@model_events_tracker, (test) -> return "event name: '#{test.name}', attribute name: '#{test.key}'") for key, value of event_groups stats_string += "\n #{key}, count: #{value.length}" return stats_string ############################### # Registered Observables and View Models ############################### # Register an object by key register: (key, obj) -> @registeredTracker(key).push(obj) # Unregister an object by key unregister: (key, obj) -> type_tracker = @registeredTracker(key) index = _.indexOf(type_tracker, obj) console?.log("kb.Statistics: failed to unregister type: #{key}") if index < 0 type_tracker.splice(index, 1) # @return [Integer] the number of registered objects by type registeredCount: (type) -> return @registeredTracker(type).length if type count = 0 count += type_tracker.length for type, type_tracker of @registered_tracker[type] return count # A debug helper to summarize the current registered objects by key # # @param [String] success_message a message to return if there are no registered objects # @return [String] a human readable string summarizing the currently registered objects or success_message registeredStatsString: (success_message) -> stats_string = '' for type, type_tracker of @registered_tracker continue unless type_tracker.length stats_string += '\n ' if written stats_string += "#{if type then type else 'No Name'}: #{type_tracker.length}" written = true return if stats_string then stats_string else success_message # @private registeredTracker: (key) -> return @registered_tracker[key] if @registered_tracker.hasOwnProperty(key) type_tracker = []; @registered_tracker[key] = type_tracker return type_tracker @eventsStats: (obj, key) -> stats = {count: 0} events = obj._events or obj._callbacks or {} for key in (if key then [key] else _.keys(events)) when node = events[key] if _.isArray(node) stats[key] = _.compact(node).length else stats[key] = 0; tail = node.tail stats[key]++ while ((node = node.next) isnt tail) stats.count += stats[key] return stats
true
### knockback.js 0.19.1 Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. ### {_} = kb = require './kb' # kb.Statistics is an optional components that is useful for measuring your application's performance. You can record all of the Backbone.Events that have triggered ko.observable subscription updates and the memory footprint (instance count-only) of your ViewModels and collection observables. # # kb.Statistics is not included in `knockback.js` nor `knockback-core.js` so you need to manually include it from the `lib` directory. # module.exports = class kb.Statistics constructor: -> @model_events_tracker = [] @registered_tracker = {} # Clear the tracked model events (but keep the registered objects intact) clear: -> @model_events_tracker = [] ############################### # Registered Events ############################### # Register a model event addModelEvent: (event) -> @model_events_tracker.push(event) # A debug helper to summarize the registered events in human-readable form modelEventsStatsString: -> stats_string = '' stats_string += "Total Count: #{@model_events_tracker.length}" event_groups = _.groupBy(@model_events_tracker, (test) -> return "event name: '#{test.name}', attribute name: '#{test.key}'") for key, value of event_groups stats_string += "\n #{key}, count: #{value.length}" return stats_string ############################### # Registered Observables and View Models ############################### # Register an object by key register: (key, obj) -> @registeredTracker(key).push(obj) # Unregister an object by key unregister: (key, obj) -> type_tracker = @registeredTracker(key) index = _.indexOf(type_tracker, obj) console?.log("kb.Statistics: failed to unregister type: #{key}") if index < 0 type_tracker.splice(index, 1) # @return [Integer] the number of registered objects by type registeredCount: (type) -> return @registeredTracker(type).length if type count = 0 count += type_tracker.length for type, type_tracker of @registered_tracker[type] return count # A debug helper to summarize the current registered objects by key # # @param [String] success_message a message to return if there are no registered objects # @return [String] a human readable string summarizing the currently registered objects or success_message registeredStatsString: (success_message) -> stats_string = '' for type, type_tracker of @registered_tracker continue unless type_tracker.length stats_string += '\n ' if written stats_string += "#{if type then type else 'No Name'}: #{type_tracker.length}" written = true return if stats_string then stats_string else success_message # @private registeredTracker: (key) -> return @registered_tracker[key] if @registered_tracker.hasOwnProperty(key) type_tracker = []; @registered_tracker[key] = type_tracker return type_tracker @eventsStats: (obj, key) -> stats = {count: 0} events = obj._events or obj._callbacks or {} for key in (if key then [key] else _.keys(events)) when node = events[key] if _.isArray(node) stats[key] = _.compact(node).length else stats[key] = 0; tail = node.tail stats[key]++ while ((node = node.next) isnt tail) stats.count += stats[key] return stats
[ { "context": "===================\n#\n# Colour Methods\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#=================================", "end": 115, "score": 0.9998763203620911, "start": 97, "tag": "NAME", "value": "Matthew Wagerfield" }, { "context": "\n#\n# Colour Methods\n#\n...
development/production/source/assets/scripts/coffee/core/Color.coffee
wagerfield/cinnamon
2
### #============================================================ # # Colour Methods # # @author Matthew Wagerfield @mwagerfield # #============================================================ ### class Color ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgb = (hex, range = 255) -> hex = hex.replace '#', '' r: (r = (parseInt hex.substring(0, 2), 16) / range) g: (g = (parseInt hex.substring(2, 4), 16) / range) b: (b = (parseInt hex.substring(4, 6), 16) / range) colors: [r, g, b] ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} alpha Opacity of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgba = (hex, alpha, range = 255) -> color = @rgb hex, range color.a = alpha color.colors.push alpha return color
53605
### #============================================================ # # Colour Methods # # @author <NAME> @mwagerfield # #============================================================ ### class Color ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgb = (hex, range = 255) -> hex = hex.replace '#', '' r: (r = (parseInt hex.substring(0, 2), 16) / range) g: (g = (parseInt hex.substring(2, 4), 16) / range) b: (b = (parseInt hex.substring(4, 6), 16) / range) colors: [r, g, b] ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} alpha Opacity of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgba = (hex, alpha, range = 255) -> color = @rgb hex, range color.a = alpha color.colors.push alpha return color
true
### #============================================================ # # Colour Methods # # @author PI:NAME:<NAME>END_PI @mwagerfield # #============================================================ ### class Color ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgb = (hex, range = 255) -> hex = hex.replace '#', '' r: (r = (parseInt hex.substring(0, 2), 16) / range) g: (g = (parseInt hex.substring(2, 4), 16) / range) b: (b = (parseInt hex.substring(4, 6), 16) / range) colors: [r, g, b] ### # Converts a hex string (). # @param {number} hex Hex value of the color. # @param {number} alpha Opacity of the color. # @param {number} range Range of the color. # @return {object} The Color. ### @rgba = (hex, alpha, range = 255) -> color = @rgb hex, range color.a = alpha color.colors.push alpha return color
[ { "context": ".inputs\n\n options =\n password : password.getValue()\n disable : yes\n\n @handleProcessOf2", "end": 2306, "score": 0.9163334369659424, "start": 2289, "tag": "PASSWORD", "value": "password.getValue" }, { "context": " key : @_a...
client/account/lib/accounttwofactorauth.coffee
ezgikaysi/koding
1
kd = require 'kd' whoami = require 'app/util/whoami' KDView = kd.View KDButtonView = kd.ButtonView module.exports = class AccountTwoFactorAuth extends KDView constructor: (options = {}, data) -> options.cssClass = kd.utils.curry \ 'AppModal--account tfauth', options.cssClass super options, data viewAppended: -> @buildInitialView() showError: (err) -> return unless err console.warn err new kd.NotificationView type : 'mini' title : err.message cssClass : 'error' return err buildInitialView: -> @destroySubViews() @addSubView loader = @getLoaderView() kd.singletons.mainController.ready => me = whoami() me.generate2FactorAuthKey (err, authInfo) => loader.hide() if err if err.name is 'ALREADY_INUSE' @addSubView @getEnabledView() return return @showError err { key, qrcode } = authInfo @_activeKey = key @addSubView @getInstructionsView() @addSubView @getQrCodeView qrcode @addSubView @getFormView() getEnabledView: -> @addSubView new kd.CustomHTMLView cssClass : 'enabled-intro' partial : " <div> 2-Factor Authentication is <green>active</green> for your account. <cite></cite> </div> #{@getLearnLink()} " @addSubView @disableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' button : type : 'submit' label : '&nbsp;' cssClass : 'Formline--half' itemClass : KDButtonView title : 'Disable 2-Factor Auth' style : 'solid medium disable-tf' callback : @bound 'handleDisableFormButton' handleDisableFormButton: -> { password } = @disableForm.inputs options = password : password.getValue() disable : yes @handleProcessOf2FactorAuth options, 'Successfully Disabled!' handleProcessOf2FactorAuth: (options, message) -> me = whoami() me.setup2FactorAuth options, (err) => return if @showError err new kd.NotificationView title : message type : 'mini' @buildInitialView() getFormView: -> @addSubView @enableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' tfcode : cssClass : 'Formline--half' placeholder : 'Enter the verification code' name : 'tfcode' label : 'Verification Code' buttons : Enable : type : 'submit' title : 'Enable 2-Factor Auth' style : 'solid green small enable-tf' callback : @bound 'handleEnableFormButton' handleEnableFormButton: -> { password, tfcode } = @enableForm.inputs options = key : @_activeKey password : password.getValue() verification : tfcode.getValue() @handleProcessOf2FactorAuth options, 'Successfully Enabled!' getQrCodeView: (url) -> view = new kd.CustomHTMLView cssClass : 'qrcode-view' view.addSubView imageView = new kd.CustomHTMLView tagName : 'img' attributes : { src : url } view.addSubView button = new kd.ButtonView iconOnly : yes icon : 'reload' loader : color : '#000000' size : width : 20 height : 20 callback : => me = whoami() me.generate2FactorAuthKey (err, authInfo) => @showError err if authInfo @_activeKey = authInfo.key imageView.setAttribute 'src', authInfo.qrcode kd.utils.defer button.bound 'hideLoader' return view getLoaderView: -> new kd.LoaderView cssClass : 'main-loader' showLoader : yes size : width : 25 height : 25 getLearnLink: -> " <a class='learn-link' href='https://koding.com/docs/2-factor-auth/' target=_blank> Learn more about 2-factor authentication.</a> " getInstructionsView: -> new kd.CustomHTMLView cssClass : 'instructions' partial : """ <div class='intro'> <cite></cite> Download and install the Google Authenticator app on your <a href='https://goo.gl/x01UdJ' target=_blank>iPhone</a> or <a href='https://goo.gl/Oe5t7l' target=_blank>Android</a> phone. Then follow the steps listed below to set up 2-factor authentication for your Koding account. <br /> #{@getLearnLink()} </div> <li>Open the Authenticator app on your phone. <li>Tap the “+" or “..." icon and then choose “Scan barcode" to add Koding. <li>Scan the code shown below using your phone's camera. <li>Enter the 6-digit verification code generated by the app in the space below and click the “Enable” button. """
23615
kd = require 'kd' whoami = require 'app/util/whoami' KDView = kd.View KDButtonView = kd.ButtonView module.exports = class AccountTwoFactorAuth extends KDView constructor: (options = {}, data) -> options.cssClass = kd.utils.curry \ 'AppModal--account tfauth', options.cssClass super options, data viewAppended: -> @buildInitialView() showError: (err) -> return unless err console.warn err new kd.NotificationView type : 'mini' title : err.message cssClass : 'error' return err buildInitialView: -> @destroySubViews() @addSubView loader = @getLoaderView() kd.singletons.mainController.ready => me = whoami() me.generate2FactorAuthKey (err, authInfo) => loader.hide() if err if err.name is 'ALREADY_INUSE' @addSubView @getEnabledView() return return @showError err { key, qrcode } = authInfo @_activeKey = key @addSubView @getInstructionsView() @addSubView @getQrCodeView qrcode @addSubView @getFormView() getEnabledView: -> @addSubView new kd.CustomHTMLView cssClass : 'enabled-intro' partial : " <div> 2-Factor Authentication is <green>active</green> for your account. <cite></cite> </div> #{@getLearnLink()} " @addSubView @disableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' button : type : 'submit' label : '&nbsp;' cssClass : 'Formline--half' itemClass : KDButtonView title : 'Disable 2-Factor Auth' style : 'solid medium disable-tf' callback : @bound 'handleDisableFormButton' handleDisableFormButton: -> { password } = @disableForm.inputs options = password : <PASSWORD>() disable : yes @handleProcessOf2FactorAuth options, 'Successfully Disabled!' handleProcessOf2FactorAuth: (options, message) -> me = whoami() me.setup2FactorAuth options, (err) => return if @showError err new kd.NotificationView title : message type : 'mini' @buildInitialView() getFormView: -> @addSubView @enableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' tfcode : cssClass : 'Formline--half' placeholder : 'Enter the verification code' name : 'tfcode' label : 'Verification Code' buttons : Enable : type : 'submit' title : 'Enable 2-Factor Auth' style : 'solid green small enable-tf' callback : @bound 'handleEnableFormButton' handleEnableFormButton: -> { password, tfcode } = @enableForm.inputs options = key : @_activeKey password : <PASSWORD>() verification : tfcode.getValue() @handleProcessOf2FactorAuth options, 'Successfully Enabled!' getQrCodeView: (url) -> view = new kd.CustomHTMLView cssClass : 'qrcode-view' view.addSubView imageView = new kd.CustomHTMLView tagName : 'img' attributes : { src : url } view.addSubView button = new kd.ButtonView iconOnly : yes icon : 'reload' loader : color : '#000000' size : width : 20 height : 20 callback : => me = whoami() me.generate2FactorAuthKey (err, authInfo) => @showError err if authInfo @_activeKey = authInfo.key imageView.setAttribute 'src', authInfo.qrcode kd.utils.defer button.bound 'hideLoader' return view getLoaderView: -> new kd.LoaderView cssClass : 'main-loader' showLoader : yes size : width : 25 height : 25 getLearnLink: -> " <a class='learn-link' href='https://koding.com/docs/2-factor-auth/' target=_blank> Learn more about 2-factor authentication.</a> " getInstructionsView: -> new kd.CustomHTMLView cssClass : 'instructions' partial : """ <div class='intro'> <cite></cite> Download and install the Google Authenticator app on your <a href='https://goo.gl/x01UdJ' target=_blank>iPhone</a> or <a href='https://goo.gl/Oe5t7l' target=_blank>Android</a> phone. Then follow the steps listed below to set up 2-factor authentication for your Koding account. <br /> #{@getLearnLink()} </div> <li>Open the Authenticator app on your phone. <li>Tap the “+" or “..." icon and then choose “Scan barcode" to add Koding. <li>Scan the code shown below using your phone's camera. <li>Enter the 6-digit verification code generated by the app in the space below and click the “Enable” button. """
true
kd = require 'kd' whoami = require 'app/util/whoami' KDView = kd.View KDButtonView = kd.ButtonView module.exports = class AccountTwoFactorAuth extends KDView constructor: (options = {}, data) -> options.cssClass = kd.utils.curry \ 'AppModal--account tfauth', options.cssClass super options, data viewAppended: -> @buildInitialView() showError: (err) -> return unless err console.warn err new kd.NotificationView type : 'mini' title : err.message cssClass : 'error' return err buildInitialView: -> @destroySubViews() @addSubView loader = @getLoaderView() kd.singletons.mainController.ready => me = whoami() me.generate2FactorAuthKey (err, authInfo) => loader.hide() if err if err.name is 'ALREADY_INUSE' @addSubView @getEnabledView() return return @showError err { key, qrcode } = authInfo @_activeKey = key @addSubView @getInstructionsView() @addSubView @getQrCodeView qrcode @addSubView @getFormView() getEnabledView: -> @addSubView new kd.CustomHTMLView cssClass : 'enabled-intro' partial : " <div> 2-Factor Authentication is <green>active</green> for your account. <cite></cite> </div> #{@getLearnLink()} " @addSubView @disableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' button : type : 'submit' label : '&nbsp;' cssClass : 'Formline--half' itemClass : KDButtonView title : 'Disable 2-Factor Auth' style : 'solid medium disable-tf' callback : @bound 'handleDisableFormButton' handleDisableFormButton: -> { password } = @disableForm.inputs options = password : PI:PASSWORD:<PASSWORD>END_PI() disable : yes @handleProcessOf2FactorAuth options, 'Successfully Disabled!' handleProcessOf2FactorAuth: (options, message) -> me = whoami() me.setup2FactorAuth options, (err) => return if @showError err new kd.NotificationView title : message type : 'mini' @buildInitialView() getFormView: -> @addSubView @enableForm = new kd.FormViewWithFields cssClass : 'AppModal-form' fields : password : cssClass : 'Formline--half' placeholder : 'Enter your Koding password' name : 'password' type : 'password' label : 'Password' tfcode : cssClass : 'Formline--half' placeholder : 'Enter the verification code' name : 'tfcode' label : 'Verification Code' buttons : Enable : type : 'submit' title : 'Enable 2-Factor Auth' style : 'solid green small enable-tf' callback : @bound 'handleEnableFormButton' handleEnableFormButton: -> { password, tfcode } = @enableForm.inputs options = key : @_activeKey password : PI:PASSWORD:<PASSWORD>END_PI() verification : tfcode.getValue() @handleProcessOf2FactorAuth options, 'Successfully Enabled!' getQrCodeView: (url) -> view = new kd.CustomHTMLView cssClass : 'qrcode-view' view.addSubView imageView = new kd.CustomHTMLView tagName : 'img' attributes : { src : url } view.addSubView button = new kd.ButtonView iconOnly : yes icon : 'reload' loader : color : '#000000' size : width : 20 height : 20 callback : => me = whoami() me.generate2FactorAuthKey (err, authInfo) => @showError err if authInfo @_activeKey = authInfo.key imageView.setAttribute 'src', authInfo.qrcode kd.utils.defer button.bound 'hideLoader' return view getLoaderView: -> new kd.LoaderView cssClass : 'main-loader' showLoader : yes size : width : 25 height : 25 getLearnLink: -> " <a class='learn-link' href='https://koding.com/docs/2-factor-auth/' target=_blank> Learn more about 2-factor authentication.</a> " getInstructionsView: -> new kd.CustomHTMLView cssClass : 'instructions' partial : """ <div class='intro'> <cite></cite> Download and install the Google Authenticator app on your <a href='https://goo.gl/x01UdJ' target=_blank>iPhone</a> or <a href='https://goo.gl/Oe5t7l' target=_blank>Android</a> phone. Then follow the steps listed below to set up 2-factor authentication for your Koding account. <br /> #{@getLearnLink()} </div> <li>Open the Authenticator app on your phone. <li>Tap the “+" or “..." icon and then choose “Scan barcode" to add Koding. <li>Scan the code shown below using your phone's camera. <li>Enter the 6-digit verification code generated by the app in the space below and click the “Enable” button. """
[ { "context": "#!/usr/bin/env coffee\n\n###\nCopyright © Avi Flax and other contributors\n\nPermission is hereby gran", "end": 47, "score": 0.9998348951339722, "start": 39, "tag": "NAME", "value": "Avi Flax" } ]
coffee-script/rollup.coffee
aviflax/rollups
2
#!/usr/bin/env coffee ### Copyright © Avi Flax 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. See the file LICENSE in the root of this project for the full license. ### LineStream = require 'linestream' optimist = require 'optimist' extractDate = (line) -> dateRegex = /// \[ (\d{2}) #day / (\w{3}) #month / (\d{4}) #year : (\d{2}) #hour : (\d{2}) #minute : (\d{2}) #second \s ([-+]\d{4}) #time zone offset \] /// matches = dateRegex.exec line return null if !matches day = matches[1] month = matches[2] year = matches[3] hour = matches[4] minute = matches[5] second = matches[6] offset = matches[7] # important to preserve the offsets so we're basically working with local times new Date("#{month} #{day}, #{year} #{hour}:#{minute}:#{second}#{offset}") extractWindowUnits = (windowSpec) -> windowSpec.charAt windowSpec.length - 1 extractWindowNum = (windowSpec) -> parseInt windowSpec windowToMillis = (windowSpec) -> num = extractWindowNum windowSpec unit = extractWindowUnits windowSpec switch unit when 'm' then num * 1000 * 60 when 'h' then num * 1000 * 60 * 60 when 'd' then num * 1000 * 60 * 60 * 24 when 'w' then num * 1000 * 60 * 60 * 24 * 7 else throw new Error "#{unit} is not a valid unit" dateToWindowStart = (date, windowSpec) -> # need to create a new date because the setters mutate state start = new Date date start.setMilliseconds 0 start.setSeconds 0 switch extractWindowUnits windowSpec when 'h' start.setMinutes 0 when 'd' start.setMinutes 0 start.setHours 0 when 'w' start.setMinutes 0 start.setHours 0 # change the day to the prior Sunday # JS appears to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. start.setDate start.getDate() - start.getDay() return start makeWindow = (startDate, windowSpec, startCount=0) -> start = dateToWindowStart startDate, windowSpec start: start end: addWindowDurationToStartDate start, windowSpec count: startCount dateToLastMinuteOfThatDay = (date) -> # dumb hack to get around Daylight Savings Time issues endOfDay = new Date date endOfDay.setHours 23 endOfDay.setMinutes 59 endOfDay.setSeconds 59 endOfDay.setMilliseconds 999 endOfDay addWindowDurationToStartDate = (startDate, windowSpec) -> num = extractWindowNum windowSpec switch extractWindowUnits windowSpec when 'm', 'h' new Date (startDate.getTime() + windowToMillis windowSpec) - 1 when 'd' end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + num - 1 end when 'w' # if start is Sunday the 1st at 00:00:00 then end needs to be Saturday the 7th at 23:59:59 # JS/V8 appear to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. # first get a date which is the last minute of the start date. This is an attempt to avoid problems with daylight savings time end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + ((num * 7) - 1) end incrementWindow = (window) -> start: window.start end: window.end count: window.count + 1 Array.prototype.updated = (index, value) -> # Return a copy of an array with an element at a specified index replaced with a new value this.slice(0, index).concat(value, this.slice(index + 1)) Array.prototype.replaceLast = (value) -> this.updated this.length - 1, value rollup = (windows, date, windowSpec='1d') -> return windows if not date # we only check the last window for a match, so the data must be pre-sorted lastWindow = windows[windows.length - 1] if lastWindow and lastWindow.start <= date < lastWindow.end windows.replaceLast incrementWindow(lastWindow) else windows.concat makeWindow date, windowSpec, 1 toCsv = (windows, separator='\t') -> 'Start' + separator + 'End' + separator + 'Count\n' + windows.reduce ((previous, window) -> previous + formatDateTimeForCsv(window.start) + separator + formatDateTimeForCsv(window.end) + separator + window.count + '\n'), '' padZeroLeft = (number) -> (if number < 10 then '0' else '') + number formatDateTimeForCsv = (date) -> '' + date.getFullYear() + '-' + padZeroLeft(date.getMonth() + 1) + '-' + padZeroLeft(date.getDate()) + ' ' + padZeroLeft(date.getHours()) + ':' + padZeroLeft(date.getMinutes()) ###### SCRIPT BODY ###### optimist.options 'w', alias: 'window', demand: true, describe: 'Time window size for rollups. E.g. 1m, 2h, 3d, 4w' argv = optimist.argv linestream = new LineStream process.stdin # TODO: this gets mutated (replaced) with every 'data' event below. Is that OK? ### It'd be more functional to treat the lines as a sequence. Gotta look into some way to do that in Node ### windows = [] linestream.on 'data', (line) -> windows = rollup windows, extractDate(line), argv.w linestream.on 'end', () -> process.stdout.write toCsv windows process.stdin.resume()
51652
#!/usr/bin/env coffee ### Copyright © <NAME> 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. See the file LICENSE in the root of this project for the full license. ### LineStream = require 'linestream' optimist = require 'optimist' extractDate = (line) -> dateRegex = /// \[ (\d{2}) #day / (\w{3}) #month / (\d{4}) #year : (\d{2}) #hour : (\d{2}) #minute : (\d{2}) #second \s ([-+]\d{4}) #time zone offset \] /// matches = dateRegex.exec line return null if !matches day = matches[1] month = matches[2] year = matches[3] hour = matches[4] minute = matches[5] second = matches[6] offset = matches[7] # important to preserve the offsets so we're basically working with local times new Date("#{month} #{day}, #{year} #{hour}:#{minute}:#{second}#{offset}") extractWindowUnits = (windowSpec) -> windowSpec.charAt windowSpec.length - 1 extractWindowNum = (windowSpec) -> parseInt windowSpec windowToMillis = (windowSpec) -> num = extractWindowNum windowSpec unit = extractWindowUnits windowSpec switch unit when 'm' then num * 1000 * 60 when 'h' then num * 1000 * 60 * 60 when 'd' then num * 1000 * 60 * 60 * 24 when 'w' then num * 1000 * 60 * 60 * 24 * 7 else throw new Error "#{unit} is not a valid unit" dateToWindowStart = (date, windowSpec) -> # need to create a new date because the setters mutate state start = new Date date start.setMilliseconds 0 start.setSeconds 0 switch extractWindowUnits windowSpec when 'h' start.setMinutes 0 when 'd' start.setMinutes 0 start.setHours 0 when 'w' start.setMinutes 0 start.setHours 0 # change the day to the prior Sunday # JS appears to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. start.setDate start.getDate() - start.getDay() return start makeWindow = (startDate, windowSpec, startCount=0) -> start = dateToWindowStart startDate, windowSpec start: start end: addWindowDurationToStartDate start, windowSpec count: startCount dateToLastMinuteOfThatDay = (date) -> # dumb hack to get around Daylight Savings Time issues endOfDay = new Date date endOfDay.setHours 23 endOfDay.setMinutes 59 endOfDay.setSeconds 59 endOfDay.setMilliseconds 999 endOfDay addWindowDurationToStartDate = (startDate, windowSpec) -> num = extractWindowNum windowSpec switch extractWindowUnits windowSpec when 'm', 'h' new Date (startDate.getTime() + windowToMillis windowSpec) - 1 when 'd' end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + num - 1 end when 'w' # if start is Sunday the 1st at 00:00:00 then end needs to be Saturday the 7th at 23:59:59 # JS/V8 appear to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. # first get a date which is the last minute of the start date. This is an attempt to avoid problems with daylight savings time end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + ((num * 7) - 1) end incrementWindow = (window) -> start: window.start end: window.end count: window.count + 1 Array.prototype.updated = (index, value) -> # Return a copy of an array with an element at a specified index replaced with a new value this.slice(0, index).concat(value, this.slice(index + 1)) Array.prototype.replaceLast = (value) -> this.updated this.length - 1, value rollup = (windows, date, windowSpec='1d') -> return windows if not date # we only check the last window for a match, so the data must be pre-sorted lastWindow = windows[windows.length - 1] if lastWindow and lastWindow.start <= date < lastWindow.end windows.replaceLast incrementWindow(lastWindow) else windows.concat makeWindow date, windowSpec, 1 toCsv = (windows, separator='\t') -> 'Start' + separator + 'End' + separator + 'Count\n' + windows.reduce ((previous, window) -> previous + formatDateTimeForCsv(window.start) + separator + formatDateTimeForCsv(window.end) + separator + window.count + '\n'), '' padZeroLeft = (number) -> (if number < 10 then '0' else '') + number formatDateTimeForCsv = (date) -> '' + date.getFullYear() + '-' + padZeroLeft(date.getMonth() + 1) + '-' + padZeroLeft(date.getDate()) + ' ' + padZeroLeft(date.getHours()) + ':' + padZeroLeft(date.getMinutes()) ###### SCRIPT BODY ###### optimist.options 'w', alias: 'window', demand: true, describe: 'Time window size for rollups. E.g. 1m, 2h, 3d, 4w' argv = optimist.argv linestream = new LineStream process.stdin # TODO: this gets mutated (replaced) with every 'data' event below. Is that OK? ### It'd be more functional to treat the lines as a sequence. Gotta look into some way to do that in Node ### windows = [] linestream.on 'data', (line) -> windows = rollup windows, extractDate(line), argv.w linestream.on 'end', () -> process.stdout.write toCsv windows process.stdin.resume()
true
#!/usr/bin/env coffee ### Copyright © PI:NAME:<NAME>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. See the file LICENSE in the root of this project for the full license. ### LineStream = require 'linestream' optimist = require 'optimist' extractDate = (line) -> dateRegex = /// \[ (\d{2}) #day / (\w{3}) #month / (\d{4}) #year : (\d{2}) #hour : (\d{2}) #minute : (\d{2}) #second \s ([-+]\d{4}) #time zone offset \] /// matches = dateRegex.exec line return null if !matches day = matches[1] month = matches[2] year = matches[3] hour = matches[4] minute = matches[5] second = matches[6] offset = matches[7] # important to preserve the offsets so we're basically working with local times new Date("#{month} #{day}, #{year} #{hour}:#{minute}:#{second}#{offset}") extractWindowUnits = (windowSpec) -> windowSpec.charAt windowSpec.length - 1 extractWindowNum = (windowSpec) -> parseInt windowSpec windowToMillis = (windowSpec) -> num = extractWindowNum windowSpec unit = extractWindowUnits windowSpec switch unit when 'm' then num * 1000 * 60 when 'h' then num * 1000 * 60 * 60 when 'd' then num * 1000 * 60 * 60 * 24 when 'w' then num * 1000 * 60 * 60 * 24 * 7 else throw new Error "#{unit} is not a valid unit" dateToWindowStart = (date, windowSpec) -> # need to create a new date because the setters mutate state start = new Date date start.setMilliseconds 0 start.setSeconds 0 switch extractWindowUnits windowSpec when 'h' start.setMinutes 0 when 'd' start.setMinutes 0 start.setHours 0 when 'w' start.setMinutes 0 start.setHours 0 # change the day to the prior Sunday # JS appears to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. start.setDate start.getDate() - start.getDay() return start makeWindow = (startDate, windowSpec, startCount=0) -> start = dateToWindowStart startDate, windowSpec start: start end: addWindowDurationToStartDate start, windowSpec count: startCount dateToLastMinuteOfThatDay = (date) -> # dumb hack to get around Daylight Savings Time issues endOfDay = new Date date endOfDay.setHours 23 endOfDay.setMinutes 59 endOfDay.setSeconds 59 endOfDay.setMilliseconds 999 endOfDay addWindowDurationToStartDate = (startDate, windowSpec) -> num = extractWindowNum windowSpec switch extractWindowUnits windowSpec when 'm', 'h' new Date (startDate.getTime() + windowToMillis windowSpec) - 1 when 'd' end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + num - 1 end when 'w' # if start is Sunday the 1st at 00:00:00 then end needs to be Saturday the 7th at 23:59:59 # JS/V8 appear to do the right thing: even if start was, for example, Thursday the first, then changing the date to Sunday also properly changes the month to the prior month. # first get a date which is the last minute of the start date. This is an attempt to avoid problems with daylight savings time end = dateToLastMinuteOfThatDay startDate end.setDate end.getDate() + ((num * 7) - 1) end incrementWindow = (window) -> start: window.start end: window.end count: window.count + 1 Array.prototype.updated = (index, value) -> # Return a copy of an array with an element at a specified index replaced with a new value this.slice(0, index).concat(value, this.slice(index + 1)) Array.prototype.replaceLast = (value) -> this.updated this.length - 1, value rollup = (windows, date, windowSpec='1d') -> return windows if not date # we only check the last window for a match, so the data must be pre-sorted lastWindow = windows[windows.length - 1] if lastWindow and lastWindow.start <= date < lastWindow.end windows.replaceLast incrementWindow(lastWindow) else windows.concat makeWindow date, windowSpec, 1 toCsv = (windows, separator='\t') -> 'Start' + separator + 'End' + separator + 'Count\n' + windows.reduce ((previous, window) -> previous + formatDateTimeForCsv(window.start) + separator + formatDateTimeForCsv(window.end) + separator + window.count + '\n'), '' padZeroLeft = (number) -> (if number < 10 then '0' else '') + number formatDateTimeForCsv = (date) -> '' + date.getFullYear() + '-' + padZeroLeft(date.getMonth() + 1) + '-' + padZeroLeft(date.getDate()) + ' ' + padZeroLeft(date.getHours()) + ':' + padZeroLeft(date.getMinutes()) ###### SCRIPT BODY ###### optimist.options 'w', alias: 'window', demand: true, describe: 'Time window size for rollups. E.g. 1m, 2h, 3d, 4w' argv = optimist.argv linestream = new LineStream process.stdin # TODO: this gets mutated (replaced) with every 'data' event below. Is that OK? ### It'd be more functional to treat the lines as a sequence. Gotta look into some way to do that in Node ### windows = [] linestream.on 'data', (line) -> windows = rollup windows, extractDate(line), argv.w linestream.on 'end', () -> process.stdout.write toCsv windows process.stdin.resume()
[ { "context": "settings =\n transmissionIframeSrc: \"http://95.128.64.231:6886\"\n @$el.html(@template(settings))\n ", "end": 220, "score": 0.9994120001792908, "start": 207, "tag": "IP_ADDRESS", "value": "95.128.64.231" } ]
app/assets/backbone/views/downloads/transmission.js.coffee
v-yarotsky/TorrentsPub
0
@module 'TorrentsPub.Downloads', -> class @DownloadsView extends Backbone.View template: JST["templates/downloads/transmission"] render: => settings = transmissionIframeSrc: "http://95.128.64.231:6886" @$el.html(@template(settings)) @
46399
@module 'TorrentsPub.Downloads', -> class @DownloadsView extends Backbone.View template: JST["templates/downloads/transmission"] render: => settings = transmissionIframeSrc: "http://172.16.17.32:6886" @$el.html(@template(settings)) @
true
@module 'TorrentsPub.Downloads', -> class @DownloadsView extends Backbone.View template: JST["templates/downloads/transmission"] render: => settings = transmissionIframeSrc: "http://PI:IP_ADDRESS:172.16.17.32END_PI:6886" @$el.html(@template(settings)) @
[ { "context": "() < upperBoundary) {\n # var old_key = my.selectedPoint.x();\n # my.selectedPoint.tr", "end": 17616, "score": 0.5756866335868835, "start": 17616, "tag": "KEY", "value": "" }, { "context": "dary) {\n # var old_key = my.selectedPoint.x();\n # ...
www/static/coffee/curve_editor.coffee
jonepatr/affordance-master-thesis
5
class window.BezierCurveEditor constructor: (@curveEditorContainer, @curveChannels, @sendHandler, @widthHeight) -> @listWithCurves = {} @gCanvas @gCtx @gBackCanvas @gBackCtx @Mode = kAdding: value: 0 name: "Adding" kSelecting: value: 1 name: "Selecting" kDragging: value: 2 name: "Dragging" kRemoving: value: 3 name: "Removing" @curveMode @gState @gBackgroundImg @gestures = [] for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] @curveMode = _.keys(@listWithCurves)[0] $("#" + @curveEditorContainer).html _.template($("#curve-editor-template").html(), {width: @widthHeight[0], height: @widthHeight[1], name: @curveEditorContainer}) $('.button-button').button() if _.keys(@listWithCurves).length > 1 for type of @listWithCurves $("#" + @curveEditorContainer + " .curve_mode_container").append " <label> <input type=\"radio\" name=\"curve_mode\" value=\"" + type + "\" " + ((if type is @curveMode then "checked=\"checked\"" else "")) + " /> " + type + "</label>" @gCanvas = $("#" + @curveEditorContainer + " .paintme").get(0) @gCtx = @gCanvas.getContext("2d") @height = @gCanvas.height @width = @gCanvas.width @gBackCanvas = $("<canvas class='back-canvas'></canvas>").appendTo($("#" + @curveEditorContainer)).get(0) @gBackCanvas.height = @height @gBackCanvas.width = @width @gBackCtx = @gBackCanvas.getContext("2d") @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .paintme").on "mousedown", (e) => handleDownSelect = (pos) => selected = @listWithCurves[@curveMode].gBezierPath.selectPoint(pos) if selected @gState = @Mode.kDragging @gCanvas.addEventListener "mousemove", ((e) => pos = @getMousePosition(e) @listWithCurves[@curveMode].gBezierPath.updateSelected pos @render() ), false return true false pos = @getMousePosition(e) switch @gState when @Mode.kAdding return if handleDownSelect(pos) # if @curveMode is "ems2" # if pos.y() < @height / 2 # pos = new Point(pos.x(), 2) # else # pos = new Point(pos.x(), @height - 2) @listWithCurves[@curveMode].gBezierPath.addPoint pos @render() when @Mode.kSelecting handleDownSelect pos when @Mode.kRemoving deleted = @listWithCurves[@curveMode].gBezierPath.deletePoint(pos) @render() if deleted $("#" + @curveEditorContainer + " .paintme").on "mouseup", (e) => if @gState is @Mode.kDragging #@gCanvas.removeEventListener("mousemove", updateSelected, false); @listWithCurves[@curveMode].gBezierPath.clearSelected() @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .selectMode").on "click", => @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .addMode").on "click", => @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .removeMode").on "click", => @gState = @Mode.kRemoving $("#" + @curveEditorContainer + " input[name=curve_mode]").on "change", (e) => @curveMode = $(e.currentTarget).val() $("#" + @curveEditorContainer + " .test_gesture_ems").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints @sendHandler.send [ "gesture" "test" JSON.stringify(list).replace(/,/g, "§") $(".time_for_gesture_test").val() ] $("#" + @curveEditorContainer + " .save_envelope_button").on "click", => list = [] for type of @listWithCurves list.push(@listWithCurves[type].bigListWithAllPoints) allPoints = JSON.stringify(list[0]).replace(/,/g, "§") gestureData = @saveGesture() send_id = @curveEditorContainer new_stuff = true if $("#" + @curveEditorContainer).data("envelope-id") send_id = $("#" + @curveEditorContainer).data("envelope-id") new_stuff = false @sendHandler.send [ "envelope" "save" window.current_user_id send_id $("#" + @curveEditorContainer + " .envelope_gestures").val() $("#" + @curveEditorContainer + " .gesture_time_duration").val() allPoints gestureData new_stuff ] $("#" + @curveEditorContainer + " .save_gesture_button").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints allPoints = JSON.stringify(list).replace(/,/g, "§") gestureData = @saveGesture() action = "save" data = $("#" + @curveEditorContainer + " .saved_gestures").val() if $("#" + @curveEditorContainer + " .saved_gestures").val() == "new_gesture" action = "save_new" data = $(".save_gesture").val() $("#" + @curveEditorContainer + " .save_gesture").val("") @sendHandler.send [ "gesture" action window.current_user_id data allPoints gestureData ] $("#" + @curveEditorContainer + " .saved_gestures").on "change", (e) => if $(e.currentTarget).val() == "new_gesture" $("#" + @curveEditorContainer + " .save_gesture_input_container").show() $("#" + @curveEditorContainer + " .remove-gesture").hide() else $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() $("#" + @curveEditorContainer + " .remove-gesture").show() if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .remove-gesture").html("Remove gesture") else $("#" + @curveEditorContainer + " .remove-gesture").html("Remove user-specific gesture") @sendHandler.send [ "gesture" "get" $(e.currentTarget).val() ] $("#" + @curveEditorContainer + " .reset-points").on "click", => if confirm("are you sure you want to delete all?") @reset() #gBezierPath = null #@gBackCtx.clearRect 0, 0, @width, @height #@gCtx.clearRect 0, 0, @width, @height for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() addGestures: (newGestures, clear) => unless clear is `undefined` @gestures = [] if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option value=\"new_gesture\">New gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").show() else $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option>Select gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() for eachh of newGestures @gestures.push newGestures[eachh] for each of @gestures $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").append "<option value=\"" + @gestures[each]['_id']['$oid'] + "\">" + @gestures[each]['name'] + "</option>" reset: -> for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() showEnvelope: (id, gesture, duration, individualPoints) => $("#" + @curveEditorContainer + " .envelope_gestures").val(gesture) $("#" + @curveEditorContainer + " .gesture_time_duration").val(duration) # $("#" + @curveEditorContainer).data("envelope-id", id) for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of individualPoints @listWithCurves[individualPoints[each][3]].gBezierPath.addPoint new Point(individualPoints[each][0][0], individualPoints[each][0][1]) @render() showGesture: (id, data) => if $("#" + @curveEditorContainer + " .saved_gestures").val() is id for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of data @listWithCurves[data[each][3]].gBezierPath.addPoint new Point(data[each][0][0], data[each][0][1]) @render() saveGesture: => allSegments = [] for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints allSegments.push @listWithCurves[type].listWithAllPoints[each].stringify() JSON.stringify(allSegments).replace /,/g, "§" render: => @gBackCtx.clearRect 0, 0, @width, @height @gCtx.clearRect 0, 0, @width, @height x = 0.5 while x < @width @gCtx.moveTo x, 0 @gCtx.lineTo x, @height x += @width / 30 y = 0.5 while y < @height @gCtx.moveTo 0, y @gCtx.lineTo @width, y y += @height / 30 @gCtx.strokeStyle = "#ddd" @gCtx.stroke() @gBackCtx.drawImage @gBackgroundImg, 0, 0 if @gBackgroundImg for each of @listWithCurves @listWithCurves[each].gBezierPath.draw @gBackCtx #var codeBox = document.getElementById('putJS'); #codeBox.innerHTML = gBezierPath.toJSString(); #} @gCtx.drawImage @gBackCanvas, 0, 0 # loop over both for type of @listWithCurves @listWithCurves[type].bigListWithAllPoints = [] for type of @listWithCurves first = true for each of @listWithCurves[type].listWithAllPoints unless first width = 600 #@listWithCurves[type].listWithAllPoints[each].pt.x() - @listWithCurves[type].listWithAllPoints[each].prev.pt.x() i = 0 while i < width startPt = @listWithCurves[type].listWithAllPoints[each].prev.pt ctrlPt1 = @listWithCurves[type].listWithAllPoints[each].ctrlPt1 ctrlPt2 = @listWithCurves[type].listWithAllPoints[each].ctrlPt2 endPt = @listWithCurves[type].listWithAllPoints[each].pt a = @getCubicBezierXYatPercent(startPt, ctrlPt1, ctrlPt2, endPt, i / width) listByX = [] x_val = Math.round(a.x) y_val = 100 - (Math.round(a.y * 100 / @height)) if x_val >= 0 and x_val < 600 if @listWithCurves[type].bigListWithAllPoints[x_val] @listWithCurves[type].bigListWithAllPoints[x_val] = Math.round((@listWithCurves[type].bigListWithAllPoints[x_val] + y_val) / 2) else @listWithCurves[type].bigListWithAllPoints[x_val] = y_val i++ #gBezierPath.addPointOrg(new Point()); else first = false for type of @listWithCurves i = 2 while i < width if not @listWithCurves[type].bigListWithAllPoints[i] or @listWithCurves[type].bigListWithAllPoints[i] is 0 values = [] values.push @listWithCurves[type].bigListWithAllPoints[i - 1] if @listWithCurves[type].bigListWithAllPoints[i - 1] < 100 values.push @listWithCurves[type].bigListWithAllPoints[i + 1] if @listWithCurves[type].bigListWithAllPoints[i + 1] < 100 @listWithCurves[type].bigListWithAllPoints[i] = Math.round(values.reduce((p, c) => p + c ) / values.length) i++ @listWithCurves[type].bigListWithAllPoints[0] = 0 @listWithCurves[type].bigListWithAllPoints[1] = 0 return getCubicBezierXYatPercent: (startPt, controlPt1, controlPt2, endPt, percent) => x = @CubicN(percent, startPt.x(), controlPt1.x(), controlPt2.x(), endPt.x()) y = @CubicN(percent, startPt.y(), controlPt1.y(), controlPt2.y(), endPt.y()) x: x y: y # cubic helper formula at percent distance CubicN: (pct, a, b, c, d) => t2 = pct * pct t3 = t2 * pct a + (-a * 3 + pct * (3 * a - a * pct)) * pct + (3 * b + pct * (-6 * b + b * 3 * pct)) * pct + (c * 3 - c * 3 * pct) * t2 + d * t3 # Modified from http://diveintohtml5.org/examples/halma.js getMousePosition: (e) => x = undefined y = undefined if e.pageX isnt `undefined` and e.pageY isnt `undefined` x = e.pageX y = e.pageY else x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop x -= @gCanvas.offsetLeft y -= @gCanvas.offsetTop new Point(x, y) Point = (newX, newY) -> my = this xVal = newX yVal = newY startXVal = -> ( newX )() RADIUS = 3 SELECT_RADIUS = RADIUS + 2 @x = -> xVal @y = -> yVal @startX = -> startXVal @set = (x, y) -> xVal = x yVal = y #xVal = Math.round(x); #yVal = Math.round(y); @drawSquare = (ctx) -> ctx.fillRect xVal - RADIUS, yVal - RADIUS, RADIUS * 2, RADIUS * 2 @computeSlope = (pt) -> (pt.y() - yVal) / (pt.x() - xVal) @contains = (pt) -> xInRange = pt.x() >= xVal - SELECT_RADIUS and pt.x() <= xVal + SELECT_RADIUS yInRange = pt.y() >= yVal - SELECT_RADIUS and pt.y() <= yVal + SELECT_RADIUS xInRange and yInRange @offsetFrom = (pt) -> xDelta: pt.x() - xVal yDelta: pt.y() - yVal @translate = (xDelta, yDelta) -> xVal += xDelta yVal += yDelta return this ControlPoint = (angle, magnitude, owner, isFirst) -> # Pointer to the line segment to which this belongs. # don't update neighbor in risk of infinite loop! # TODO fixme fragile # Returns the Point at which the knob is located. computeMagnitudeAngleFromOffset = (xDelta, yDelta) -> _magnitude = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)) tryAngle = Math.atan(yDelta / xDelta) unless isNaN(tryAngle) _angle = tryAngle _angle += Math.PI if xDelta < 0 return updateNeighbor = -> neighbor = null if _isFirst and _owner.prev neighbor = _owner.prev.ctrlPt2 else neighbor = _owner.next.ctrlPt1 if not _isFirst and _owner.next neighbor.setAngle _angle + Math.PI if neighbor return my = this _angle = angle _magnitude = magnitude _owner = owner _isFirst = isFirst @setAngle = (deg) -> _angle = deg unless _angle is deg @origin = origin = -> line = null if _isFirst line = _owner.prev else line = _owner return new Point(line.pt.x(), line.pt.y()) if line null @asPoint = -> new Point(my.x(), my.y()) @x = -> my.origin().x() + my.xDelta() @y = -> my.origin().y() + my.yDelta() @xDelta = -> _magnitude * Math.cos(_angle) @yDelta = -> _magnitude * Math.sin(_angle) @translate = (xDelta, yDelta) -> newLoc = my.asPoint() newLoc.translate xDelta, yDelta dist = my.origin().offsetFrom(newLoc) computeMagnitudeAngleFromOffset dist.xDelta, dist.yDelta updateNeighbor() if my.__proto__.syncNeighbor @contains = (pt) -> my.asPoint().contains pt @offsetFrom = (pt) -> my.asPoint().offsetFrom pt @draw = (ctx) -> ctx.save() ctx.fillStyle = "gray" ctx.strokeStyle = "gray" ctx.beginPath() startPt = my.origin() endPt = my.asPoint() ctx.moveTo startPt.x(), startPt.y() ctx.lineTo endPt.x(), endPt.y() ctx.stroke() endPt.drawSquare ctx ctx.restore() # When Constructed updateNeighbor() return this # Static variable dictacting if neighbors must be kept in sync. #ControlPoint.prototype.syncNeighbor = true; #} LineSegment = (pt, prev, channel, these) -> # Path point. # Control point 1. # Control point 2. # Next LineSegment in path # Previous LineSegment in path # Specific point on the LineSegment that is selected. # Draw control points if we have them # If there are at least two points, draw curve. # THIS STUFF CONTROLS SO POINTS DON'T CROSS EACHOTHER ON THE X AXIS # # var lowerBoundary = _.max(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x < my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # var upperBoundary = _.min(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x > my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # # # # if (my.selectedPoint.x() > lowerBoundary && my.selectedPoint.x() < upperBoundary) { # var old_key = my.selectedPoint.x(); # my.selectedPoint.translate(dist.xDelta, dist.yDelta); # //listWithAllPoints[newCord[0]] = listWithAllPoints[my.selectedPoint.x()]; # //Object.defineProperty(listWithAllPoints, , Object.getOwnPropertyDescriptor(listWithAllPoints, old_key)); # //delete listWithAllPoints[old_key]; # # // if(my.selectedPoint.x() !== old_key) { # // listWithAllPoints[my.channel][my.selectedPoint.x()] = listWithAllPoints[my.channel][old_key]; # // delete listWithAllPoints[my.channel][old_key]; # // } # # # # } drawCurve = (ctx, startPt, endPt, ctrlPt1, ctrlPt2) -> ctx.save() ctx.fillStyle = these.listWithCurves[my.channel].color ctx.strokeStyle = these.listWithCurves[my.channel].color ctx.beginPath() ctx.moveTo startPt.x(), startPt.y() ctx.bezierCurveTo ctrlPt1.x(), ctrlPt1.y(), ctrlPt2.x(), ctrlPt2.y(), endPt.x(), endPt.y() ctx.lineWidth = 10; ctx.stroke() ctx.restore() init = -> my.pt = pt my.prev = prev my.channel = channel if my.prev # Make initial line straight and with controls of length 15. slope = my.pt.computeSlope(my.prev.pt) angle = Math.atan(slope) angle *= -1 if my.prev.pt.x() > my.pt.x() my.ctrlPt1 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, true) my.ctrlPt2 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, false) my = this these = these @channel @pt @ctrlPt1 @ctrlPt2 @next @prev @selectedPoint init() @stringify = -> p = null c1 = null c2 = null if @pt? p = [ @pt.x() @pt.y() ] if @ctrlPt1? c1 = [ @ctrlPt1.x() @ctrlPt1.y() ] if @ctrlPt2? c2 = [ @ctrlPt2.x() @ctrlPt2.y() ] [ p c1 c2 this.channel ] @draw = (ctx) -> my.pt.drawSquare ctx my.ctrlPt1.draw ctx if my.ctrlPt1 my.ctrlPt2.draw ctx if my.ctrlPt2 drawCurve ctx, my.prev.pt, my.pt, my.ctrlPt1, my.ctrlPt2 if my.prev return @findInLineSegment = (pos) -> if my.pathPointIntersects(pos) my.selectedPoint = my.pt return true else if my.ctrlPt1 and my.ctrlPt1.contains(pos) my.selectedPoint = my.ctrlPt1 return true else if my.ctrlPt2 and my.ctrlPt2.contains(pos) my.selectedPoint = my.ctrlPt2 return true false @pathPointIntersects = (pos) -> my.pt and my.pt.contains(pos) @moveTo = (pos) -> dist = my.selectedPoint.offsetFrom(pos) if my.selectedPoint.x() isnt 2 and my.selectedPoint.x() isnt these.width - 2 my.selectedPoint.translate dist.xDelta, dist.yDelta else xx = (if my.selectedPoint.x() is 2 then 2 else these.width - 2) my.selectedPoint.translate 0, dist.yDelta return this BezierPath = (channel, these) -> my = this these = these my.channel = channel @channel # Beginning of BezierPath linked list. @head = null # End of BezierPath linked list @tail = null # Reference to selected LineSegment @selectedSegment @addPoint = (pt) -> for each of these.listWithCurves[my.channel].listWithAllPoints my.deletePoint these.listWithCurves[my.channel].listWithAllPoints[each].pt if pt.x() >= 0 and pt.x() < 600 these.listWithCurves[my.channel].listWithAllPoints[pt.x()] = pt: pt #listWithLineSegments = []; for each of these.listWithCurves[my.channel].listWithAllPoints these.listWithCurves[my.channel].listWithAllPoints[each] = my.addPointOrg(these.listWithCurves[my.channel].listWithAllPoints[each].pt) @addPointOrg = (pt) -> newPt = new LineSegment(pt, my.tail, my.channel, these) #listWithLineSegments.push(newPt); unless my.tail? my.tail = newPt my.head = newPt else my.tail.next = newPt my.tail = my.tail.next newPt # Must call after add point, since init uses # addPoint # TODO: this is a little gross @draw = (ctx) -> return unless my.head? current = my.head while current? current.draw ctx current = current.next # returns true if point selected @selectPoint = (pos) -> current = my.head while current? if current.findInLineSegment(pos) @selectedSegment = current return true current = current.next false # returns true if point deleted @deletePoint = (pos) -> current = my.head while current? if current.pathPointIntersects(pos) toDelete = current leftNeighbor = current.prev rightNeighbor = current.next # Middle case if leftNeighbor and rightNeighbor leftNeighbor.next = rightNeighbor rightNeighbor.prev = leftNeighbor # HEAD CASE else unless leftNeighbor my.head = rightNeighbor if my.head rightNeighbor.ctrlPt1 = null rightNeighbor.ctrlPt2 = null my.head.prev = null else my.tail = null # TAIL CASE else unless rightNeighbor my.tail = leftNeighbor if my.tail my.tail.next = null else my.head = null return true current = current.next false @clearSelected = -> @selectedSegment = null @updateSelected = (pos) -> @selectedSegment.moveTo pos return this
225832
class window.BezierCurveEditor constructor: (@curveEditorContainer, @curveChannels, @sendHandler, @widthHeight) -> @listWithCurves = {} @gCanvas @gCtx @gBackCanvas @gBackCtx @Mode = kAdding: value: 0 name: "Adding" kSelecting: value: 1 name: "Selecting" kDragging: value: 2 name: "Dragging" kRemoving: value: 3 name: "Removing" @curveMode @gState @gBackgroundImg @gestures = [] for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] @curveMode = _.keys(@listWithCurves)[0] $("#" + @curveEditorContainer).html _.template($("#curve-editor-template").html(), {width: @widthHeight[0], height: @widthHeight[1], name: @curveEditorContainer}) $('.button-button').button() if _.keys(@listWithCurves).length > 1 for type of @listWithCurves $("#" + @curveEditorContainer + " .curve_mode_container").append " <label> <input type=\"radio\" name=\"curve_mode\" value=\"" + type + "\" " + ((if type is @curveMode then "checked=\"checked\"" else "")) + " /> " + type + "</label>" @gCanvas = $("#" + @curveEditorContainer + " .paintme").get(0) @gCtx = @gCanvas.getContext("2d") @height = @gCanvas.height @width = @gCanvas.width @gBackCanvas = $("<canvas class='back-canvas'></canvas>").appendTo($("#" + @curveEditorContainer)).get(0) @gBackCanvas.height = @height @gBackCanvas.width = @width @gBackCtx = @gBackCanvas.getContext("2d") @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .paintme").on "mousedown", (e) => handleDownSelect = (pos) => selected = @listWithCurves[@curveMode].gBezierPath.selectPoint(pos) if selected @gState = @Mode.kDragging @gCanvas.addEventListener "mousemove", ((e) => pos = @getMousePosition(e) @listWithCurves[@curveMode].gBezierPath.updateSelected pos @render() ), false return true false pos = @getMousePosition(e) switch @gState when @Mode.kAdding return if handleDownSelect(pos) # if @curveMode is "ems2" # if pos.y() < @height / 2 # pos = new Point(pos.x(), 2) # else # pos = new Point(pos.x(), @height - 2) @listWithCurves[@curveMode].gBezierPath.addPoint pos @render() when @Mode.kSelecting handleDownSelect pos when @Mode.kRemoving deleted = @listWithCurves[@curveMode].gBezierPath.deletePoint(pos) @render() if deleted $("#" + @curveEditorContainer + " .paintme").on "mouseup", (e) => if @gState is @Mode.kDragging #@gCanvas.removeEventListener("mousemove", updateSelected, false); @listWithCurves[@curveMode].gBezierPath.clearSelected() @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .selectMode").on "click", => @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .addMode").on "click", => @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .removeMode").on "click", => @gState = @Mode.kRemoving $("#" + @curveEditorContainer + " input[name=curve_mode]").on "change", (e) => @curveMode = $(e.currentTarget).val() $("#" + @curveEditorContainer + " .test_gesture_ems").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints @sendHandler.send [ "gesture" "test" JSON.stringify(list).replace(/,/g, "§") $(".time_for_gesture_test").val() ] $("#" + @curveEditorContainer + " .save_envelope_button").on "click", => list = [] for type of @listWithCurves list.push(@listWithCurves[type].bigListWithAllPoints) allPoints = JSON.stringify(list[0]).replace(/,/g, "§") gestureData = @saveGesture() send_id = @curveEditorContainer new_stuff = true if $("#" + @curveEditorContainer).data("envelope-id") send_id = $("#" + @curveEditorContainer).data("envelope-id") new_stuff = false @sendHandler.send [ "envelope" "save" window.current_user_id send_id $("#" + @curveEditorContainer + " .envelope_gestures").val() $("#" + @curveEditorContainer + " .gesture_time_duration").val() allPoints gestureData new_stuff ] $("#" + @curveEditorContainer + " .save_gesture_button").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints allPoints = JSON.stringify(list).replace(/,/g, "§") gestureData = @saveGesture() action = "save" data = $("#" + @curveEditorContainer + " .saved_gestures").val() if $("#" + @curveEditorContainer + " .saved_gestures").val() == "new_gesture" action = "save_new" data = $(".save_gesture").val() $("#" + @curveEditorContainer + " .save_gesture").val("") @sendHandler.send [ "gesture" action window.current_user_id data allPoints gestureData ] $("#" + @curveEditorContainer + " .saved_gestures").on "change", (e) => if $(e.currentTarget).val() == "new_gesture" $("#" + @curveEditorContainer + " .save_gesture_input_container").show() $("#" + @curveEditorContainer + " .remove-gesture").hide() else $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() $("#" + @curveEditorContainer + " .remove-gesture").show() if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .remove-gesture").html("Remove gesture") else $("#" + @curveEditorContainer + " .remove-gesture").html("Remove user-specific gesture") @sendHandler.send [ "gesture" "get" $(e.currentTarget).val() ] $("#" + @curveEditorContainer + " .reset-points").on "click", => if confirm("are you sure you want to delete all?") @reset() #gBezierPath = null #@gBackCtx.clearRect 0, 0, @width, @height #@gCtx.clearRect 0, 0, @width, @height for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() addGestures: (newGestures, clear) => unless clear is `undefined` @gestures = [] if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option value=\"new_gesture\">New gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").show() else $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option>Select gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() for eachh of newGestures @gestures.push newGestures[eachh] for each of @gestures $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").append "<option value=\"" + @gestures[each]['_id']['$oid'] + "\">" + @gestures[each]['name'] + "</option>" reset: -> for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() showEnvelope: (id, gesture, duration, individualPoints) => $("#" + @curveEditorContainer + " .envelope_gestures").val(gesture) $("#" + @curveEditorContainer + " .gesture_time_duration").val(duration) # $("#" + @curveEditorContainer).data("envelope-id", id) for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of individualPoints @listWithCurves[individualPoints[each][3]].gBezierPath.addPoint new Point(individualPoints[each][0][0], individualPoints[each][0][1]) @render() showGesture: (id, data) => if $("#" + @curveEditorContainer + " .saved_gestures").val() is id for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of data @listWithCurves[data[each][3]].gBezierPath.addPoint new Point(data[each][0][0], data[each][0][1]) @render() saveGesture: => allSegments = [] for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints allSegments.push @listWithCurves[type].listWithAllPoints[each].stringify() JSON.stringify(allSegments).replace /,/g, "§" render: => @gBackCtx.clearRect 0, 0, @width, @height @gCtx.clearRect 0, 0, @width, @height x = 0.5 while x < @width @gCtx.moveTo x, 0 @gCtx.lineTo x, @height x += @width / 30 y = 0.5 while y < @height @gCtx.moveTo 0, y @gCtx.lineTo @width, y y += @height / 30 @gCtx.strokeStyle = "#ddd" @gCtx.stroke() @gBackCtx.drawImage @gBackgroundImg, 0, 0 if @gBackgroundImg for each of @listWithCurves @listWithCurves[each].gBezierPath.draw @gBackCtx #var codeBox = document.getElementById('putJS'); #codeBox.innerHTML = gBezierPath.toJSString(); #} @gCtx.drawImage @gBackCanvas, 0, 0 # loop over both for type of @listWithCurves @listWithCurves[type].bigListWithAllPoints = [] for type of @listWithCurves first = true for each of @listWithCurves[type].listWithAllPoints unless first width = 600 #@listWithCurves[type].listWithAllPoints[each].pt.x() - @listWithCurves[type].listWithAllPoints[each].prev.pt.x() i = 0 while i < width startPt = @listWithCurves[type].listWithAllPoints[each].prev.pt ctrlPt1 = @listWithCurves[type].listWithAllPoints[each].ctrlPt1 ctrlPt2 = @listWithCurves[type].listWithAllPoints[each].ctrlPt2 endPt = @listWithCurves[type].listWithAllPoints[each].pt a = @getCubicBezierXYatPercent(startPt, ctrlPt1, ctrlPt2, endPt, i / width) listByX = [] x_val = Math.round(a.x) y_val = 100 - (Math.round(a.y * 100 / @height)) if x_val >= 0 and x_val < 600 if @listWithCurves[type].bigListWithAllPoints[x_val] @listWithCurves[type].bigListWithAllPoints[x_val] = Math.round((@listWithCurves[type].bigListWithAllPoints[x_val] + y_val) / 2) else @listWithCurves[type].bigListWithAllPoints[x_val] = y_val i++ #gBezierPath.addPointOrg(new Point()); else first = false for type of @listWithCurves i = 2 while i < width if not @listWithCurves[type].bigListWithAllPoints[i] or @listWithCurves[type].bigListWithAllPoints[i] is 0 values = [] values.push @listWithCurves[type].bigListWithAllPoints[i - 1] if @listWithCurves[type].bigListWithAllPoints[i - 1] < 100 values.push @listWithCurves[type].bigListWithAllPoints[i + 1] if @listWithCurves[type].bigListWithAllPoints[i + 1] < 100 @listWithCurves[type].bigListWithAllPoints[i] = Math.round(values.reduce((p, c) => p + c ) / values.length) i++ @listWithCurves[type].bigListWithAllPoints[0] = 0 @listWithCurves[type].bigListWithAllPoints[1] = 0 return getCubicBezierXYatPercent: (startPt, controlPt1, controlPt2, endPt, percent) => x = @CubicN(percent, startPt.x(), controlPt1.x(), controlPt2.x(), endPt.x()) y = @CubicN(percent, startPt.y(), controlPt1.y(), controlPt2.y(), endPt.y()) x: x y: y # cubic helper formula at percent distance CubicN: (pct, a, b, c, d) => t2 = pct * pct t3 = t2 * pct a + (-a * 3 + pct * (3 * a - a * pct)) * pct + (3 * b + pct * (-6 * b + b * 3 * pct)) * pct + (c * 3 - c * 3 * pct) * t2 + d * t3 # Modified from http://diveintohtml5.org/examples/halma.js getMousePosition: (e) => x = undefined y = undefined if e.pageX isnt `undefined` and e.pageY isnt `undefined` x = e.pageX y = e.pageY else x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop x -= @gCanvas.offsetLeft y -= @gCanvas.offsetTop new Point(x, y) Point = (newX, newY) -> my = this xVal = newX yVal = newY startXVal = -> ( newX )() RADIUS = 3 SELECT_RADIUS = RADIUS + 2 @x = -> xVal @y = -> yVal @startX = -> startXVal @set = (x, y) -> xVal = x yVal = y #xVal = Math.round(x); #yVal = Math.round(y); @drawSquare = (ctx) -> ctx.fillRect xVal - RADIUS, yVal - RADIUS, RADIUS * 2, RADIUS * 2 @computeSlope = (pt) -> (pt.y() - yVal) / (pt.x() - xVal) @contains = (pt) -> xInRange = pt.x() >= xVal - SELECT_RADIUS and pt.x() <= xVal + SELECT_RADIUS yInRange = pt.y() >= yVal - SELECT_RADIUS and pt.y() <= yVal + SELECT_RADIUS xInRange and yInRange @offsetFrom = (pt) -> xDelta: pt.x() - xVal yDelta: pt.y() - yVal @translate = (xDelta, yDelta) -> xVal += xDelta yVal += yDelta return this ControlPoint = (angle, magnitude, owner, isFirst) -> # Pointer to the line segment to which this belongs. # don't update neighbor in risk of infinite loop! # TODO fixme fragile # Returns the Point at which the knob is located. computeMagnitudeAngleFromOffset = (xDelta, yDelta) -> _magnitude = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)) tryAngle = Math.atan(yDelta / xDelta) unless isNaN(tryAngle) _angle = tryAngle _angle += Math.PI if xDelta < 0 return updateNeighbor = -> neighbor = null if _isFirst and _owner.prev neighbor = _owner.prev.ctrlPt2 else neighbor = _owner.next.ctrlPt1 if not _isFirst and _owner.next neighbor.setAngle _angle + Math.PI if neighbor return my = this _angle = angle _magnitude = magnitude _owner = owner _isFirst = isFirst @setAngle = (deg) -> _angle = deg unless _angle is deg @origin = origin = -> line = null if _isFirst line = _owner.prev else line = _owner return new Point(line.pt.x(), line.pt.y()) if line null @asPoint = -> new Point(my.x(), my.y()) @x = -> my.origin().x() + my.xDelta() @y = -> my.origin().y() + my.yDelta() @xDelta = -> _magnitude * Math.cos(_angle) @yDelta = -> _magnitude * Math.sin(_angle) @translate = (xDelta, yDelta) -> newLoc = my.asPoint() newLoc.translate xDelta, yDelta dist = my.origin().offsetFrom(newLoc) computeMagnitudeAngleFromOffset dist.xDelta, dist.yDelta updateNeighbor() if my.__proto__.syncNeighbor @contains = (pt) -> my.asPoint().contains pt @offsetFrom = (pt) -> my.asPoint().offsetFrom pt @draw = (ctx) -> ctx.save() ctx.fillStyle = "gray" ctx.strokeStyle = "gray" ctx.beginPath() startPt = my.origin() endPt = my.asPoint() ctx.moveTo startPt.x(), startPt.y() ctx.lineTo endPt.x(), endPt.y() ctx.stroke() endPt.drawSquare ctx ctx.restore() # When Constructed updateNeighbor() return this # Static variable dictacting if neighbors must be kept in sync. #ControlPoint.prototype.syncNeighbor = true; #} LineSegment = (pt, prev, channel, these) -> # Path point. # Control point 1. # Control point 2. # Next LineSegment in path # Previous LineSegment in path # Specific point on the LineSegment that is selected. # Draw control points if we have them # If there are at least two points, draw curve. # THIS STUFF CONTROLS SO POINTS DON'T CROSS EACHOTHER ON THE X AXIS # # var lowerBoundary = _.max(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x < my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # var upperBoundary = _.min(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x > my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # # # # if (my.selectedPoint.x() > lowerBoundary && my.selectedPoint.x() < upperBoundary) { # var old_key = my<KEY>.selectedPoint.<KEY>(); # my.selectedPoint.translate(dist.xDelta, dist.yDelta); # //listWithAllPoints[newCord[0]] = listWithAllPoints[my.selectedPoint.x()]; # //Object.defineProperty(listWithAllPoints, , Object.getOwnPropertyDescriptor(listWithAllPoints, old_key)); # //delete listWithAllPoints[old_key]; # # // if(my.selectedPoint.x() !== old_key) { # // listWithAllPoints[my.channel][my.selectedPoint.x()] = listWithAllPoints[my.channel][old_key]; # // delete listWithAllPoints[my.channel][old_key]; # // } # # # # } drawCurve = (ctx, startPt, endPt, ctrlPt1, ctrlPt2) -> ctx.save() ctx.fillStyle = these.listWithCurves[my.channel].color ctx.strokeStyle = these.listWithCurves[my.channel].color ctx.beginPath() ctx.moveTo startPt.x(), startPt.y() ctx.bezierCurveTo ctrlPt1.x(), ctrlPt1.y(), ctrlPt2.x(), ctrlPt2.y(), endPt.x(), endPt.y() ctx.lineWidth = 10; ctx.stroke() ctx.restore() init = -> my.pt = pt my.prev = prev my.channel = channel if my.prev # Make initial line straight and with controls of length 15. slope = my.pt.computeSlope(my.prev.pt) angle = Math.atan(slope) angle *= -1 if my.prev.pt.x() > my.pt.x() my.ctrlPt1 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, true) my.ctrlPt2 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, false) my = this these = these @channel @pt @ctrlPt1 @ctrlPt2 @next @prev @selectedPoint init() @stringify = -> p = null c1 = null c2 = null if @pt? p = [ @pt.x() @pt.y() ] if @ctrlPt1? c1 = [ @ctrlPt1.x() @ctrlPt1.y() ] if @ctrlPt2? c2 = [ @ctrlPt2.x() @ctrlPt2.y() ] [ p c1 c2 this.channel ] @draw = (ctx) -> my.pt.drawSquare ctx my.ctrlPt1.draw ctx if my.ctrlPt1 my.ctrlPt2.draw ctx if my.ctrlPt2 drawCurve ctx, my.prev.pt, my.pt, my.ctrlPt1, my.ctrlPt2 if my.prev return @findInLineSegment = (pos) -> if my.pathPointIntersects(pos) my.selectedPoint = my.pt return true else if my.ctrlPt1 and my.ctrlPt1.contains(pos) my.selectedPoint = my.ctrlPt1 return true else if my.ctrlPt2 and my.ctrlPt2.contains(pos) my.selectedPoint = my.ctrlPt2 return true false @pathPointIntersects = (pos) -> my.pt and my.pt.contains(pos) @moveTo = (pos) -> dist = my.selectedPoint.offsetFrom(pos) if my.selectedPoint.x() isnt 2 and my.selectedPoint.x() isnt these.width - 2 my.selectedPoint.translate dist.xDelta, dist.yDelta else xx = (if my.selectedPoint.x() is 2 then 2 else these.width - 2) my.selectedPoint.translate 0, dist.yDelta return this BezierPath = (channel, these) -> my = this these = these my.channel = channel @channel # Beginning of BezierPath linked list. @head = null # End of BezierPath linked list @tail = null # Reference to selected LineSegment @selectedSegment @addPoint = (pt) -> for each of these.listWithCurves[my.channel].listWithAllPoints my.deletePoint these.listWithCurves[my.channel].listWithAllPoints[each].pt if pt.x() >= 0 and pt.x() < 600 these.listWithCurves[my.channel].listWithAllPoints[pt.x()] = pt: pt #listWithLineSegments = []; for each of these.listWithCurves[my.channel].listWithAllPoints these.listWithCurves[my.channel].listWithAllPoints[each] = my.addPointOrg(these.listWithCurves[my.channel].listWithAllPoints[each].pt) @addPointOrg = (pt) -> newPt = new LineSegment(pt, my.tail, my.channel, these) #listWithLineSegments.push(newPt); unless my.tail? my.tail = newPt my.head = newPt else my.tail.next = newPt my.tail = my.tail.next newPt # Must call after add point, since init uses # addPoint # TODO: this is a little gross @draw = (ctx) -> return unless my.head? current = my.head while current? current.draw ctx current = current.next # returns true if point selected @selectPoint = (pos) -> current = my.head while current? if current.findInLineSegment(pos) @selectedSegment = current return true current = current.next false # returns true if point deleted @deletePoint = (pos) -> current = my.head while current? if current.pathPointIntersects(pos) toDelete = current leftNeighbor = current.prev rightNeighbor = current.next # Middle case if leftNeighbor and rightNeighbor leftNeighbor.next = rightNeighbor rightNeighbor.prev = leftNeighbor # HEAD CASE else unless leftNeighbor my.head = rightNeighbor if my.head rightNeighbor.ctrlPt1 = null rightNeighbor.ctrlPt2 = null my.head.prev = null else my.tail = null # TAIL CASE else unless rightNeighbor my.tail = leftNeighbor if my.tail my.tail.next = null else my.head = null return true current = current.next false @clearSelected = -> @selectedSegment = null @updateSelected = (pos) -> @selectedSegment.moveTo pos return this
true
class window.BezierCurveEditor constructor: (@curveEditorContainer, @curveChannels, @sendHandler, @widthHeight) -> @listWithCurves = {} @gCanvas @gCtx @gBackCanvas @gBackCtx @Mode = kAdding: value: 0 name: "Adding" kSelecting: value: 1 name: "Selecting" kDragging: value: 2 name: "Dragging" kRemoving: value: 3 name: "Removing" @curveMode @gState @gBackgroundImg @gestures = [] for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] @curveMode = _.keys(@listWithCurves)[0] $("#" + @curveEditorContainer).html _.template($("#curve-editor-template").html(), {width: @widthHeight[0], height: @widthHeight[1], name: @curveEditorContainer}) $('.button-button').button() if _.keys(@listWithCurves).length > 1 for type of @listWithCurves $("#" + @curveEditorContainer + " .curve_mode_container").append " <label> <input type=\"radio\" name=\"curve_mode\" value=\"" + type + "\" " + ((if type is @curveMode then "checked=\"checked\"" else "")) + " /> " + type + "</label>" @gCanvas = $("#" + @curveEditorContainer + " .paintme").get(0) @gCtx = @gCanvas.getContext("2d") @height = @gCanvas.height @width = @gCanvas.width @gBackCanvas = $("<canvas class='back-canvas'></canvas>").appendTo($("#" + @curveEditorContainer)).get(0) @gBackCanvas.height = @height @gBackCanvas.width = @width @gBackCtx = @gBackCanvas.getContext("2d") @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .paintme").on "mousedown", (e) => handleDownSelect = (pos) => selected = @listWithCurves[@curveMode].gBezierPath.selectPoint(pos) if selected @gState = @Mode.kDragging @gCanvas.addEventListener "mousemove", ((e) => pos = @getMousePosition(e) @listWithCurves[@curveMode].gBezierPath.updateSelected pos @render() ), false return true false pos = @getMousePosition(e) switch @gState when @Mode.kAdding return if handleDownSelect(pos) # if @curveMode is "ems2" # if pos.y() < @height / 2 # pos = new Point(pos.x(), 2) # else # pos = new Point(pos.x(), @height - 2) @listWithCurves[@curveMode].gBezierPath.addPoint pos @render() when @Mode.kSelecting handleDownSelect pos when @Mode.kRemoving deleted = @listWithCurves[@curveMode].gBezierPath.deletePoint(pos) @render() if deleted $("#" + @curveEditorContainer + " .paintme").on "mouseup", (e) => if @gState is @Mode.kDragging #@gCanvas.removeEventListener("mousemove", updateSelected, false); @listWithCurves[@curveMode].gBezierPath.clearSelected() @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .selectMode").on "click", => @gState = @Mode.kSelecting $("#" + @curveEditorContainer + " .addMode").on "click", => @gState = @Mode.kAdding $("#" + @curveEditorContainer + " .removeMode").on "click", => @gState = @Mode.kRemoving $("#" + @curveEditorContainer + " input[name=curve_mode]").on "change", (e) => @curveMode = $(e.currentTarget).val() $("#" + @curveEditorContainer + " .test_gesture_ems").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints @sendHandler.send [ "gesture" "test" JSON.stringify(list).replace(/,/g, "§") $(".time_for_gesture_test").val() ] $("#" + @curveEditorContainer + " .save_envelope_button").on "click", => list = [] for type of @listWithCurves list.push(@listWithCurves[type].bigListWithAllPoints) allPoints = JSON.stringify(list[0]).replace(/,/g, "§") gestureData = @saveGesture() send_id = @curveEditorContainer new_stuff = true if $("#" + @curveEditorContainer).data("envelope-id") send_id = $("#" + @curveEditorContainer).data("envelope-id") new_stuff = false @sendHandler.send [ "envelope" "save" window.current_user_id send_id $("#" + @curveEditorContainer + " .envelope_gestures").val() $("#" + @curveEditorContainer + " .gesture_time_duration").val() allPoints gestureData new_stuff ] $("#" + @curveEditorContainer + " .save_gesture_button").on "click", => list = {} for type of @listWithCurves list[type] = @listWithCurves[type].bigListWithAllPoints allPoints = JSON.stringify(list).replace(/,/g, "§") gestureData = @saveGesture() action = "save" data = $("#" + @curveEditorContainer + " .saved_gestures").val() if $("#" + @curveEditorContainer + " .saved_gestures").val() == "new_gesture" action = "save_new" data = $(".save_gesture").val() $("#" + @curveEditorContainer + " .save_gesture").val("") @sendHandler.send [ "gesture" action window.current_user_id data allPoints gestureData ] $("#" + @curveEditorContainer + " .saved_gestures").on "change", (e) => if $(e.currentTarget).val() == "new_gesture" $("#" + @curveEditorContainer + " .save_gesture_input_container").show() $("#" + @curveEditorContainer + " .remove-gesture").hide() else $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() $("#" + @curveEditorContainer + " .remove-gesture").show() if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .remove-gesture").html("Remove gesture") else $("#" + @curveEditorContainer + " .remove-gesture").html("Remove user-specific gesture") @sendHandler.send [ "gesture" "get" $(e.currentTarget).val() ] $("#" + @curveEditorContainer + " .reset-points").on "click", => if confirm("are you sure you want to delete all?") @reset() #gBezierPath = null #@gBackCtx.clearRect 0, 0, @width, @height #@gCtx.clearRect 0, 0, @width, @height for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() addGestures: (newGestures, clear) => unless clear is `undefined` @gestures = [] if window.default_user == window.current_user_id $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option value=\"new_gesture\">New gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").show() else $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").html("<option>Select gesture</option>") $("#" + @curveEditorContainer + " .save_gesture_input_container").hide() for eachh of newGestures @gestures.push newGestures[eachh] for each of @gestures $("#" + @curveEditorContainer + " .saved_gestures,#" + @curveEditorContainer + " .envelope_gestures").append "<option value=\"" + @gestures[each]['_id']['$oid'] + "\">" + @gestures[each]['name'] + "</option>" reset: -> for each of @curveChannels @listWithCurves[@curveChannels[each][0]] = color: @curveChannels[each][1] gBezierPath: new BezierPath(@curveChannels[each][0], @) bigListWithAllPoints: [] listWithAllPoints: [] for each2 of @listWithCurves @listWithCurves[each2].gBezierPath.addPoint new Point(2, @height - 2) @listWithCurves[each2].gBezierPath.addPoint new Point(@width - 2, @height - 2) @render() showEnvelope: (id, gesture, duration, individualPoints) => $("#" + @curveEditorContainer + " .envelope_gestures").val(gesture) $("#" + @curveEditorContainer + " .gesture_time_duration").val(duration) # $("#" + @curveEditorContainer).data("envelope-id", id) for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of individualPoints @listWithCurves[individualPoints[each][3]].gBezierPath.addPoint new Point(individualPoints[each][0][0], individualPoints[each][0][1]) @render() showGesture: (id, data) => if $("#" + @curveEditorContainer + " .saved_gestures").val() is id for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints @listWithCurves[type].gBezierPath.deletePoint @listWithCurves[type].listWithAllPoints[each].pt for type of @listWithCurves @listWithCurves[type].listWithAllPoints = [] @listWithCurves[type].bigListWithAllPoints = [] for each of data @listWithCurves[data[each][3]].gBezierPath.addPoint new Point(data[each][0][0], data[each][0][1]) @render() saveGesture: => allSegments = [] for type of @listWithCurves for each of @listWithCurves[type].listWithAllPoints allSegments.push @listWithCurves[type].listWithAllPoints[each].stringify() JSON.stringify(allSegments).replace /,/g, "§" render: => @gBackCtx.clearRect 0, 0, @width, @height @gCtx.clearRect 0, 0, @width, @height x = 0.5 while x < @width @gCtx.moveTo x, 0 @gCtx.lineTo x, @height x += @width / 30 y = 0.5 while y < @height @gCtx.moveTo 0, y @gCtx.lineTo @width, y y += @height / 30 @gCtx.strokeStyle = "#ddd" @gCtx.stroke() @gBackCtx.drawImage @gBackgroundImg, 0, 0 if @gBackgroundImg for each of @listWithCurves @listWithCurves[each].gBezierPath.draw @gBackCtx #var codeBox = document.getElementById('putJS'); #codeBox.innerHTML = gBezierPath.toJSString(); #} @gCtx.drawImage @gBackCanvas, 0, 0 # loop over both for type of @listWithCurves @listWithCurves[type].bigListWithAllPoints = [] for type of @listWithCurves first = true for each of @listWithCurves[type].listWithAllPoints unless first width = 600 #@listWithCurves[type].listWithAllPoints[each].pt.x() - @listWithCurves[type].listWithAllPoints[each].prev.pt.x() i = 0 while i < width startPt = @listWithCurves[type].listWithAllPoints[each].prev.pt ctrlPt1 = @listWithCurves[type].listWithAllPoints[each].ctrlPt1 ctrlPt2 = @listWithCurves[type].listWithAllPoints[each].ctrlPt2 endPt = @listWithCurves[type].listWithAllPoints[each].pt a = @getCubicBezierXYatPercent(startPt, ctrlPt1, ctrlPt2, endPt, i / width) listByX = [] x_val = Math.round(a.x) y_val = 100 - (Math.round(a.y * 100 / @height)) if x_val >= 0 and x_val < 600 if @listWithCurves[type].bigListWithAllPoints[x_val] @listWithCurves[type].bigListWithAllPoints[x_val] = Math.round((@listWithCurves[type].bigListWithAllPoints[x_val] + y_val) / 2) else @listWithCurves[type].bigListWithAllPoints[x_val] = y_val i++ #gBezierPath.addPointOrg(new Point()); else first = false for type of @listWithCurves i = 2 while i < width if not @listWithCurves[type].bigListWithAllPoints[i] or @listWithCurves[type].bigListWithAllPoints[i] is 0 values = [] values.push @listWithCurves[type].bigListWithAllPoints[i - 1] if @listWithCurves[type].bigListWithAllPoints[i - 1] < 100 values.push @listWithCurves[type].bigListWithAllPoints[i + 1] if @listWithCurves[type].bigListWithAllPoints[i + 1] < 100 @listWithCurves[type].bigListWithAllPoints[i] = Math.round(values.reduce((p, c) => p + c ) / values.length) i++ @listWithCurves[type].bigListWithAllPoints[0] = 0 @listWithCurves[type].bigListWithAllPoints[1] = 0 return getCubicBezierXYatPercent: (startPt, controlPt1, controlPt2, endPt, percent) => x = @CubicN(percent, startPt.x(), controlPt1.x(), controlPt2.x(), endPt.x()) y = @CubicN(percent, startPt.y(), controlPt1.y(), controlPt2.y(), endPt.y()) x: x y: y # cubic helper formula at percent distance CubicN: (pct, a, b, c, d) => t2 = pct * pct t3 = t2 * pct a + (-a * 3 + pct * (3 * a - a * pct)) * pct + (3 * b + pct * (-6 * b + b * 3 * pct)) * pct + (c * 3 - c * 3 * pct) * t2 + d * t3 # Modified from http://diveintohtml5.org/examples/halma.js getMousePosition: (e) => x = undefined y = undefined if e.pageX isnt `undefined` and e.pageY isnt `undefined` x = e.pageX y = e.pageY else x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop x -= @gCanvas.offsetLeft y -= @gCanvas.offsetTop new Point(x, y) Point = (newX, newY) -> my = this xVal = newX yVal = newY startXVal = -> ( newX )() RADIUS = 3 SELECT_RADIUS = RADIUS + 2 @x = -> xVal @y = -> yVal @startX = -> startXVal @set = (x, y) -> xVal = x yVal = y #xVal = Math.round(x); #yVal = Math.round(y); @drawSquare = (ctx) -> ctx.fillRect xVal - RADIUS, yVal - RADIUS, RADIUS * 2, RADIUS * 2 @computeSlope = (pt) -> (pt.y() - yVal) / (pt.x() - xVal) @contains = (pt) -> xInRange = pt.x() >= xVal - SELECT_RADIUS and pt.x() <= xVal + SELECT_RADIUS yInRange = pt.y() >= yVal - SELECT_RADIUS and pt.y() <= yVal + SELECT_RADIUS xInRange and yInRange @offsetFrom = (pt) -> xDelta: pt.x() - xVal yDelta: pt.y() - yVal @translate = (xDelta, yDelta) -> xVal += xDelta yVal += yDelta return this ControlPoint = (angle, magnitude, owner, isFirst) -> # Pointer to the line segment to which this belongs. # don't update neighbor in risk of infinite loop! # TODO fixme fragile # Returns the Point at which the knob is located. computeMagnitudeAngleFromOffset = (xDelta, yDelta) -> _magnitude = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)) tryAngle = Math.atan(yDelta / xDelta) unless isNaN(tryAngle) _angle = tryAngle _angle += Math.PI if xDelta < 0 return updateNeighbor = -> neighbor = null if _isFirst and _owner.prev neighbor = _owner.prev.ctrlPt2 else neighbor = _owner.next.ctrlPt1 if not _isFirst and _owner.next neighbor.setAngle _angle + Math.PI if neighbor return my = this _angle = angle _magnitude = magnitude _owner = owner _isFirst = isFirst @setAngle = (deg) -> _angle = deg unless _angle is deg @origin = origin = -> line = null if _isFirst line = _owner.prev else line = _owner return new Point(line.pt.x(), line.pt.y()) if line null @asPoint = -> new Point(my.x(), my.y()) @x = -> my.origin().x() + my.xDelta() @y = -> my.origin().y() + my.yDelta() @xDelta = -> _magnitude * Math.cos(_angle) @yDelta = -> _magnitude * Math.sin(_angle) @translate = (xDelta, yDelta) -> newLoc = my.asPoint() newLoc.translate xDelta, yDelta dist = my.origin().offsetFrom(newLoc) computeMagnitudeAngleFromOffset dist.xDelta, dist.yDelta updateNeighbor() if my.__proto__.syncNeighbor @contains = (pt) -> my.asPoint().contains pt @offsetFrom = (pt) -> my.asPoint().offsetFrom pt @draw = (ctx) -> ctx.save() ctx.fillStyle = "gray" ctx.strokeStyle = "gray" ctx.beginPath() startPt = my.origin() endPt = my.asPoint() ctx.moveTo startPt.x(), startPt.y() ctx.lineTo endPt.x(), endPt.y() ctx.stroke() endPt.drawSquare ctx ctx.restore() # When Constructed updateNeighbor() return this # Static variable dictacting if neighbors must be kept in sync. #ControlPoint.prototype.syncNeighbor = true; #} LineSegment = (pt, prev, channel, these) -> # Path point. # Control point 1. # Control point 2. # Next LineSegment in path # Previous LineSegment in path # Specific point on the LineSegment that is selected. # Draw control points if we have them # If there are at least two points, draw curve. # THIS STUFF CONTROLS SO POINTS DON'T CROSS EACHOTHER ON THE X AXIS # # var lowerBoundary = _.max(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x < my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # var upperBoundary = _.min(_.map(listWithAllPoints[my.channel].filter(function (ls, x) { # return x > my.selectedPoint.startX(); # }), function (ls) { return ls.pt.x(); })); # # # # # if (my.selectedPoint.x() > lowerBoundary && my.selectedPoint.x() < upperBoundary) { # var old_key = myPI:KEY:<KEY>END_PI.selectedPoint.PI:KEY:<KEY>END_PI(); # my.selectedPoint.translate(dist.xDelta, dist.yDelta); # //listWithAllPoints[newCord[0]] = listWithAllPoints[my.selectedPoint.x()]; # //Object.defineProperty(listWithAllPoints, , Object.getOwnPropertyDescriptor(listWithAllPoints, old_key)); # //delete listWithAllPoints[old_key]; # # // if(my.selectedPoint.x() !== old_key) { # // listWithAllPoints[my.channel][my.selectedPoint.x()] = listWithAllPoints[my.channel][old_key]; # // delete listWithAllPoints[my.channel][old_key]; # // } # # # # } drawCurve = (ctx, startPt, endPt, ctrlPt1, ctrlPt2) -> ctx.save() ctx.fillStyle = these.listWithCurves[my.channel].color ctx.strokeStyle = these.listWithCurves[my.channel].color ctx.beginPath() ctx.moveTo startPt.x(), startPt.y() ctx.bezierCurveTo ctrlPt1.x(), ctrlPt1.y(), ctrlPt2.x(), ctrlPt2.y(), endPt.x(), endPt.y() ctx.lineWidth = 10; ctx.stroke() ctx.restore() init = -> my.pt = pt my.prev = prev my.channel = channel if my.prev # Make initial line straight and with controls of length 15. slope = my.pt.computeSlope(my.prev.pt) angle = Math.atan(slope) angle *= -1 if my.prev.pt.x() > my.pt.x() my.ctrlPt1 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, true) my.ctrlPt2 = new ControlPoint(10 * Math.PI, 10 * Math.PI, my, false) my = this these = these @channel @pt @ctrlPt1 @ctrlPt2 @next @prev @selectedPoint init() @stringify = -> p = null c1 = null c2 = null if @pt? p = [ @pt.x() @pt.y() ] if @ctrlPt1? c1 = [ @ctrlPt1.x() @ctrlPt1.y() ] if @ctrlPt2? c2 = [ @ctrlPt2.x() @ctrlPt2.y() ] [ p c1 c2 this.channel ] @draw = (ctx) -> my.pt.drawSquare ctx my.ctrlPt1.draw ctx if my.ctrlPt1 my.ctrlPt2.draw ctx if my.ctrlPt2 drawCurve ctx, my.prev.pt, my.pt, my.ctrlPt1, my.ctrlPt2 if my.prev return @findInLineSegment = (pos) -> if my.pathPointIntersects(pos) my.selectedPoint = my.pt return true else if my.ctrlPt1 and my.ctrlPt1.contains(pos) my.selectedPoint = my.ctrlPt1 return true else if my.ctrlPt2 and my.ctrlPt2.contains(pos) my.selectedPoint = my.ctrlPt2 return true false @pathPointIntersects = (pos) -> my.pt and my.pt.contains(pos) @moveTo = (pos) -> dist = my.selectedPoint.offsetFrom(pos) if my.selectedPoint.x() isnt 2 and my.selectedPoint.x() isnt these.width - 2 my.selectedPoint.translate dist.xDelta, dist.yDelta else xx = (if my.selectedPoint.x() is 2 then 2 else these.width - 2) my.selectedPoint.translate 0, dist.yDelta return this BezierPath = (channel, these) -> my = this these = these my.channel = channel @channel # Beginning of BezierPath linked list. @head = null # End of BezierPath linked list @tail = null # Reference to selected LineSegment @selectedSegment @addPoint = (pt) -> for each of these.listWithCurves[my.channel].listWithAllPoints my.deletePoint these.listWithCurves[my.channel].listWithAllPoints[each].pt if pt.x() >= 0 and pt.x() < 600 these.listWithCurves[my.channel].listWithAllPoints[pt.x()] = pt: pt #listWithLineSegments = []; for each of these.listWithCurves[my.channel].listWithAllPoints these.listWithCurves[my.channel].listWithAllPoints[each] = my.addPointOrg(these.listWithCurves[my.channel].listWithAllPoints[each].pt) @addPointOrg = (pt) -> newPt = new LineSegment(pt, my.tail, my.channel, these) #listWithLineSegments.push(newPt); unless my.tail? my.tail = newPt my.head = newPt else my.tail.next = newPt my.tail = my.tail.next newPt # Must call after add point, since init uses # addPoint # TODO: this is a little gross @draw = (ctx) -> return unless my.head? current = my.head while current? current.draw ctx current = current.next # returns true if point selected @selectPoint = (pos) -> current = my.head while current? if current.findInLineSegment(pos) @selectedSegment = current return true current = current.next false # returns true if point deleted @deletePoint = (pos) -> current = my.head while current? if current.pathPointIntersects(pos) toDelete = current leftNeighbor = current.prev rightNeighbor = current.next # Middle case if leftNeighbor and rightNeighbor leftNeighbor.next = rightNeighbor rightNeighbor.prev = leftNeighbor # HEAD CASE else unless leftNeighbor my.head = rightNeighbor if my.head rightNeighbor.ctrlPt1 = null rightNeighbor.ctrlPt2 = null my.head.prev = null else my.tail = null # TAIL CASE else unless rightNeighbor my.tail = leftNeighbor if my.tail my.tail.next = null else my.head = null return true current = current.next false @clearSelected = -> @selectedSegment = null @updateSelected = (pos) -> @selectedSegment.moveTo pos return this
[ { "context": " contains configuration of the project.\n\n @author Fabian M. <mail.fabianm@gmail.com>\n###\nclass ProjectConfig", "end": 212, "score": 0.9995850324630737, "start": 204, "tag": "NAME", "value": "Fabian M" }, { "context": "nfiguration of the project.\n\n @author Fabian...
kaffee/src/main/kaffee/project/configuration.coffee
fabianm/kaffee
1
Fs = require "fs" Path = require "path" Configuration = require "../configuration" Util = require "../util" ### The {@link ProjectConfiguration} class contains configuration of the project. @author Fabian M. <mail.fabianm@gmail.com> ### class ProjectConfiguration ### Constructs a new {@link ProjectConfiguration} instance. @since 1.0 @param workspace The workspace of this {@link ProjectConfiguration} instance. @param file The relative path to the project configuration file. ### constructor: (@workspace, @file = Configuration.DEFAULT_PROJECT_CONFIG_FILE) -> @data = Configuration.SUPER_PROJECT_CONFIG @path = Path.join @getWorkspace().getPath(), @file @data = Util.merge @data, @read() ### Reads the package data file into a Javascript array. @since 0.0.1 ### read: -> try return JSON.parse(Fs.readFileSync(@path, 'UTF-8')) catch e throw "Failed to load the project configuration file (#{ @path })\n#{ e }" ### Updates the package data file. @param arr The array to update the package data file with. @since 0.0.1 ### update: (arr = @data) -> Fs.writeFileSync(@path, JSON.stringify(arr)) ### Returns the path to the file that contains the project data. @since 0.1.1 @return The path to the file that contains the project data. ### getPath: -> @path ### Returns the {@link Workspace} of this {@link ProjectConfiguration} instance. @since 0.3.0 @return The {@link Workspace} of this {@link ProjectConfiguration} instance. ### getWorkspace: -> @workspace ### Returns the data that has been read. @since 0.1.1 @return The data that has been read. ### getData: -> @data ### Returns the name of this package. @since 0.3.0 @return The name of this package. ### getName: -> @data.name ### Returns the version of this package. @since 0.3.0 @return The version of this package. ### getVersion: -> @data.version ### Returns the dependencies of this package. @since 0.3.0 @return The dependencies of this package. ### getDependencies: -> @data.dependencies ### Returns the Kaffee configuration of this package. The Kaffee configuration of this package should look something like: configuration: plugins: "compiler" : module: "kaffee-coffeemaker" alias: ["coffeescript", "coffee-script"] "minify" : module: "kaffee-minify" "automatic-build-1": module: "kaffee-cyclus" goals: ["compile"] every: "hour" "automatic-build-2": module: "kaffee-cyclus" goals: ["compile"] every: "change" archtype: "kaffee-archtype-simple" @since 0.3.0 @return The Kaffee configuration of this package. ### getKaffeeConfiguration: -> ((o) -> ### Kaffee configuration ### data = o.data.kaffee ### Returns the plugins of this Kaffee project. @since 0.3.0 @return The plugins of this Kaffee project. ### @getPlugins = -> data.plugins ### Returns the directory structure of this Kaffee project. @since 0.3.0 @return The directory structure of this Kaffee project. ### @getStructure = -> ### Returns this directory structure as an array. @since 0.3.0 @return This directory structure as an array. ### @toArray = -> data.structure ### Returns the path of the directory with the specified name. @since 0.3.0 @return The path of the directory with the specified name. ### @get = (name) -> Path.join o.getWorkspace().getPath(), @toArray()[name] this ### Returns the lifecycles of this Kaffee project. @since 0.3.0 @return The lifecycles of this Kaffee project. ### @getLifecycles = -> data.lifecycles ### Returns the parent project of this Kaffee project. @since 0.3.0 @return The parent project of this Kaffee project. ### @getParent = -> data.parent ### Returns the childs of this Kaffee project. @since 0.3.0 @return The childs of this Kaffee project. ### @getModules = -> data.modules ### Returns the archtype of this Kaffee project. @since 0.3.0 @return The archtype of this Kaffee project. ### @getArchtype = -> data.archtype this ) this ### Determines if the configuration file exists. @since 0.0.1 @return <code>true</code> if the package.json exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path module.exports = ProjectConfiguration
206781
Fs = require "fs" Path = require "path" Configuration = require "../configuration" Util = require "../util" ### The {@link ProjectConfiguration} class contains configuration of the project. @author <NAME>. <<EMAIL>> ### class ProjectConfiguration ### Constructs a new {@link ProjectConfiguration} instance. @since 1.0 @param workspace The workspace of this {@link ProjectConfiguration} instance. @param file The relative path to the project configuration file. ### constructor: (@workspace, @file = Configuration.DEFAULT_PROJECT_CONFIG_FILE) -> @data = Configuration.SUPER_PROJECT_CONFIG @path = Path.join @getWorkspace().getPath(), @file @data = Util.merge @data, @read() ### Reads the package data file into a Javascript array. @since 0.0.1 ### read: -> try return JSON.parse(Fs.readFileSync(@path, 'UTF-8')) catch e throw "Failed to load the project configuration file (#{ @path })\n#{ e }" ### Updates the package data file. @param arr The array to update the package data file with. @since 0.0.1 ### update: (arr = @data) -> Fs.writeFileSync(@path, JSON.stringify(arr)) ### Returns the path to the file that contains the project data. @since 0.1.1 @return The path to the file that contains the project data. ### getPath: -> @path ### Returns the {@link Workspace} of this {@link ProjectConfiguration} instance. @since 0.3.0 @return The {@link Workspace} of this {@link ProjectConfiguration} instance. ### getWorkspace: -> @workspace ### Returns the data that has been read. @since 0.1.1 @return The data that has been read. ### getData: -> @data ### Returns the name of this package. @since 0.3.0 @return The name of this package. ### getName: -> @data.name ### Returns the version of this package. @since 0.3.0 @return The version of this package. ### getVersion: -> @data.version ### Returns the dependencies of this package. @since 0.3.0 @return The dependencies of this package. ### getDependencies: -> @data.dependencies ### Returns the Kaffee configuration of this package. The Kaffee configuration of this package should look something like: configuration: plugins: "compiler" : module: "kaffee-coffeemaker" alias: ["coffeescript", "coffee-script"] "minify" : module: "kaffee-minify" "automatic-build-1": module: "kaffee-cyclus" goals: ["compile"] every: "hour" "automatic-build-2": module: "kaffee-cyclus" goals: ["compile"] every: "change" archtype: "kaffee-archtype-simple" @since 0.3.0 @return The Kaffee configuration of this package. ### getKaffeeConfiguration: -> ((o) -> ### Kaffee configuration ### data = o.data.kaffee ### Returns the plugins of this Kaffee project. @since 0.3.0 @return The plugins of this Kaffee project. ### @getPlugins = -> data.plugins ### Returns the directory structure of this Kaffee project. @since 0.3.0 @return The directory structure of this Kaffee project. ### @getStructure = -> ### Returns this directory structure as an array. @since 0.3.0 @return This directory structure as an array. ### @toArray = -> data.structure ### Returns the path of the directory with the specified name. @since 0.3.0 @return The path of the directory with the specified name. ### @get = (name) -> Path.join o.getWorkspace().getPath(), @toArray()[name] this ### Returns the lifecycles of this Kaffee project. @since 0.3.0 @return The lifecycles of this Kaffee project. ### @getLifecycles = -> data.lifecycles ### Returns the parent project of this Kaffee project. @since 0.3.0 @return The parent project of this Kaffee project. ### @getParent = -> data.parent ### Returns the childs of this Kaffee project. @since 0.3.0 @return The childs of this Kaffee project. ### @getModules = -> data.modules ### Returns the archtype of this Kaffee project. @since 0.3.0 @return The archtype of this Kaffee project. ### @getArchtype = -> data.archtype this ) this ### Determines if the configuration file exists. @since 0.0.1 @return <code>true</code> if the package.json exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path module.exports = ProjectConfiguration
true
Fs = require "fs" Path = require "path" Configuration = require "../configuration" Util = require "../util" ### The {@link ProjectConfiguration} class contains configuration of the project. @author PI:NAME:<NAME>END_PI. <PI:EMAIL:<EMAIL>END_PI> ### class ProjectConfiguration ### Constructs a new {@link ProjectConfiguration} instance. @since 1.0 @param workspace The workspace of this {@link ProjectConfiguration} instance. @param file The relative path to the project configuration file. ### constructor: (@workspace, @file = Configuration.DEFAULT_PROJECT_CONFIG_FILE) -> @data = Configuration.SUPER_PROJECT_CONFIG @path = Path.join @getWorkspace().getPath(), @file @data = Util.merge @data, @read() ### Reads the package data file into a Javascript array. @since 0.0.1 ### read: -> try return JSON.parse(Fs.readFileSync(@path, 'UTF-8')) catch e throw "Failed to load the project configuration file (#{ @path })\n#{ e }" ### Updates the package data file. @param arr The array to update the package data file with. @since 0.0.1 ### update: (arr = @data) -> Fs.writeFileSync(@path, JSON.stringify(arr)) ### Returns the path to the file that contains the project data. @since 0.1.1 @return The path to the file that contains the project data. ### getPath: -> @path ### Returns the {@link Workspace} of this {@link ProjectConfiguration} instance. @since 0.3.0 @return The {@link Workspace} of this {@link ProjectConfiguration} instance. ### getWorkspace: -> @workspace ### Returns the data that has been read. @since 0.1.1 @return The data that has been read. ### getData: -> @data ### Returns the name of this package. @since 0.3.0 @return The name of this package. ### getName: -> @data.name ### Returns the version of this package. @since 0.3.0 @return The version of this package. ### getVersion: -> @data.version ### Returns the dependencies of this package. @since 0.3.0 @return The dependencies of this package. ### getDependencies: -> @data.dependencies ### Returns the Kaffee configuration of this package. The Kaffee configuration of this package should look something like: configuration: plugins: "compiler" : module: "kaffee-coffeemaker" alias: ["coffeescript", "coffee-script"] "minify" : module: "kaffee-minify" "automatic-build-1": module: "kaffee-cyclus" goals: ["compile"] every: "hour" "automatic-build-2": module: "kaffee-cyclus" goals: ["compile"] every: "change" archtype: "kaffee-archtype-simple" @since 0.3.0 @return The Kaffee configuration of this package. ### getKaffeeConfiguration: -> ((o) -> ### Kaffee configuration ### data = o.data.kaffee ### Returns the plugins of this Kaffee project. @since 0.3.0 @return The plugins of this Kaffee project. ### @getPlugins = -> data.plugins ### Returns the directory structure of this Kaffee project. @since 0.3.0 @return The directory structure of this Kaffee project. ### @getStructure = -> ### Returns this directory structure as an array. @since 0.3.0 @return This directory structure as an array. ### @toArray = -> data.structure ### Returns the path of the directory with the specified name. @since 0.3.0 @return The path of the directory with the specified name. ### @get = (name) -> Path.join o.getWorkspace().getPath(), @toArray()[name] this ### Returns the lifecycles of this Kaffee project. @since 0.3.0 @return The lifecycles of this Kaffee project. ### @getLifecycles = -> data.lifecycles ### Returns the parent project of this Kaffee project. @since 0.3.0 @return The parent project of this Kaffee project. ### @getParent = -> data.parent ### Returns the childs of this Kaffee project. @since 0.3.0 @return The childs of this Kaffee project. ### @getModules = -> data.modules ### Returns the archtype of this Kaffee project. @since 0.3.0 @return The archtype of this Kaffee project. ### @getArchtype = -> data.archtype this ) this ### Determines if the configuration file exists. @since 0.0.1 @return <code>true</code> if the package.json exists, <code>false</code> otherwise. ### exists: -> Fs.existsSync @path module.exports = ProjectConfiguration
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.7049664258956909, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/spec/SpecBarcode.coffee
heartyoh/infopik
0
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'bwip' 'KineticJS' ], (bwip, kin) -> "use strict" createView = (attributes) -> view = new kin.Image x: attributes.x y: attributes.y draggable: true id: attributes.id imageObj = new Image() imageObj.onload = -> view.setAttrs width : imageObj.width, height : imageObj.height layer = view.getLayer() layer.draw() if layer imageObj.src = bwip.imageUrl symbol : attributes['symbol'] text : attributes['text'] alttext : attributes['alttext'] scale_h : attributes['scale_h'] scale_w : attributes['scale_w'] rotation : attributes['rotation'] view.setImage(imageObj) view createHandle = (attributes) -> new Kin.Image(attributes) model_event_map = '(self)' : '(self)' : change : (component, before, after, changed) -> return if after.x or after.y controller = this view = controller.getAttachedViews()[0] url = bwip.imageUrl symbol : component.get('symbol'), text : component.get('text'), alttext : component.get('alttext'), scale_h : component.get('scale_h'), scale_w : component.get('scale_w'), rotation : component.get('rotation') imageObj = view.getImage() imageObj.src = url { type: 'barcode' name: 'barcode' description: 'Barcode Specification' defaults: { width: 100 height: 50 stroke: 'black' strokeWidth: 1 rotationDeg: 0 draggable: true } model_event_map: model_event_map view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_barcode.png' }
99898
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'bwip' 'KineticJS' ], (bwip, kin) -> "use strict" createView = (attributes) -> view = new kin.Image x: attributes.x y: attributes.y draggable: true id: attributes.id imageObj = new Image() imageObj.onload = -> view.setAttrs width : imageObj.width, height : imageObj.height layer = view.getLayer() layer.draw() if layer imageObj.src = bwip.imageUrl symbol : attributes['symbol'] text : attributes['text'] alttext : attributes['alttext'] scale_h : attributes['scale_h'] scale_w : attributes['scale_w'] rotation : attributes['rotation'] view.setImage(imageObj) view createHandle = (attributes) -> new Kin.Image(attributes) model_event_map = '(self)' : '(self)' : change : (component, before, after, changed) -> return if after.x or after.y controller = this view = controller.getAttachedViews()[0] url = bwip.imageUrl symbol : component.get('symbol'), text : component.get('text'), alttext : component.get('alttext'), scale_h : component.get('scale_h'), scale_w : component.get('scale_w'), rotation : component.get('rotation') imageObj = view.getImage() imageObj.src = url { type: 'barcode' name: 'barcode' description: 'Barcode Specification' defaults: { width: 100 height: 50 stroke: 'black' strokeWidth: 1 rotationDeg: 0 draggable: true } model_event_map: model_event_map view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_barcode.png' }
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'bwip' 'KineticJS' ], (bwip, kin) -> "use strict" createView = (attributes) -> view = new kin.Image x: attributes.x y: attributes.y draggable: true id: attributes.id imageObj = new Image() imageObj.onload = -> view.setAttrs width : imageObj.width, height : imageObj.height layer = view.getLayer() layer.draw() if layer imageObj.src = bwip.imageUrl symbol : attributes['symbol'] text : attributes['text'] alttext : attributes['alttext'] scale_h : attributes['scale_h'] scale_w : attributes['scale_w'] rotation : attributes['rotation'] view.setImage(imageObj) view createHandle = (attributes) -> new Kin.Image(attributes) model_event_map = '(self)' : '(self)' : change : (component, before, after, changed) -> return if after.x or after.y controller = this view = controller.getAttachedViews()[0] url = bwip.imageUrl symbol : component.get('symbol'), text : component.get('text'), alttext : component.get('alttext'), scale_h : component.get('scale_h'), scale_w : component.get('scale_w'), rotation : component.get('rotation') imageObj = view.getImage() imageObj.src = url { type: 'barcode' name: 'barcode' description: 'Barcode Specification' defaults: { width: 100 height: 50 stroke: 'black' strokeWidth: 1 rotationDeg: 0 draggable: true } model_event_map: model_event_map view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_barcode.png' }
[ { "context": "(|\\\\)|\\\\s|\\\\.)*$\")\n\n setting =\n key: \"offsets-#{scope.offsetsKey}\"\n\n setting.initialize = ->\n", "end": 662, "score": 0.9956178665161133, "start": 652, "tag": "KEY", "value": "offsets-#{" } ]
src/components/widgets-settings/offsets/offsets.directive.coffee
agranado2k/impac-angular
7
module = angular.module('impac.components.widgets-settings.offsets',[]) module.directive('settingOffsets', ($templateCache, ImpacUtilities) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' offsetsKey: '@' initialOffsets: '=' currency: '=' intervalsCount: '=' period: '=' showIntervalsMult: '=' textPlaceholder: '@?' }, template: $templateCache.get('widgets-settings/offsets.tmpl.html'), link: (scope) -> w = scope.parentWidget authorized_regex = new RegExp("^(\\{|\\d|\\}|\\/|\\+|-|\\*|\\(|\\)|\\s|\\.)*$") setting = key: "offsets-#{scope.offsetsKey}" setting.initialize = -> scope.offsets = [] for offsetValue in (scope.initialOffsets || []) scope.offsets.push offsetValue scope.offsetFormula = "" scope.periodWord = ImpacUtilities.getPeriodWord(scope.period) scope.placeholder = placeholder(scope.period || 'MONTHLY') setting.toMetadata = -> metadata = { offset: {} } metadata.offset[scope.offsetsKey] = scope.offsets metadata scope.addOffset = -> result = computedFormula() scope.offsets.push(result) if result scope.offsetFormula = "" scope.removeOffset = (offsetIndex) -> scope.offsets.splice(offsetIndex, 1) scope.addOffsetOnEnter = (event) -> scope.addOffset() if event.keyCode == 13 placeholder = (inputPeriod) -> return scope.textPlaceholder if scope.textPlaceholder? period = inputPeriod.charAt(0).toUpperCase() + inputPeriod.slice(1).toLowerCase() "#{period} adjustment" computedFormula = -> eval(scope.offsetFormula) if scope.offsetFormula.match(authorized_regex) w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
64766
module = angular.module('impac.components.widgets-settings.offsets',[]) module.directive('settingOffsets', ($templateCache, ImpacUtilities) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' offsetsKey: '@' initialOffsets: '=' currency: '=' intervalsCount: '=' period: '=' showIntervalsMult: '=' textPlaceholder: '@?' }, template: $templateCache.get('widgets-settings/offsets.tmpl.html'), link: (scope) -> w = scope.parentWidget authorized_regex = new RegExp("^(\\{|\\d|\\}|\\/|\\+|-|\\*|\\(|\\)|\\s|\\.)*$") setting = key: "<KEY>scope.offsetsKey}" setting.initialize = -> scope.offsets = [] for offsetValue in (scope.initialOffsets || []) scope.offsets.push offsetValue scope.offsetFormula = "" scope.periodWord = ImpacUtilities.getPeriodWord(scope.period) scope.placeholder = placeholder(scope.period || 'MONTHLY') setting.toMetadata = -> metadata = { offset: {} } metadata.offset[scope.offsetsKey] = scope.offsets metadata scope.addOffset = -> result = computedFormula() scope.offsets.push(result) if result scope.offsetFormula = "" scope.removeOffset = (offsetIndex) -> scope.offsets.splice(offsetIndex, 1) scope.addOffsetOnEnter = (event) -> scope.addOffset() if event.keyCode == 13 placeholder = (inputPeriod) -> return scope.textPlaceholder if scope.textPlaceholder? period = inputPeriod.charAt(0).toUpperCase() + inputPeriod.slice(1).toLowerCase() "#{period} adjustment" computedFormula = -> eval(scope.offsetFormula) if scope.offsetFormula.match(authorized_regex) w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
true
module = angular.module('impac.components.widgets-settings.offsets',[]) module.directive('settingOffsets', ($templateCache, ImpacUtilities) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' offsetsKey: '@' initialOffsets: '=' currency: '=' intervalsCount: '=' period: '=' showIntervalsMult: '=' textPlaceholder: '@?' }, template: $templateCache.get('widgets-settings/offsets.tmpl.html'), link: (scope) -> w = scope.parentWidget authorized_regex = new RegExp("^(\\{|\\d|\\}|\\/|\\+|-|\\*|\\(|\\)|\\s|\\.)*$") setting = key: "PI:KEY:<KEY>END_PIscope.offsetsKey}" setting.initialize = -> scope.offsets = [] for offsetValue in (scope.initialOffsets || []) scope.offsets.push offsetValue scope.offsetFormula = "" scope.periodWord = ImpacUtilities.getPeriodWord(scope.period) scope.placeholder = placeholder(scope.period || 'MONTHLY') setting.toMetadata = -> metadata = { offset: {} } metadata.offset[scope.offsetsKey] = scope.offsets metadata scope.addOffset = -> result = computedFormula() scope.offsets.push(result) if result scope.offsetFormula = "" scope.removeOffset = (offsetIndex) -> scope.offsets.splice(offsetIndex, 1) scope.addOffsetOnEnter = (event) -> scope.addOffset() if event.keyCode == 13 placeholder = (inputPeriod) -> return scope.textPlaceholder if scope.textPlaceholder? period = inputPeriod.charAt(0).toUpperCase() + inputPeriod.slice(1).toLowerCase() "#{period} adjustment" computedFormula = -> eval(scope.offsetFormula) if scope.offsetFormula.match(authorized_regex) w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
[ { "context": "E = \"test/resources/logo.png\"\n PUBLIC_ID = \"api_test\"\n TIMEOUT_SHORT = 5000\n TIMEOUT_MEDIUM ", "end": 396, "score": 0.5211643576622009, "start": 393, "tag": "KEY", "value": "api" }, { "context": "ry.v2.uploader.upload IMAGE_FILE, public_id: \"api_test5...
countProject/countproject_temp/node_modules/keystone/node_modules/cloudinary/test/apispec.coffee
edagarli/countProjects
0
dotenv = require('dotenv') dotenv.load() expect = require("expect.js") cloudinary = require("../cloudinary") utils = require("../lib/utils") _ = require("lodash") Q = require('q') fs = require('fs') describe "api", -> return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret? IMAGE_FILE = "test/resources/logo.png" PUBLIC_ID = "api_test" TIMEOUT_SHORT = 5000 TIMEOUT_MEDIUM = 20000 TIMEOUT_LONG = 50000 find_by_attr = (elements, attr, value) -> for element in elements return element if element[attr] == value undefined uploaded = [] uploadedRaw = [] ###* # Upload an image to be tested on. # @callback the callback recieves the public_id of the uploaded image ### upload_image = (callback)-> cloudinary.v2.uploader.upload IMAGE_FILE, (error, result) -> expect(error).to.be undefined expect(result).to.be.an(Object) uploaded.push(result.public_id) callback(result) before (done) -> @timeout 0 @timestamp_tag = "api_test_tag_" + cloudinary.utils.timestamp() uploaded = [] cloudinary.v2.api.delete_resources [PUBLIC_ID, "api_test1", "api_test2"], (error, result)-> Q.all [ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: PUBLIC_ID, tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: "api_test2", tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.api.delete_transformation("api_test_transformation") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset1") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset2") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset3") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset4")] .finally -> done() after (done) -> @timeout TIMEOUT_LONG operations = [] operations.push cloudinary.v2.api.delete_resources_by_tag @timestamp_tag, keep_original: false unless _.isEmpty(uploaded) operations.push cloudinary.v2.api.delete_resources uploaded unless _.isEmpty(uploadedRaw) operations.push cloudinary.v2.api.delete_resources uploadedRaw, resource_type: "raw" Q.allSettled(operations) .finally ()-> done() describe "resources", ()-> it "should allow listing resource_types", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resource_types (error, result) -> return done(new Error error.message) if error? expect(result.resource_types).to.contain("image") done() it "should allow listing resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).not.to.eql(undefined) expect(resource.type).to.eql("upload") done() it "should allow listing resources with cursor", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources max_results: 1, (error, result) -> return done(new Error error.message) if error? expect(result.resources).to.have.length 1 expect(result.next_cursor).not.to.eql(undefined) cloudinary.v2.api.resources max_results: 1, next_cursor: result.next_cursor, (error2, result2) -> return done(new Error error2.message) if error2? expect(result2.resources).to.have.length 1 expect(result2.next_cursor).not.to.eql(undefined) expect(result.resources[0].public_id).not.to.eql result2.resources[0].public_id done() it "should allow listing resources by type", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources type: "upload", (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).to.be.an(Object) expect(resource.type).to.eql("upload") done() it "should allow listing resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources type: "upload", prefix: PUBLIC_ID, (error, result) -> return done(new Error error.message) if error? public_ids = (resource.public_id for resource in result.resources) expect(public_ids).to.contain(PUBLIC_ID) expect(public_ids).to.contain("api_test2") done() it "should allow listing resources by tag", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag "api_test_tag", context: true, tags: true, (error, result) -> return done(new Error error.message) if error? expect(result.resources.map((e) -> e.public_id)).to.contain(PUBLIC_ID) .and.contain("api_test2") expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> if e.context? then e.context.custom.key else null)).to.contain("value") done() it "should allow listing resources by public ids", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_ids [PUBLIC_ID, "api_test2"], context: true, tags: true, (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", PUBLIC_ID) expect(result.resources.map((e) -> e.public_id).sort()).to.eql([PUBLIC_ID,"api_test2"]) expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> e.context.custom.key)).to.contain("value") done() it "should allow listing resources specifying direction", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "asc", (error, result) => return done(new Error error.message) if error? asc = (resource.public_id for resource in result.resources) cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "desc", (error, result) -> return done(new Error error.message) if error? desc = (resource.public_id for resource in result.resources) expect(asc.reverse()).to.eql(desc) done() it "should allow listing resources by start_at", (done) -> @timeout TIMEOUT_MEDIUM start_at = null setTimeout -> start_at = new Date() setTimeout -> cloudinary.v2.uploader.upload IMAGE_FILE, (error, response) -> cloudinary.v2.api.resources type: "upload", start_at: start_at, direction: "asc", (error, resources_response) -> expect(resources_response.resources).to.have.length(1) expect(resources_response.resources[0].public_id).to.eql(response.public_id) done() ,2000 ,2000 it "should allow get resource metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], eager: [width: 100, crop: "scale"], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.public_id).to.eql(public_id) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) done() describe "delete", ()-> it "should allow deleting derived resource", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, eager: [width: 101, crop: "scale"], (error, r) -> return done(new Error error.message) if error? public_id = r.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) derived_resource_id = resource.derived[0].id cloudinary.v2.api.delete_derived_resources derived_resource_id, (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.derived).to.have.length(0) done() it "should allow deleting resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test3", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources ["apit_test", "api_test2", "api_test3"], (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test_by_prefix", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test_by_prefix", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources_by_prefix "api_test_by", () -> cloudinary.v2.api.resource "api_test_by_prefix", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test4", tags: ["api_test_tag_for_delete"] , (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, resource) -> expect(resource).to.be.ok() cloudinary.v2.api.delete_resources_by_tag "api_test_tag_for_delete", (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() describe "tags", ()-> it "should allow listing tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix ", (done) => @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test", (error, result) => return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix if not found", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test_no_such_tag", (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.be.empty() done() describe "transformations", ()-> it "should allow listing transformations", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformations (error, result) -> return done(new Error error.message) if error? transformation = find_by_attr(result.transformations, "name", "c_scale,w_100") expect(transformation).not.to.eql(undefined) expect(transformation.used).to.be.ok done() it "should allow getting transformation metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow getting transformation metadata by info", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation {crop: "scale", width: 100}, (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow updating transformation allowed_for_strict", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: true}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: false}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).not.to.be.ok done() it "should allow creating named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation", {crop: "scale", width: 102}, () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok expect(transformation.info).to.eql([crop: "scale", width: 102]) expect(transformation.used).not.to.be.ok done() it "should allow unsafe update of named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation3", {crop: "scale", width: 102}, () -> cloudinary.v2.api.update_transformation "api_test_transformation3", {unsafe_update: {crop: "scale", width: 103}}, () -> cloudinary.v2.api.transformation "api_test_transformation3", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 103]) expect(transformation.used).not.to.be.ok done() it "should allow deleting named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.delete_transformation "api_test_transformation", () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(error.http_code).to.eql 404 done() it "should allow deleting implicit transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).to.be.an(Object) cloudinary.v2.api.delete_transformation "c_scale,w_100", () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(error.http_code).to.eql 404 done() describe "upload_preset", ()-> it "should allow creating and listing upload_presets", (done) -> @timeout TIMEOUT_MEDIUM create_names = ["api_test_upload_preset3", "api_test_upload_preset2", "api_test_upload_preset1"] delete_names = [] after_delete = -> delete_names.pop() done() if delete_names.length == 0 validate_presets = -> cloudinary.v2.api.upload_presets (error, response) -> expect(response.presets.slice(0,3).map((p) -> p.name)).to.eql(delete_names) delete_names.forEach((name) -> cloudinary.v2.api.delete_upload_preset name, after_delete) after_create = -> if create_names.length > 0 name = create_names.pop() delete_names.unshift(name) cloudinary.v2.api.create_upload_preset name: name , folder: "folder", after_create else validate_presets() after_create() it "should allow getting a single upload_preset", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset unsigned: true, folder: "folder", transformation: {width: 100, crop: "scale"}, tags: ["a","b","c"], context: {a: "b", c: "d"}, (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings.folder).to.eql("folder") expect(preset.settings.transformation).to.eql([{width: 100, crop: "scale"}]) expect(preset.settings.context).to.eql({a: "b", c: "d"}) expect(preset.settings.tags).to.eql(["a","b","c"]) cloudinary.v2.api.delete_upload_preset name, -> done() it "should allow deleting upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset name: "api_test_upload_preset4", folder: "folder", (error, preset) -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.delete_upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", (error, result) -> expect(error.message).to.contain "Can't find" done() it "should allow updating upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset folder: "folder", (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> cloudinary.v2.api.update_upload_preset name, utils.merge(preset.settings, {colors: true, unsigned: true, disallow_public_id: true}), (error, preset) -> cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings).to.eql(folder: "folder", colors: true, disallow_public_id: true) cloudinary.v2.api.delete_upload_preset name, -> done() it "should support the usage API call", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.usage (error, usage) -> expect(usage.last_update).not.to.eql null done() it "should allow deleting all derived resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test5", eager: {transformation: {width: 101, crop: "scale"}}, (error, upload_result) -> cloudinary.v2.api.resource "api_test5", (error, resource) -> return done(new Error error.message) if error? expect(resource).to.be.an(Object) expect(resource.derived).not.to.be.empty() # Prepare to loop until no more resources to delete delete_all = (next, callback)-> options = {keep_original: yes} options.next_cursor = next if next? cloudinary.v2.api.delete_all_resources options, (error, delete_result) -> return done(new Error error.message) if error? if delete_result.next_cursor? delete_all(delete_result.next_cursor, callback) else callback() # execute loop delete_all undefined, ()-> cloudinary.v2.api.resource "api_test5", (error, new_resource) -> return done(new Error error.message) if error? expect(new_resource.derived).to.be.empty() done() describe "update", ()-> it "should support setting manual moderation status", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, moderation: "manual", (error, upload_result) -> uploaded.push upload_result.public_id cloudinary.v2.api.update upload_result.public_id, moderation_status: "approved", (error, api_result) -> expect(api_result.moderation[0].status).to.eql("approved") done() it "should support requesting ocr info", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, ocr: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting raw conversion", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, raw_convert: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting categorization", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, categorization: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting detection", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, detection: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting background_removal", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, background_removal: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting similarity_search", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, similarity_search: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting auto_tagging", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, auto_tagging: "illegal", (error, api_result) -> expect(error.message).to.contain "Must use" done() it "should support listing by moderation kind and value", (done) -> @timeout TIMEOUT_MEDIUM ids = [] api_results =[] lists = {} after_listing = (list) -> (error, list_result) -> lists[list] = list_result.resources.map((r) -> r.public_id) if _.keys(lists).length == 3 expect(lists.approved).to.contain(ids[0]) expect(lists.approved).not.to.contain(ids[1]) expect(lists.approved).not.to.contain(ids[2]) expect(lists.rejected).to.contain(ids[1]) expect(lists.rejected).not.to.contain(ids[0]) expect(lists.rejected).not.to.contain(ids[2]) expect(lists.pending).to.contain(ids[2]) expect(lists.pending).not.to.contain(ids[0]) expect(lists.pending).not.to.contain(ids[1]) done() after_update = (error, api_result) -> api_results.push(api_result) if api_results.length == 2 cloudinary.v2.api.resources_by_moderation("manual", "approved", max_results: 1000, moderations: true, after_listing("approved")) cloudinary.v2.api.resources_by_moderation("manual", "rejected", max_results: 1000, moderations: true, after_listing("rejected")) cloudinary.v2.api.resources_by_moderation("manual", "pending", max_results: 1000, moderations: true, after_listing("pending")) after_upload = (error, upload_result) -> ids.push(upload_result.public_id) if ids.length == 3 cloudinary.v2.api.update ids[0], moderation_status: "approved", after_update cloudinary.v2.api.update ids[1], moderation_status: "rejected", after_update cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) # For this test to work, "Auto-create folders" should be enabled in the Upload Settings. # Replace `it` with `it.skip` below if you want to disable it. it "should list folders in cloudinary", (done)-> @timeout TIMEOUT_LONG Q.all([ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder2/item' ) ]).then((results)-> Q.all([ cloudinary.v2.api.root_folders(), cloudinary.v2.api.sub_folders('test_folder1') ]) ).then((results)-> root= results[0] root_folders = (folder.name for folder in root.folders) sub_1 = results[1] expect(root_folders).to.contain('test_folder1') expect(root_folders).to.contain('test_folder2') expect(sub_1.folders[0].path).to.eql('test_folder1/test_subfolder1') expect(sub_1.folders[1].path).to.eql('test_folder1/test_subfolder2') cloudinary.v2.api.sub_folders('test_folder_not_exists') ).then((result)-> console.log('error test_folder_not_exists should not pass to "then" handler but "catch"') expect(true).to.eql(false) ).catch((err)-> expect(err.error.message).to.eql('Can\'t find folder with path test_folder_not_exists') done() )
1395
dotenv = require('dotenv') dotenv.load() expect = require("expect.js") cloudinary = require("../cloudinary") utils = require("../lib/utils") _ = require("lodash") Q = require('q') fs = require('fs') describe "api", -> return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret? IMAGE_FILE = "test/resources/logo.png" PUBLIC_ID = "<KEY>_test" TIMEOUT_SHORT = 5000 TIMEOUT_MEDIUM = 20000 TIMEOUT_LONG = 50000 find_by_attr = (elements, attr, value) -> for element in elements return element if element[attr] == value undefined uploaded = [] uploadedRaw = [] ###* # Upload an image to be tested on. # @callback the callback recieves the public_id of the uploaded image ### upload_image = (callback)-> cloudinary.v2.uploader.upload IMAGE_FILE, (error, result) -> expect(error).to.be undefined expect(result).to.be.an(Object) uploaded.push(result.public_id) callback(result) before (done) -> @timeout 0 @timestamp_tag = "api_test_tag_" + cloudinary.utils.timestamp() uploaded = [] cloudinary.v2.api.delete_resources [PUBLIC_ID, "api_test1", "api_test2"], (error, result)-> Q.all [ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: PUBLIC_ID, tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: "api_test2", tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.api.delete_transformation("api_test_transformation") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset1") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset2") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset3") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset4")] .finally -> done() after (done) -> @timeout TIMEOUT_LONG operations = [] operations.push cloudinary.v2.api.delete_resources_by_tag @timestamp_tag, keep_original: false unless _.isEmpty(uploaded) operations.push cloudinary.v2.api.delete_resources uploaded unless _.isEmpty(uploadedRaw) operations.push cloudinary.v2.api.delete_resources uploadedRaw, resource_type: "raw" Q.allSettled(operations) .finally ()-> done() describe "resources", ()-> it "should allow listing resource_types", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resource_types (error, result) -> return done(new Error error.message) if error? expect(result.resource_types).to.contain("image") done() it "should allow listing resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).not.to.eql(undefined) expect(resource.type).to.eql("upload") done() it "should allow listing resources with cursor", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources max_results: 1, (error, result) -> return done(new Error error.message) if error? expect(result.resources).to.have.length 1 expect(result.next_cursor).not.to.eql(undefined) cloudinary.v2.api.resources max_results: 1, next_cursor: result.next_cursor, (error2, result2) -> return done(new Error error2.message) if error2? expect(result2.resources).to.have.length 1 expect(result2.next_cursor).not.to.eql(undefined) expect(result.resources[0].public_id).not.to.eql result2.resources[0].public_id done() it "should allow listing resources by type", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources type: "upload", (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).to.be.an(Object) expect(resource.type).to.eql("upload") done() it "should allow listing resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources type: "upload", prefix: PUBLIC_ID, (error, result) -> return done(new Error error.message) if error? public_ids = (resource.public_id for resource in result.resources) expect(public_ids).to.contain(PUBLIC_ID) expect(public_ids).to.contain("api_test2") done() it "should allow listing resources by tag", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag "api_test_tag", context: true, tags: true, (error, result) -> return done(new Error error.message) if error? expect(result.resources.map((e) -> e.public_id)).to.contain(PUBLIC_ID) .and.contain("api_test2") expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> if e.context? then e.context.custom.key else null)).to.contain("value") done() it "should allow listing resources by public ids", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_ids [PUBLIC_ID, "api_test2"], context: true, tags: true, (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", PUBLIC_ID) expect(result.resources.map((e) -> e.public_id).sort()).to.eql([PUBLIC_ID,"api_test2"]) expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> e.context.custom.key)).to.contain("value") done() it "should allow listing resources specifying direction", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "asc", (error, result) => return done(new Error error.message) if error? asc = (resource.public_id for resource in result.resources) cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "desc", (error, result) -> return done(new Error error.message) if error? desc = (resource.public_id for resource in result.resources) expect(asc.reverse()).to.eql(desc) done() it "should allow listing resources by start_at", (done) -> @timeout TIMEOUT_MEDIUM start_at = null setTimeout -> start_at = new Date() setTimeout -> cloudinary.v2.uploader.upload IMAGE_FILE, (error, response) -> cloudinary.v2.api.resources type: "upload", start_at: start_at, direction: "asc", (error, resources_response) -> expect(resources_response.resources).to.have.length(1) expect(resources_response.resources[0].public_id).to.eql(response.public_id) done() ,2000 ,2000 it "should allow get resource metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], eager: [width: 100, crop: "scale"], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.public_id).to.eql(public_id) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) done() describe "delete", ()-> it "should allow deleting derived resource", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, eager: [width: 101, crop: "scale"], (error, r) -> return done(new Error error.message) if error? public_id = r.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) derived_resource_id = resource.derived[0].id cloudinary.v2.api.delete_derived_resources derived_resource_id, (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.derived).to.have.length(0) done() it "should allow deleting resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test3", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources ["apit_test", "api_test2", "api_test3"], (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test_by_prefix", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test_by_prefix", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources_by_prefix "api_test_by", () -> cloudinary.v2.api.resource "api_test_by_prefix", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test4", tags: ["api_test_tag_for_delete"] , (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, resource) -> expect(resource).to.be.ok() cloudinary.v2.api.delete_resources_by_tag "api_test_tag_for_delete", (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() describe "tags", ()-> it "should allow listing tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix ", (done) => @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test", (error, result) => return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix if not found", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test_no_such_tag", (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.be.empty() done() describe "transformations", ()-> it "should allow listing transformations", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformations (error, result) -> return done(new Error error.message) if error? transformation = find_by_attr(result.transformations, "name", "c_scale,w_100") expect(transformation).not.to.eql(undefined) expect(transformation.used).to.be.ok done() it "should allow getting transformation metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow getting transformation metadata by info", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation {crop: "scale", width: 100}, (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow updating transformation allowed_for_strict", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: true}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: false}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).not.to.be.ok done() it "should allow creating named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation", {crop: "scale", width: 102}, () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok expect(transformation.info).to.eql([crop: "scale", width: 102]) expect(transformation.used).not.to.be.ok done() it "should allow unsafe update of named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation3", {crop: "scale", width: 102}, () -> cloudinary.v2.api.update_transformation "api_test_transformation3", {unsafe_update: {crop: "scale", width: 103}}, () -> cloudinary.v2.api.transformation "api_test_transformation3", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 103]) expect(transformation.used).not.to.be.ok done() it "should allow deleting named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.delete_transformation "api_test_transformation", () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(error.http_code).to.eql 404 done() it "should allow deleting implicit transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).to.be.an(Object) cloudinary.v2.api.delete_transformation "c_scale,w_100", () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(error.http_code).to.eql 404 done() describe "upload_preset", ()-> it "should allow creating and listing upload_presets", (done) -> @timeout TIMEOUT_MEDIUM create_names = ["api_test_upload_preset3", "api_test_upload_preset2", "api_test_upload_preset1"] delete_names = [] after_delete = -> delete_names.pop() done() if delete_names.length == 0 validate_presets = -> cloudinary.v2.api.upload_presets (error, response) -> expect(response.presets.slice(0,3).map((p) -> p.name)).to.eql(delete_names) delete_names.forEach((name) -> cloudinary.v2.api.delete_upload_preset name, after_delete) after_create = -> if create_names.length > 0 name = create_names.pop() delete_names.unshift(name) cloudinary.v2.api.create_upload_preset name: name , folder: "folder", after_create else validate_presets() after_create() it "should allow getting a single upload_preset", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset unsigned: true, folder: "folder", transformation: {width: 100, crop: "scale"}, tags: ["a","b","c"], context: {a: "b", c: "d"}, (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings.folder).to.eql("folder") expect(preset.settings.transformation).to.eql([{width: 100, crop: "scale"}]) expect(preset.settings.context).to.eql({a: "b", c: "d"}) expect(preset.settings.tags).to.eql(["a","b","c"]) cloudinary.v2.api.delete_upload_preset name, -> done() it "should allow deleting upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset name: "api_test_upload_preset4", folder: "folder", (error, preset) -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.delete_upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", (error, result) -> expect(error.message).to.contain "Can't find" done() it "should allow updating upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset folder: "folder", (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> cloudinary.v2.api.update_upload_preset name, utils.merge(preset.settings, {colors: true, unsigned: true, disallow_public_id: true}), (error, preset) -> cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings).to.eql(folder: "folder", colors: true, disallow_public_id: true) cloudinary.v2.api.delete_upload_preset name, -> done() it "should support the usage API call", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.usage (error, usage) -> expect(usage.last_update).not.to.eql null done() it "should allow deleting all derived resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test5", eager: {transformation: {width: 101, crop: "scale"}}, (error, upload_result) -> cloudinary.v2.api.resource "api_test5", (error, resource) -> return done(new Error error.message) if error? expect(resource).to.be.an(Object) expect(resource.derived).not.to.be.empty() # Prepare to loop until no more resources to delete delete_all = (next, callback)-> options = {keep_original: yes} options.next_cursor = next if next? cloudinary.v2.api.delete_all_resources options, (error, delete_result) -> return done(new Error error.message) if error? if delete_result.next_cursor? delete_all(delete_result.next_cursor, callback) else callback() # execute loop delete_all undefined, ()-> cloudinary.v2.api.resource "api_test5", (error, new_resource) -> return done(new Error error.message) if error? expect(new_resource.derived).to.be.empty() done() describe "update", ()-> it "should support setting manual moderation status", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, moderation: "manual", (error, upload_result) -> uploaded.push upload_result.public_id cloudinary.v2.api.update upload_result.public_id, moderation_status: "approved", (error, api_result) -> expect(api_result.moderation[0].status).to.eql("approved") done() it "should support requesting ocr info", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, ocr: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting raw conversion", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, raw_convert: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting categorization", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, categorization: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting detection", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, detection: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting background_removal", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, background_removal: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting similarity_search", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, similarity_search: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting auto_tagging", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, auto_tagging: "illegal", (error, api_result) -> expect(error.message).to.contain "Must use" done() it "should support listing by moderation kind and value", (done) -> @timeout TIMEOUT_MEDIUM ids = [] api_results =[] lists = {} after_listing = (list) -> (error, list_result) -> lists[list] = list_result.resources.map((r) -> r.public_id) if _.keys(lists).length == 3 expect(lists.approved).to.contain(ids[0]) expect(lists.approved).not.to.contain(ids[1]) expect(lists.approved).not.to.contain(ids[2]) expect(lists.rejected).to.contain(ids[1]) expect(lists.rejected).not.to.contain(ids[0]) expect(lists.rejected).not.to.contain(ids[2]) expect(lists.pending).to.contain(ids[2]) expect(lists.pending).not.to.contain(ids[0]) expect(lists.pending).not.to.contain(ids[1]) done() after_update = (error, api_result) -> api_results.push(api_result) if api_results.length == 2 cloudinary.v2.api.resources_by_moderation("manual", "approved", max_results: 1000, moderations: true, after_listing("approved")) cloudinary.v2.api.resources_by_moderation("manual", "rejected", max_results: 1000, moderations: true, after_listing("rejected")) cloudinary.v2.api.resources_by_moderation("manual", "pending", max_results: 1000, moderations: true, after_listing("pending")) after_upload = (error, upload_result) -> ids.push(upload_result.public_id) if ids.length == 3 cloudinary.v2.api.update ids[0], moderation_status: "approved", after_update cloudinary.v2.api.update ids[1], moderation_status: "rejected", after_update cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) # For this test to work, "Auto-create folders" should be enabled in the Upload Settings. # Replace `it` with `it.skip` below if you want to disable it. it "should list folders in cloudinary", (done)-> @timeout TIMEOUT_LONG Q.all([ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder2/item' ) ]).then((results)-> Q.all([ cloudinary.v2.api.root_folders(), cloudinary.v2.api.sub_folders('test_folder1') ]) ).then((results)-> root= results[0] root_folders = (folder.name for folder in root.folders) sub_1 = results[1] expect(root_folders).to.contain('test_folder1') expect(root_folders).to.contain('test_folder2') expect(sub_1.folders[0].path).to.eql('test_folder1/test_subfolder1') expect(sub_1.folders[1].path).to.eql('test_folder1/test_subfolder2') cloudinary.v2.api.sub_folders('test_folder_not_exists') ).then((result)-> console.log('error test_folder_not_exists should not pass to "then" handler but "catch"') expect(true).to.eql(false) ).catch((err)-> expect(err.error.message).to.eql('Can\'t find folder with path test_folder_not_exists') done() )
true
dotenv = require('dotenv') dotenv.load() expect = require("expect.js") cloudinary = require("../cloudinary") utils = require("../lib/utils") _ = require("lodash") Q = require('q') fs = require('fs') describe "api", -> return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret? IMAGE_FILE = "test/resources/logo.png" PUBLIC_ID = "PI:KEY:<KEY>END_PI_test" TIMEOUT_SHORT = 5000 TIMEOUT_MEDIUM = 20000 TIMEOUT_LONG = 50000 find_by_attr = (elements, attr, value) -> for element in elements return element if element[attr] == value undefined uploaded = [] uploadedRaw = [] ###* # Upload an image to be tested on. # @callback the callback recieves the public_id of the uploaded image ### upload_image = (callback)-> cloudinary.v2.uploader.upload IMAGE_FILE, (error, result) -> expect(error).to.be undefined expect(result).to.be.an(Object) uploaded.push(result.public_id) callback(result) before (done) -> @timeout 0 @timestamp_tag = "api_test_tag_" + cloudinary.utils.timestamp() uploaded = [] cloudinary.v2.api.delete_resources [PUBLIC_ID, "api_test1", "api_test2"], (error, result)-> Q.all [ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: PUBLIC_ID, tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: "api_test2", tags: ["api_test_tag", @timestamp_tag], context: "key=value", eager: [width: 100, crop: "scale"]) cloudinary.v2.api.delete_transformation("api_test_transformation") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset1") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset2") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset3") cloudinary.v2.api.delete_upload_preset("api_test_upload_preset4")] .finally -> done() after (done) -> @timeout TIMEOUT_LONG operations = [] operations.push cloudinary.v2.api.delete_resources_by_tag @timestamp_tag, keep_original: false unless _.isEmpty(uploaded) operations.push cloudinary.v2.api.delete_resources uploaded unless _.isEmpty(uploadedRaw) operations.push cloudinary.v2.api.delete_resources uploadedRaw, resource_type: "raw" Q.allSettled(operations) .finally ()-> done() describe "resources", ()-> it "should allow listing resource_types", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resource_types (error, result) -> return done(new Error error.message) if error? expect(result.resource_types).to.contain("image") done() it "should allow listing resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).not.to.eql(undefined) expect(resource.type).to.eql("upload") done() it "should allow listing resources with cursor", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources max_results: 1, (error, result) -> return done(new Error error.message) if error? expect(result.resources).to.have.length 1 expect(result.next_cursor).not.to.eql(undefined) cloudinary.v2.api.resources max_results: 1, next_cursor: result.next_cursor, (error2, result2) -> return done(new Error error2.message) if error2? expect(result2.resources).to.have.length 1 expect(result2.next_cursor).not.to.eql(undefined) expect(result.resources[0].public_id).not.to.eql result2.resources[0].public_id done() it "should allow listing resources by type", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resources type: "upload", (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", public_id) expect(resource).to.be.an(Object) expect(resource.type).to.eql("upload") done() it "should allow listing resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources type: "upload", prefix: PUBLIC_ID, (error, result) -> return done(new Error error.message) if error? public_ids = (resource.public_id for resource in result.resources) expect(public_ids).to.contain(PUBLIC_ID) expect(public_ids).to.contain("api_test2") done() it "should allow listing resources by tag", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag "api_test_tag", context: true, tags: true, (error, result) -> return done(new Error error.message) if error? expect(result.resources.map((e) -> e.public_id)).to.contain(PUBLIC_ID) .and.contain("api_test2") expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> if e.context? then e.context.custom.key else null)).to.contain("value") done() it "should allow listing resources by public ids", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_ids [PUBLIC_ID, "api_test2"], context: true, tags: true, (error, result) -> return done(new Error error.message) if error? resource = find_by_attr(result.resources, "public_id", PUBLIC_ID) expect(result.resources.map((e) -> e.public_id).sort()).to.eql([PUBLIC_ID,"api_test2"]) expect(result.resources.map((e) -> e.tags[0])).to.contain("api_test_tag") expect(result.resources.map((e) -> e.context.custom.key)).to.contain("value") done() it "should allow listing resources specifying direction", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "asc", (error, result) => return done(new Error error.message) if error? asc = (resource.public_id for resource in result.resources) cloudinary.v2.api.resources_by_tag @timestamp_tag, type: "upload", direction: "desc", (error, result) -> return done(new Error error.message) if error? desc = (resource.public_id for resource in result.resources) expect(asc.reverse()).to.eql(desc) done() it "should allow listing resources by start_at", (done) -> @timeout TIMEOUT_MEDIUM start_at = null setTimeout -> start_at = new Date() setTimeout -> cloudinary.v2.uploader.upload IMAGE_FILE, (error, response) -> cloudinary.v2.api.resources type: "upload", start_at: start_at, direction: "asc", (error, resources_response) -> expect(resources_response.resources).to.have.length(1) expect(resources_response.resources[0].public_id).to.eql(response.public_id) done() ,2000 ,2000 it "should allow get resource metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, tags: ["api_test_tag", @timestamp_tag], eager: [width: 100, crop: "scale"], (error, result)-> done(new Error error.message) if error? public_id = result.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.public_id).to.eql(public_id) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) done() describe "delete", ()-> it "should allow deleting derived resource", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, eager: [width: 101, crop: "scale"], (error, r) -> return done(new Error error.message) if error? public_id = r.public_id uploaded.push public_id cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.bytes).to.eql(3381) expect(resource.derived).to.have.length(1) derived_resource_id = resource.derived[0].id cloudinary.v2.api.delete_derived_resources derived_resource_id, (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource public_id, (error, resource) -> return done(new Error error.message) if error? expect(resource).not.to.eql(undefined) expect(resource.derived).to.have.length(0) done() it "should allow deleting resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test3", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources ["apit_test", "api_test2", "api_test3"], (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test3", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by prefix", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test_by_prefix", (error, r) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test_by_prefix", (error, resource) -> expect(resource).not.to.eql(undefined) cloudinary.v2.api.delete_resources_by_prefix "api_test_by", () -> cloudinary.v2.api.resource "api_test_by_prefix", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() it "should allow deleting resources by tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test4", tags: ["api_test_tag_for_delete"] , (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, resource) -> expect(resource).to.be.ok() cloudinary.v2.api.delete_resources_by_tag "api_test_tag_for_delete", (error, result) -> return done(new Error error.message) if error? cloudinary.v2.api.resource "api_test4", (error, result) -> expect(error).to.be.an(Object) expect(error.http_code).to.eql 404 done() describe "tags", ()-> it "should allow listing tags", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix ", (done) => @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test", (error, result) => return done(new Error error.message) if error? expect(result.tags).to.contain("api_test_tag") done() it "should allow listing tag by prefix if not found", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.tags prefix: "api_test_no_such_tag", (error, result) -> return done(new Error error.message) if error? expect(result.tags).to.be.empty() done() describe "transformations", ()-> it "should allow listing transformations", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformations (error, result) -> return done(new Error error.message) if error? transformation = find_by_attr(result.transformations, "name", "c_scale,w_100") expect(transformation).not.to.eql(undefined) expect(transformation.used).to.be.ok done() it "should allow getting transformation metadata", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow getting transformation metadata by info", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation {crop: "scale", width: 100}, (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 100]) done() it "should allow updating transformation allowed_for_strict", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: true}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok cloudinary.v2.api.update_transformation "c_scale,w_100", {allowed_for_strict: false}, () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).not.to.be.ok done() it "should allow creating named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation", {crop: "scale", width: 102}, () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.allowed_for_strict).to.be.ok expect(transformation.info).to.eql([crop: "scale", width: 102]) expect(transformation.used).not.to.be.ok done() it "should allow unsafe update of named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_transformation "api_test_transformation3", {crop: "scale", width: 102}, () -> cloudinary.v2.api.update_transformation "api_test_transformation3", {unsafe_update: {crop: "scale", width: 103}}, () -> cloudinary.v2.api.transformation "api_test_transformation3", (error, transformation) -> expect(transformation).not.to.eql(undefined) expect(transformation.info).to.eql([crop: "scale", width: 103]) expect(transformation.used).not.to.be.ok done() it "should allow deleting named transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.delete_transformation "api_test_transformation", () -> cloudinary.v2.api.transformation "api_test_transformation", (error, transformation) -> expect(error.http_code).to.eql 404 done() it "should allow deleting implicit transformation", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(transformation).to.be.an(Object) cloudinary.v2.api.delete_transformation "c_scale,w_100", () -> cloudinary.v2.api.transformation "c_scale,w_100", (error, transformation) -> expect(error.http_code).to.eql 404 done() describe "upload_preset", ()-> it "should allow creating and listing upload_presets", (done) -> @timeout TIMEOUT_MEDIUM create_names = ["api_test_upload_preset3", "api_test_upload_preset2", "api_test_upload_preset1"] delete_names = [] after_delete = -> delete_names.pop() done() if delete_names.length == 0 validate_presets = -> cloudinary.v2.api.upload_presets (error, response) -> expect(response.presets.slice(0,3).map((p) -> p.name)).to.eql(delete_names) delete_names.forEach((name) -> cloudinary.v2.api.delete_upload_preset name, after_delete) after_create = -> if create_names.length > 0 name = create_names.pop() delete_names.unshift(name) cloudinary.v2.api.create_upload_preset name: name , folder: "folder", after_create else validate_presets() after_create() it "should allow getting a single upload_preset", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset unsigned: true, folder: "folder", transformation: {width: 100, crop: "scale"}, tags: ["a","b","c"], context: {a: "b", c: "d"}, (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings.folder).to.eql("folder") expect(preset.settings.transformation).to.eql([{width: 100, crop: "scale"}]) expect(preset.settings.context).to.eql({a: "b", c: "d"}) expect(preset.settings.tags).to.eql(["a","b","c"]) cloudinary.v2.api.delete_upload_preset name, -> done() it "should allow deleting upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset name: "api_test_upload_preset4", folder: "folder", (error, preset) -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.delete_upload_preset "api_test_upload_preset4", -> cloudinary.v2.api.upload_preset "api_test_upload_preset4", (error, result) -> expect(error.message).to.contain "Can't find" done() it "should allow updating upload_presets", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.create_upload_preset folder: "folder", (error, preset) -> name = preset.name cloudinary.v2.api.upload_preset name, (error, preset) -> cloudinary.v2.api.update_upload_preset name, utils.merge(preset.settings, {colors: true, unsigned: true, disallow_public_id: true}), (error, preset) -> cloudinary.v2.api.upload_preset name, (error, preset) -> expect(preset.name).to.eql(name) expect(preset.unsigned).to.eql(true) expect(preset.settings).to.eql(folder: "folder", colors: true, disallow_public_id: true) cloudinary.v2.api.delete_upload_preset name, -> done() it "should support the usage API call", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.api.usage (error, usage) -> expect(usage.last_update).not.to.eql null done() it "should allow deleting all derived resources", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, public_id: "api_test5", eager: {transformation: {width: 101, crop: "scale"}}, (error, upload_result) -> cloudinary.v2.api.resource "api_test5", (error, resource) -> return done(new Error error.message) if error? expect(resource).to.be.an(Object) expect(resource.derived).not.to.be.empty() # Prepare to loop until no more resources to delete delete_all = (next, callback)-> options = {keep_original: yes} options.next_cursor = next if next? cloudinary.v2.api.delete_all_resources options, (error, delete_result) -> return done(new Error error.message) if error? if delete_result.next_cursor? delete_all(delete_result.next_cursor, callback) else callback() # execute loop delete_all undefined, ()-> cloudinary.v2.api.resource "api_test5", (error, new_resource) -> return done(new Error error.message) if error? expect(new_resource.derived).to.be.empty() done() describe "update", ()-> it "should support setting manual moderation status", (done) -> @timeout TIMEOUT_MEDIUM cloudinary.v2.uploader.upload IMAGE_FILE, moderation: "manual", (error, upload_result) -> uploaded.push upload_result.public_id cloudinary.v2.api.update upload_result.public_id, moderation_status: "approved", (error, api_result) -> expect(api_result.moderation[0].status).to.eql("approved") done() it "should support requesting ocr info", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, ocr: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting raw conversion", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, raw_convert: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting categorization", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, categorization: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting detection", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, detection: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting background_removal", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, background_removal: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting similarity_search", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, similarity_search: "illegal", (error, api_result) -> expect(error.message).to.contain "Illegal value" done() it "should support requesting auto_tagging", (done) -> @timeout TIMEOUT_MEDIUM upload_image (upload_result)-> cloudinary.v2.api.update upload_result.public_id, auto_tagging: "illegal", (error, api_result) -> expect(error.message).to.contain "Must use" done() it "should support listing by moderation kind and value", (done) -> @timeout TIMEOUT_MEDIUM ids = [] api_results =[] lists = {} after_listing = (list) -> (error, list_result) -> lists[list] = list_result.resources.map((r) -> r.public_id) if _.keys(lists).length == 3 expect(lists.approved).to.contain(ids[0]) expect(lists.approved).not.to.contain(ids[1]) expect(lists.approved).not.to.contain(ids[2]) expect(lists.rejected).to.contain(ids[1]) expect(lists.rejected).not.to.contain(ids[0]) expect(lists.rejected).not.to.contain(ids[2]) expect(lists.pending).to.contain(ids[2]) expect(lists.pending).not.to.contain(ids[0]) expect(lists.pending).not.to.contain(ids[1]) done() after_update = (error, api_result) -> api_results.push(api_result) if api_results.length == 2 cloudinary.v2.api.resources_by_moderation("manual", "approved", max_results: 1000, moderations: true, after_listing("approved")) cloudinary.v2.api.resources_by_moderation("manual", "rejected", max_results: 1000, moderations: true, after_listing("rejected")) cloudinary.v2.api.resources_by_moderation("manual", "pending", max_results: 1000, moderations: true, after_listing("pending")) after_upload = (error, upload_result) -> ids.push(upload_result.public_id) if ids.length == 3 cloudinary.v2.api.update ids[0], moderation_status: "approved", after_update cloudinary.v2.api.update ids[1], moderation_status: "rejected", after_update cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) cloudinary.v2.uploader.upload(IMAGE_FILE, moderation: "manual", after_upload) # For this test to work, "Auto-create folders" should be enabled in the Upload Settings. # Replace `it` with `it.skip` below if you want to disable it. it "should list folders in cloudinary", (done)-> @timeout TIMEOUT_LONG Q.all([ cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder2/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder1/item' ), cloudinary.v2.uploader.upload(IMAGE_FILE, public_id: 'test_folder1/test_subfolder2/item' ) ]).then((results)-> Q.all([ cloudinary.v2.api.root_folders(), cloudinary.v2.api.sub_folders('test_folder1') ]) ).then((results)-> root= results[0] root_folders = (folder.name for folder in root.folders) sub_1 = results[1] expect(root_folders).to.contain('test_folder1') expect(root_folders).to.contain('test_folder2') expect(sub_1.folders[0].path).to.eql('test_folder1/test_subfolder1') expect(sub_1.folders[1].path).to.eql('test_folder1/test_subfolder2') cloudinary.v2.api.sub_folders('test_folder_not_exists') ).then((result)-> console.log('error test_folder_not_exists should not pass to "then" handler but "catch"') expect(true).to.eql(false) ).catch((err)-> expect(err.error.message).to.eql('Can\'t find folder with path test_folder_not_exists') done() )
[ { "context": " ht = {}\n for row in @rows\n key = @keyf(row)[1]\n ht[key] = [] unless key of ht\n ht[", "end": 3978, "score": 0.9433931112289429, "start": 3965, "tag": "KEY", "value": "@keyf(row)[1]" } ]
src/data/partitionedpairtable.coffee
sirrice/ggdata
0
#<< data/pairtable class data.PartitionedPairTable extends data.PairTable constructor: (@table, @cols, @lschema, @rschema) -> unless @table.has 'left' throw Error unless @table.has 'right' throw Error if @cols.length + 2 != @table.cols().length #throw Error "table should have #{@cols.length+2} cols, has #{@table.ncols()}" 1 @keyf = data.ops.Util.createKeyF cols, @table.schema # cache a local clone of the rows, these will be update in place @table = @table.cache() unless _.isType @table, data.ops.Array @ht = {} @rows = @table.rows for row in @rows str = @keyf(row)[1] if str of @ht cur = @ht[str] cur.set 'left', (cur.get('left').union row.get('left')) cur.set 'right', (cur.get('right').union row.get('right')) else @ht[str] = row @left_ = null @right_ = null addProv: (lefts, rights)-> lefts = _.compact _.flatten [lefts] rights = _.compact _.flatten [rights] pstore = ggprov.Prov.get() for l in lefts pstore.connect l, @left(), 'table' for r in rights pstore.connect r, @right(), 'table' left: (t) -> if t? throw Error "PartitionedPairTable cannot set left" ls = @lefts() if @left_? @left_.tables = ls @left_.ensureSchema() @left_.setProv() else @left_ = new data.ops.Union ls ggprov.Prov.get().connect @table, @left_, 'table' @left_ lefts: -> _.compact @rows.map (row) -> row.get 'left' right: (t) -> if t? throw Error "PartitionedPairTable cannot set right" rs = @rights() if @right_? @right_.tables = rs @right_.ensureSchema() @right_.setProv() else @right_ = new data.ops.Union rs ggprov.Prov.get().connect @table, @right_, 'table' @right_ rights: -> _.compact @rows.map (row) -> row.get 'right' leftSchema: -> @lschema rightSchema: -> @rschema clone: -> ret = new data.PartitionedPairTable @table, @cols, @lschema, @rschema ret.addProv @left(), @right() ret rmSharedCol: (col) -> unless col in @cols return @ schema = @table.schema.exclude col lschema = @lschema.exclude col rschema = @rschema.exclude col cols = _.without @cols, col rows = for row in @rows schema.cols.map (c) -> row.get c table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, lschema, rschema ret.addProv @left(), @right() ret addSharedCol: (col, val, type) -> if col in @cols throw Error "cannot add shared col that exists" type ?= data.Schema.type val schema = @table.schema.clone() schema.addColumn col, type cols = @cols.concat [col] rows = for row in @rows row = row.data.map _.identity row.push val row table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, @lschema, @rschema ret.addProv @left(), @right() ret unpartition: -> new data.PairTable( @left() @right() ) update: (key, pt) -> unless key of @ht throw Error @ht[key].set 'left', pt.left() @ht[key].set 'right', pt.right() @ ensure: (cols) -> ensureCols = _.difference cols, @cols if ensureCols.length > 0 newtable = @table.project { alias: ['left', 'right'] cols: ['left', 'right'] type: data.Schema.table f: (l, r) -> pt = data.PairTable.ensure l, r, ensureCols { left: pt.left() right: pt.right() } } ret = new data.PartitionedPairTable newtable, @cols, @lschema, @rschema ret.addProv @left(), @right() return ret return @ partition: (cols) -> if _.difference(cols, @cols).length > 0 @partitionOn(cols).partition cols else if _.difference(@cols, cols).length > 0 ht = {} for row in @rows key = @keyf(row)[1] ht[key] = [] unless key of ht ht[key].push row for key, rows of ht ls = [] rs = [] for row in rows ls.push row.get 'left' rs.push row.get 'right' l = new data.ops.Union ls r = new data.ops.Union rs [key, new data.PairTable(l, r)] else for key, row of @ht l = row.get 'left' r = row.get 'right' [key, new data.PairTable(l, r)] partitionOn: (cols) -> cols = _.compact _.flatten [cols] diffcols = _.difference(cols, @cols) mycols = _.difference @cols, cols if diffcols.length > 0 newtables = [] _.each @rows, (row) -> partitions = data.PairTable.partition row.get('left'), row.get('right'), diffcols mapping = mycols.map (mycol) -> { alias: mycol cols: [] type: row.schema.type mycol f: -> row.get(mycol) } proj = partitions.partition.project mapping newtables.push proj union = new data.ops.Union newtables ret = new data.PartitionedPairTable union, _.union(@cols,cols), @lschema, @rschema ret.addProv @left(), @right() ret else @ @fromPairTables: (pts) -> cols = {} pts = for pt in pts if _.isType pt, data.PartitionedPairTable for col in pt.cols cols[col] = yes pt else [l, r] = [pt.left(), pt.right()] schema = new data.Schema ['left', 'right'], [data.Schema.table, data.Schema.table] table = new data.RowTable schema, [[l, r]] newppt = new data.PartitionedPairTable table, [], pt.leftSchema(), pt.rightSchema() newppt.addProv l, r newppt cols = _.keys cols rows = [] schema = null prov = for pt in pts pt = pt.partitionOn cols rows.push.apply rows, pt.table.rows schema ?= pt.table.schema pt.left() newtable = new data.ops.Array schema, rows, prov new data.PartitionedPairTable newtable, cols, pts[0].leftSchema(), pts[0].rightSchema()
133042
#<< data/pairtable class data.PartitionedPairTable extends data.PairTable constructor: (@table, @cols, @lschema, @rschema) -> unless @table.has 'left' throw Error unless @table.has 'right' throw Error if @cols.length + 2 != @table.cols().length #throw Error "table should have #{@cols.length+2} cols, has #{@table.ncols()}" 1 @keyf = data.ops.Util.createKeyF cols, @table.schema # cache a local clone of the rows, these will be update in place @table = @table.cache() unless _.isType @table, data.ops.Array @ht = {} @rows = @table.rows for row in @rows str = @keyf(row)[1] if str of @ht cur = @ht[str] cur.set 'left', (cur.get('left').union row.get('left')) cur.set 'right', (cur.get('right').union row.get('right')) else @ht[str] = row @left_ = null @right_ = null addProv: (lefts, rights)-> lefts = _.compact _.flatten [lefts] rights = _.compact _.flatten [rights] pstore = ggprov.Prov.get() for l in lefts pstore.connect l, @left(), 'table' for r in rights pstore.connect r, @right(), 'table' left: (t) -> if t? throw Error "PartitionedPairTable cannot set left" ls = @lefts() if @left_? @left_.tables = ls @left_.ensureSchema() @left_.setProv() else @left_ = new data.ops.Union ls ggprov.Prov.get().connect @table, @left_, 'table' @left_ lefts: -> _.compact @rows.map (row) -> row.get 'left' right: (t) -> if t? throw Error "PartitionedPairTable cannot set right" rs = @rights() if @right_? @right_.tables = rs @right_.ensureSchema() @right_.setProv() else @right_ = new data.ops.Union rs ggprov.Prov.get().connect @table, @right_, 'table' @right_ rights: -> _.compact @rows.map (row) -> row.get 'right' leftSchema: -> @lschema rightSchema: -> @rschema clone: -> ret = new data.PartitionedPairTable @table, @cols, @lschema, @rschema ret.addProv @left(), @right() ret rmSharedCol: (col) -> unless col in @cols return @ schema = @table.schema.exclude col lschema = @lschema.exclude col rschema = @rschema.exclude col cols = _.without @cols, col rows = for row in @rows schema.cols.map (c) -> row.get c table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, lschema, rschema ret.addProv @left(), @right() ret addSharedCol: (col, val, type) -> if col in @cols throw Error "cannot add shared col that exists" type ?= data.Schema.type val schema = @table.schema.clone() schema.addColumn col, type cols = @cols.concat [col] rows = for row in @rows row = row.data.map _.identity row.push val row table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, @lschema, @rschema ret.addProv @left(), @right() ret unpartition: -> new data.PairTable( @left() @right() ) update: (key, pt) -> unless key of @ht throw Error @ht[key].set 'left', pt.left() @ht[key].set 'right', pt.right() @ ensure: (cols) -> ensureCols = _.difference cols, @cols if ensureCols.length > 0 newtable = @table.project { alias: ['left', 'right'] cols: ['left', 'right'] type: data.Schema.table f: (l, r) -> pt = data.PairTable.ensure l, r, ensureCols { left: pt.left() right: pt.right() } } ret = new data.PartitionedPairTable newtable, @cols, @lschema, @rschema ret.addProv @left(), @right() return ret return @ partition: (cols) -> if _.difference(cols, @cols).length > 0 @partitionOn(cols).partition cols else if _.difference(@cols, cols).length > 0 ht = {} for row in @rows key = <KEY> ht[key] = [] unless key of ht ht[key].push row for key, rows of ht ls = [] rs = [] for row in rows ls.push row.get 'left' rs.push row.get 'right' l = new data.ops.Union ls r = new data.ops.Union rs [key, new data.PairTable(l, r)] else for key, row of @ht l = row.get 'left' r = row.get 'right' [key, new data.PairTable(l, r)] partitionOn: (cols) -> cols = _.compact _.flatten [cols] diffcols = _.difference(cols, @cols) mycols = _.difference @cols, cols if diffcols.length > 0 newtables = [] _.each @rows, (row) -> partitions = data.PairTable.partition row.get('left'), row.get('right'), diffcols mapping = mycols.map (mycol) -> { alias: mycol cols: [] type: row.schema.type mycol f: -> row.get(mycol) } proj = partitions.partition.project mapping newtables.push proj union = new data.ops.Union newtables ret = new data.PartitionedPairTable union, _.union(@cols,cols), @lschema, @rschema ret.addProv @left(), @right() ret else @ @fromPairTables: (pts) -> cols = {} pts = for pt in pts if _.isType pt, data.PartitionedPairTable for col in pt.cols cols[col] = yes pt else [l, r] = [pt.left(), pt.right()] schema = new data.Schema ['left', 'right'], [data.Schema.table, data.Schema.table] table = new data.RowTable schema, [[l, r]] newppt = new data.PartitionedPairTable table, [], pt.leftSchema(), pt.rightSchema() newppt.addProv l, r newppt cols = _.keys cols rows = [] schema = null prov = for pt in pts pt = pt.partitionOn cols rows.push.apply rows, pt.table.rows schema ?= pt.table.schema pt.left() newtable = new data.ops.Array schema, rows, prov new data.PartitionedPairTable newtable, cols, pts[0].leftSchema(), pts[0].rightSchema()
true
#<< data/pairtable class data.PartitionedPairTable extends data.PairTable constructor: (@table, @cols, @lschema, @rschema) -> unless @table.has 'left' throw Error unless @table.has 'right' throw Error if @cols.length + 2 != @table.cols().length #throw Error "table should have #{@cols.length+2} cols, has #{@table.ncols()}" 1 @keyf = data.ops.Util.createKeyF cols, @table.schema # cache a local clone of the rows, these will be update in place @table = @table.cache() unless _.isType @table, data.ops.Array @ht = {} @rows = @table.rows for row in @rows str = @keyf(row)[1] if str of @ht cur = @ht[str] cur.set 'left', (cur.get('left').union row.get('left')) cur.set 'right', (cur.get('right').union row.get('right')) else @ht[str] = row @left_ = null @right_ = null addProv: (lefts, rights)-> lefts = _.compact _.flatten [lefts] rights = _.compact _.flatten [rights] pstore = ggprov.Prov.get() for l in lefts pstore.connect l, @left(), 'table' for r in rights pstore.connect r, @right(), 'table' left: (t) -> if t? throw Error "PartitionedPairTable cannot set left" ls = @lefts() if @left_? @left_.tables = ls @left_.ensureSchema() @left_.setProv() else @left_ = new data.ops.Union ls ggprov.Prov.get().connect @table, @left_, 'table' @left_ lefts: -> _.compact @rows.map (row) -> row.get 'left' right: (t) -> if t? throw Error "PartitionedPairTable cannot set right" rs = @rights() if @right_? @right_.tables = rs @right_.ensureSchema() @right_.setProv() else @right_ = new data.ops.Union rs ggprov.Prov.get().connect @table, @right_, 'table' @right_ rights: -> _.compact @rows.map (row) -> row.get 'right' leftSchema: -> @lschema rightSchema: -> @rschema clone: -> ret = new data.PartitionedPairTable @table, @cols, @lschema, @rschema ret.addProv @left(), @right() ret rmSharedCol: (col) -> unless col in @cols return @ schema = @table.schema.exclude col lschema = @lschema.exclude col rschema = @rschema.exclude col cols = _.without @cols, col rows = for row in @rows schema.cols.map (c) -> row.get c table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, lschema, rschema ret.addProv @left(), @right() ret addSharedCol: (col, val, type) -> if col in @cols throw Error "cannot add shared col that exists" type ?= data.Schema.type val schema = @table.schema.clone() schema.addColumn col, type cols = @cols.concat [col] rows = for row in @rows row = row.data.map _.identity row.push val row table = new data.RowTable schema, rows ret = new data.PartitionedPairTable table, cols, @lschema, @rschema ret.addProv @left(), @right() ret unpartition: -> new data.PairTable( @left() @right() ) update: (key, pt) -> unless key of @ht throw Error @ht[key].set 'left', pt.left() @ht[key].set 'right', pt.right() @ ensure: (cols) -> ensureCols = _.difference cols, @cols if ensureCols.length > 0 newtable = @table.project { alias: ['left', 'right'] cols: ['left', 'right'] type: data.Schema.table f: (l, r) -> pt = data.PairTable.ensure l, r, ensureCols { left: pt.left() right: pt.right() } } ret = new data.PartitionedPairTable newtable, @cols, @lschema, @rschema ret.addProv @left(), @right() return ret return @ partition: (cols) -> if _.difference(cols, @cols).length > 0 @partitionOn(cols).partition cols else if _.difference(@cols, cols).length > 0 ht = {} for row in @rows key = PI:KEY:<KEY>END_PI ht[key] = [] unless key of ht ht[key].push row for key, rows of ht ls = [] rs = [] for row in rows ls.push row.get 'left' rs.push row.get 'right' l = new data.ops.Union ls r = new data.ops.Union rs [key, new data.PairTable(l, r)] else for key, row of @ht l = row.get 'left' r = row.get 'right' [key, new data.PairTable(l, r)] partitionOn: (cols) -> cols = _.compact _.flatten [cols] diffcols = _.difference(cols, @cols) mycols = _.difference @cols, cols if diffcols.length > 0 newtables = [] _.each @rows, (row) -> partitions = data.PairTable.partition row.get('left'), row.get('right'), diffcols mapping = mycols.map (mycol) -> { alias: mycol cols: [] type: row.schema.type mycol f: -> row.get(mycol) } proj = partitions.partition.project mapping newtables.push proj union = new data.ops.Union newtables ret = new data.PartitionedPairTable union, _.union(@cols,cols), @lschema, @rschema ret.addProv @left(), @right() ret else @ @fromPairTables: (pts) -> cols = {} pts = for pt in pts if _.isType pt, data.PartitionedPairTable for col in pt.cols cols[col] = yes pt else [l, r] = [pt.left(), pt.right()] schema = new data.Schema ['left', 'right'], [data.Schema.table, data.Schema.table] table = new data.RowTable schema, [[l, r]] newppt = new data.PartitionedPairTable table, [], pt.leftSchema(), pt.rightSchema() newppt.addProv l, r newppt cols = _.keys cols rows = [] schema = null prov = for pt in pts pt = pt.partitionOn cols rows.push.apply rows, pt.table.rows schema ?= pt.table.schema pt.left() newtable = new data.ops.Array schema, rows, prov new data.PartitionedPairTable newtable, cols, pts[0].leftSchema(), pts[0].rightSchema()
[ { "context": "\n# File: Tiramisu/_helper/camera.coffee\r\n# Author: NaNuNo\r\n# Project: https://github.com/NaNuNoo/Tiramisu\r\n", "end": 97, "score": 0.9546462893486023, "start": 91, "tag": "NAME", "value": "NaNuNo" }, { "context": "\r\n# Author: NaNuNo\r\n# Project: https://github....
_helper/camera.coffee
NaNuNoo/Tiramisu
0
# # # # # # # # # # # # # # # # # # # # # File: Tiramisu/_helper/camera.coffee # Author: NaNuNo # Project: https://github.com/NaNuNoo/Tiramisu # WebSite: http://FenQi.IO # # # # # # # # # # # # # # # # # # # # PHI_MIN = 0 PHI_MAX = Math.PI * 2 THETA_MIN = 0 THETA_MAX = Math.PI class SphereView constructor: () -> @_phi = 0 @_theta = Math.PI / 2 @_radius = 200 @_viewPos = vec3.create() @_viewMat = mat4.create() return getViewPos: () -> return @_viewPos getViewMat: () -> return @_viewMat update: () -> x = @_radius * Math.sin(@_theta) * Math.cos(@_phi) z = @_radius * Math.sin(@_theta) * Math.sin(@_phi) y = @_radius * Math.cos(@_theta) vec3.set(@_viewPos, x, y, z) upx = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.cos(@_phi) upz = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.sin(@_phi) upy = @_radius * Math.cos(@_theta + Math.PI / 2) mat4.lookAt(@_viewMat, [0,0,0], [upx,upy,upz]) return incPhi: () -> decPhi: () -> incTheta: () -> decTheta: () ->
141463
# # # # # # # # # # # # # # # # # # # # # File: Tiramisu/_helper/camera.coffee # Author: <NAME> # Project: https://github.com/NaNuNoo/Tiramisu # WebSite: http://FenQi.IO # # # # # # # # # # # # # # # # # # # # PHI_MIN = 0 PHI_MAX = Math.PI * 2 THETA_MIN = 0 THETA_MAX = Math.PI class SphereView constructor: () -> @_phi = 0 @_theta = Math.PI / 2 @_radius = 200 @_viewPos = vec3.create() @_viewMat = mat4.create() return getViewPos: () -> return @_viewPos getViewMat: () -> return @_viewMat update: () -> x = @_radius * Math.sin(@_theta) * Math.cos(@_phi) z = @_radius * Math.sin(@_theta) * Math.sin(@_phi) y = @_radius * Math.cos(@_theta) vec3.set(@_viewPos, x, y, z) upx = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.cos(@_phi) upz = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.sin(@_phi) upy = @_radius * Math.cos(@_theta + Math.PI / 2) mat4.lookAt(@_viewMat, [0,0,0], [upx,upy,upz]) return incPhi: () -> decPhi: () -> incTheta: () -> decTheta: () ->
true
# # # # # # # # # # # # # # # # # # # # # File: Tiramisu/_helper/camera.coffee # Author: PI:NAME:<NAME>END_PI # Project: https://github.com/NaNuNoo/Tiramisu # WebSite: http://FenQi.IO # # # # # # # # # # # # # # # # # # # # PHI_MIN = 0 PHI_MAX = Math.PI * 2 THETA_MIN = 0 THETA_MAX = Math.PI class SphereView constructor: () -> @_phi = 0 @_theta = Math.PI / 2 @_radius = 200 @_viewPos = vec3.create() @_viewMat = mat4.create() return getViewPos: () -> return @_viewPos getViewMat: () -> return @_viewMat update: () -> x = @_radius * Math.sin(@_theta) * Math.cos(@_phi) z = @_radius * Math.sin(@_theta) * Math.sin(@_phi) y = @_radius * Math.cos(@_theta) vec3.set(@_viewPos, x, y, z) upx = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.cos(@_phi) upz = @_radius * Math.sin(@_theta + Math.PI / 2) * Math.sin(@_phi) upy = @_radius * Math.cos(@_theta + Math.PI / 2) mat4.lookAt(@_viewMat, [0,0,0], [upx,upy,upz]) return incPhi: () -> decPhi: () -> incTheta: () -> decTheta: () ->
[ { "context": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apache Lice", "end": 30, "score": 0.9998822212219238, "start": 17, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apac...
mrfogg-front/app/coffee/plugins/overlay.coffee
PIWEEK/mrfogg
0
# Copyright 2013 Andrey Antukh <niwi@niwi.be> # # 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. OverlayProvider = ($rootScope, $q, $log) -> class OverlayService constructor: -> @.el = angular.element("<div />", {"class": "overlay"}) @.defered = $q.defer() _.bindAll(@) close: -> $log.debug "OverlayService.close" @.el.off() @.el.remove() open: -> $log.debug "OverlayService.open" self = @ @.el.on "click", (event) -> $rootScope.$apply -> self.close() self.defered.resolve() body = angular.element("body") body.append(@.el) return @.defered.promise return -> new OverlayService() module = angular.module("gmOverlay", []) module.factory('$gmOverlay', ["$rootScope", "$q", "$log", OverlayProvider])
140078
# Copyright 2013 <NAME> <<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. OverlayProvider = ($rootScope, $q, $log) -> class OverlayService constructor: -> @.el = angular.element("<div />", {"class": "overlay"}) @.defered = $q.defer() _.bindAll(@) close: -> $log.debug "OverlayService.close" @.el.off() @.el.remove() open: -> $log.debug "OverlayService.open" self = @ @.el.on "click", (event) -> $rootScope.$apply -> self.close() self.defered.resolve() body = angular.element("body") body.append(@.el) return @.defered.promise return -> new OverlayService() module = angular.module("gmOverlay", []) module.factory('$gmOverlay', ["$rootScope", "$q", "$log", OverlayProvider])
true
# Copyright 2013 PI:NAME:<NAME>END_PI <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. OverlayProvider = ($rootScope, $q, $log) -> class OverlayService constructor: -> @.el = angular.element("<div />", {"class": "overlay"}) @.defered = $q.defer() _.bindAll(@) close: -> $log.debug "OverlayService.close" @.el.off() @.el.remove() open: -> $log.debug "OverlayService.open" self = @ @.el.on "click", (event) -> $rootScope.$apply -> self.close() self.defered.resolve() body = angular.element("body") body.append(@.el) return @.defered.promise return -> new OverlayService() module = angular.module("gmOverlay", []) module.factory('$gmOverlay', ["$rootScope", "$q", "$log", OverlayProvider])
[ { "context": "s token.\n @param {String} [options.admin.email=loopback-with-admin@example.com] email address for admin user\n @param {String}", "end": 1259, "score": 0.9998177289962769, "start": 1228, "tag": "EMAIL", "value": "loopback-with-admin@example.com" }, { "context": " ...
src/main.coffee
CureApp/loopback-with-admin
13
LoopbackInfo = require './lib/loopback-info' LoopbackServer = require './lib/loopback-server' ConfigJSONGenerator = require './lib/config-json-generator' ModelsGenerator = require './lib/models-generator' BuildInfoGenerator = require './lib/build-info-generator' CustomConfigs = require './lib/custom-configs' LoopbackBootGenerator = require './lib/loopback-boot-generator' ###* entry point @class Main ### class Main ###* entry point. run loopback with model definitions, config @method run @public @static @param {Object} loopbackDefinitions @param {Object|String} [config] config object or config directory containing config info @param {Boolean} [options.reset] reset previously-generated settings before generation @param {String} [options.env] set environment (production|development|...) @param {String} [options.participantToken] token for participant user @param {Object} [options.admin] options for admin token manager @param {Function|Array(String)} [options.admin.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token. @param {String} [options.admin.email=loopback-with-admin@example.com] email address for admin user @param {String} [options.admin.id=loopback-with-admin-user-id] id of admin user @param {String} [options.admin.password=admin-user-password] password of admin user @param {Number} [options.admin.intervalHours] IntervalHours to fetch new admin token. return {Promise(LoopbackInfo)} ### @run: (loopbackDefinitions, config, options = {}) -> main = new @(loopbackDefinitions, config, options.env) main.reset() unless options.reset is false generated = main.generate() if (options.adminToken) console.error 'LoopbackWithAdmin.run(): options.adminToken is deprecated. Use options.admin instead.' adminOptions = options.admin or options.adminToken # adminToken is for backward compatibility @launchLoopback(adminOptions, options.participantToken).then (server) => return new LoopbackInfo(server, generated) ###* @constructor @private ### constructor: (loopbackDefinitions, configs, @env) -> if loopbackDefinitions.models? modelDefinitions = loopbackDefinitions.models { customRoles } = loopbackDefinitions else modelDefinitions = loopbackDefinitions customRoles = null @env ?= process.env.NODE_ENV or 'development' customConfigs = new CustomConfigs(configs, @env) configObj = customConfigs.toObject() @configJSONGenerator = new ConfigJSONGenerator(configObj, @env) @modelsGenerator = new ModelsGenerator(modelDefinitions) @bootGenerator = new LoopbackBootGenerator(customRoles: customRoles) @buildInfoGenerator = new BuildInfoGenerator(modelDefinitions, configObj, @env) ###* @private ### generate: -> config : @configJSONGenerator.generate() models : @modelsGenerator.generate() buildInfo : @buildInfoGenerator.generate() bootInfo : @bootGenerator.generate() ###* @private ### reset: -> @configJSONGenerator.reset() @modelsGenerator.reset() @buildInfoGenerator.reset() @bootGenerator.reset() ###* run loopback @private ### @launchLoopback: (adminOptions, participantToken) -> server = new LoopbackServer() server.launch(adminOptions, participantToken).then => server module.exports = Main
48624
LoopbackInfo = require './lib/loopback-info' LoopbackServer = require './lib/loopback-server' ConfigJSONGenerator = require './lib/config-json-generator' ModelsGenerator = require './lib/models-generator' BuildInfoGenerator = require './lib/build-info-generator' CustomConfigs = require './lib/custom-configs' LoopbackBootGenerator = require './lib/loopback-boot-generator' ###* entry point @class Main ### class Main ###* entry point. run loopback with model definitions, config @method run @public @static @param {Object} loopbackDefinitions @param {Object|String} [config] config object or config directory containing config info @param {Boolean} [options.reset] reset previously-generated settings before generation @param {String} [options.env] set environment (production|development|...) @param {String} [options.participantToken] token for participant user @param {Object} [options.admin] options for admin token manager @param {Function|Array(String)} [options.admin.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token. @param {String} [options.admin.email=<EMAIL>] email address for admin user @param {String} [options.admin.id=loopback-with-admin-user-id] id of admin user @param {String} [options.admin.password=<PASSWORD>] <PASSWORD> of <PASSWORD> @param {Number} [options.admin.intervalHours] IntervalHours to fetch new admin token. return {Promise(LoopbackInfo)} ### @run: (loopbackDefinitions, config, options = {}) -> main = new @(loopbackDefinitions, config, options.env) main.reset() unless options.reset is false generated = main.generate() if (options.adminToken) console.error 'LoopbackWithAdmin.run(): options.adminToken is deprecated. Use options.admin instead.' adminOptions = options.admin or options.adminToken # adminToken is for backward compatibility @launchLoopback(adminOptions, options.participantToken).then (server) => return new LoopbackInfo(server, generated) ###* @constructor @private ### constructor: (loopbackDefinitions, configs, @env) -> if loopbackDefinitions.models? modelDefinitions = loopbackDefinitions.models { customRoles } = loopbackDefinitions else modelDefinitions = loopbackDefinitions customRoles = null @env ?= process.env.NODE_ENV or 'development' customConfigs = new CustomConfigs(configs, @env) configObj = customConfigs.toObject() @configJSONGenerator = new ConfigJSONGenerator(configObj, @env) @modelsGenerator = new ModelsGenerator(modelDefinitions) @bootGenerator = new LoopbackBootGenerator(customRoles: customRoles) @buildInfoGenerator = new BuildInfoGenerator(modelDefinitions, configObj, @env) ###* @private ### generate: -> config : @configJSONGenerator.generate() models : @modelsGenerator.generate() buildInfo : @buildInfoGenerator.generate() bootInfo : @bootGenerator.generate() ###* @private ### reset: -> @configJSONGenerator.reset() @modelsGenerator.reset() @buildInfoGenerator.reset() @bootGenerator.reset() ###* run loopback @private ### @launchLoopback: (adminOptions, participantToken) -> server = new LoopbackServer() server.launch(adminOptions, participantToken).then => server module.exports = Main
true
LoopbackInfo = require './lib/loopback-info' LoopbackServer = require './lib/loopback-server' ConfigJSONGenerator = require './lib/config-json-generator' ModelsGenerator = require './lib/models-generator' BuildInfoGenerator = require './lib/build-info-generator' CustomConfigs = require './lib/custom-configs' LoopbackBootGenerator = require './lib/loopback-boot-generator' ###* entry point @class Main ### class Main ###* entry point. run loopback with model definitions, config @method run @public @static @param {Object} loopbackDefinitions @param {Object|String} [config] config object or config directory containing config info @param {Boolean} [options.reset] reset previously-generated settings before generation @param {String} [options.env] set environment (production|development|...) @param {String} [options.participantToken] token for participant user @param {Object} [options.admin] options for admin token manager @param {Function|Array(String)} [options.admin.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token. @param {String} [options.admin.email=PI:EMAIL:<EMAIL>END_PI] email address for admin user @param {String} [options.admin.id=loopback-with-admin-user-id] id of admin user @param {String} [options.admin.password=PI:PASSWORD:<PASSWORD>END_PI] PI:PASSWORD:<PASSWORD>END_PI of PI:PASSWORD:<PASSWORD>END_PI @param {Number} [options.admin.intervalHours] IntervalHours to fetch new admin token. return {Promise(LoopbackInfo)} ### @run: (loopbackDefinitions, config, options = {}) -> main = new @(loopbackDefinitions, config, options.env) main.reset() unless options.reset is false generated = main.generate() if (options.adminToken) console.error 'LoopbackWithAdmin.run(): options.adminToken is deprecated. Use options.admin instead.' adminOptions = options.admin or options.adminToken # adminToken is for backward compatibility @launchLoopback(adminOptions, options.participantToken).then (server) => return new LoopbackInfo(server, generated) ###* @constructor @private ### constructor: (loopbackDefinitions, configs, @env) -> if loopbackDefinitions.models? modelDefinitions = loopbackDefinitions.models { customRoles } = loopbackDefinitions else modelDefinitions = loopbackDefinitions customRoles = null @env ?= process.env.NODE_ENV or 'development' customConfigs = new CustomConfigs(configs, @env) configObj = customConfigs.toObject() @configJSONGenerator = new ConfigJSONGenerator(configObj, @env) @modelsGenerator = new ModelsGenerator(modelDefinitions) @bootGenerator = new LoopbackBootGenerator(customRoles: customRoles) @buildInfoGenerator = new BuildInfoGenerator(modelDefinitions, configObj, @env) ###* @private ### generate: -> config : @configJSONGenerator.generate() models : @modelsGenerator.generate() buildInfo : @buildInfoGenerator.generate() bootInfo : @bootGenerator.generate() ###* @private ### reset: -> @configJSONGenerator.reset() @modelsGenerator.reset() @buildInfoGenerator.reset() @bootGenerator.reset() ###* run loopback @private ### @launchLoopback: (adminOptions, participantToken) -> server = new LoopbackServer() server.launch(adminOptions, participantToken).then => server module.exports = Main
[ { "context": " ele: \"simple element\"\r\n person:\r\n name: \"John\"\r\n '@age': 35\r\n '?pi': 'mypi'\r\n '#", "end": 113, "score": 0.9997250437736511, "start": 109, "tag": "NAME", "value": "John" } ]
node_modules/xmlbuilder/perf/basic/object.coffee
jordaoqualho/Lorena-Felicio
8
perf 'Create simple object', 100000, (run) -> obj = ele: "simple element" person: name: "John" '@age': 35 '?pi': 'mypi' '#comment': 'Good guy' '#cdata': 'well formed!' unescaped: '#raw': '&<>&' address: city: "Istanbul" street: "End of long and winding road" contact: phone: [ "555-1234", "555-1235" ] id: () -> return 42 details: '#text': 'classified' run () -> xml(obj)
39707
perf 'Create simple object', 100000, (run) -> obj = ele: "simple element" person: name: "<NAME>" '@age': 35 '?pi': 'mypi' '#comment': 'Good guy' '#cdata': 'well formed!' unescaped: '#raw': '&<>&' address: city: "Istanbul" street: "End of long and winding road" contact: phone: [ "555-1234", "555-1235" ] id: () -> return 42 details: '#text': 'classified' run () -> xml(obj)
true
perf 'Create simple object', 100000, (run) -> obj = ele: "simple element" person: name: "PI:NAME:<NAME>END_PI" '@age': 35 '?pi': 'mypi' '#comment': 'Good guy' '#cdata': 'well formed!' unescaped: '#raw': '&<>&' address: city: "Istanbul" street: "End of long and winding road" contact: phone: [ "555-1234", "555-1235" ] id: () -> return 42 details: '#text': 'classified' run () -> xml(obj)
[ { "context": ".3.18 Darwin/14.0.0'\n 'Authorization':'oauth 5774b305d2ae4469a2c9258956ea49'\n 'Content-Type':'application/json'\n }\n\n\n", "end": 449, "score": 0.5984563827514648, "start": 419, "tag": "PASSWORD", "value": "5774b305d2ae4469a2c9258956ea49" } ]
server/getCollection.coffee
youqingkui/zhihu2evernote
0
requrest = require('request') fs = require('fs') path = require('path') queue = require('../server/getAnswers') SyncLog = require('../models/sync-log') async = require('async') saveErr = require('../server/errInfo') Task = require('../models/task') class GetCol constructor:(@noteStore) -> @headers = { 'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0' 'Authorization':'oauth 5774b305d2ae4469a2c9258956ea49' 'Content-Type':'application/json' } getColList:(url) -> self = @ op = { url:url headers:self.headers gzip:true } async.auto getList:(cb) -> requrest.get op, (err, res, body) -> return saveErr op.url, 1, {err:err} if err data = JSON.parse(body) cb(null, data) checkList:['getList', (cb, result) -> data = result.getList if data.data.length answerList = data.data answerList.forEach (answer) -> Task.findOne {url:answer.url}, (err, row) -> return saveErr url, 2, {err:err, answer:answer.url} if err if row console.log "already exits ==>", answer.url else self.addTask answer.url, (err2, status) -> console.log err2 if err2 if status is 3 console.log "#{answer.url} do {error}" else if status is 4 console.log "#{answer.url} do ok" self.getColList(data.paging.next) else console.log data ] addTask:(url, cb) -> self = @ async.auto addDB:(callback) -> task = new Task task.url = url task.save (err, row) -> return cb(err) if err callback() addDo:['addDB', (callback) -> queue.push {url:url, noteStore:self.noteStore}, (err) -> if err console.log err self.changeStatus url, 3, cb else self.changeStatus url, 4, cb ] changeStatus: (url, status, cb) -> async.auto findUrl:(callback) -> Task.findOne {url:url}, (err, row) -> return cb(err, status) if err callback(null, row) if row change:['findUrl', (callback, result) -> row = result.findUrl row.status = status row.save (err, row) -> return cb(err) if err cb(null, status) ] getColInfo:() -> module.exports = GetCol
175782
requrest = require('request') fs = require('fs') path = require('path') queue = require('../server/getAnswers') SyncLog = require('../models/sync-log') async = require('async') saveErr = require('../server/errInfo') Task = require('../models/task') class GetCol constructor:(@noteStore) -> @headers = { 'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0' 'Authorization':'oauth <PASSWORD>' 'Content-Type':'application/json' } getColList:(url) -> self = @ op = { url:url headers:self.headers gzip:true } async.auto getList:(cb) -> requrest.get op, (err, res, body) -> return saveErr op.url, 1, {err:err} if err data = JSON.parse(body) cb(null, data) checkList:['getList', (cb, result) -> data = result.getList if data.data.length answerList = data.data answerList.forEach (answer) -> Task.findOne {url:answer.url}, (err, row) -> return saveErr url, 2, {err:err, answer:answer.url} if err if row console.log "already exits ==>", answer.url else self.addTask answer.url, (err2, status) -> console.log err2 if err2 if status is 3 console.log "#{answer.url} do {error}" else if status is 4 console.log "#{answer.url} do ok" self.getColList(data.paging.next) else console.log data ] addTask:(url, cb) -> self = @ async.auto addDB:(callback) -> task = new Task task.url = url task.save (err, row) -> return cb(err) if err callback() addDo:['addDB', (callback) -> queue.push {url:url, noteStore:self.noteStore}, (err) -> if err console.log err self.changeStatus url, 3, cb else self.changeStatus url, 4, cb ] changeStatus: (url, status, cb) -> async.auto findUrl:(callback) -> Task.findOne {url:url}, (err, row) -> return cb(err, status) if err callback(null, row) if row change:['findUrl', (callback, result) -> row = result.findUrl row.status = status row.save (err, row) -> return cb(err) if err cb(null, status) ] getColInfo:() -> module.exports = GetCol
true
requrest = require('request') fs = require('fs') path = require('path') queue = require('../server/getAnswers') SyncLog = require('../models/sync-log') async = require('async') saveErr = require('../server/errInfo') Task = require('../models/task') class GetCol constructor:(@noteStore) -> @headers = { 'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0' 'Authorization':'oauth PI:PASSWORD:<PASSWORD>END_PI' 'Content-Type':'application/json' } getColList:(url) -> self = @ op = { url:url headers:self.headers gzip:true } async.auto getList:(cb) -> requrest.get op, (err, res, body) -> return saveErr op.url, 1, {err:err} if err data = JSON.parse(body) cb(null, data) checkList:['getList', (cb, result) -> data = result.getList if data.data.length answerList = data.data answerList.forEach (answer) -> Task.findOne {url:answer.url}, (err, row) -> return saveErr url, 2, {err:err, answer:answer.url} if err if row console.log "already exits ==>", answer.url else self.addTask answer.url, (err2, status) -> console.log err2 if err2 if status is 3 console.log "#{answer.url} do {error}" else if status is 4 console.log "#{answer.url} do ok" self.getColList(data.paging.next) else console.log data ] addTask:(url, cb) -> self = @ async.auto addDB:(callback) -> task = new Task task.url = url task.save (err, row) -> return cb(err) if err callback() addDo:['addDB', (callback) -> queue.push {url:url, noteStore:self.noteStore}, (err) -> if err console.log err self.changeStatus url, 3, cb else self.changeStatus url, 4, cb ] changeStatus: (url, status, cb) -> async.auto findUrl:(callback) -> Task.findOne {url:url}, (err, row) -> return cb(err, status) if err callback(null, row) if row change:['findUrl', (callback, result) -> row = result.findUrl row.status = status row.save (err, row) -> return cb(err) if err cb(null, status) ] getColInfo:() -> module.exports = GetCol
[ { "context": "ft part is the same as the right\n# part.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------", "end": 116, "score": 0.9998145699501038, "start": 104, "tag": "NAME", "value": "Ilya Volodin" } ]
src/rules/no-self-compare.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag comparison where left part is the same as the right # part. # @author Ilya Volodin ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow comparisons where both sides are exactly the same' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-self-compare' schema: [] create: (context) -> sourceCode = context.getSourceCode() ###* # Determines whether two nodes are composed of the same tokens. # @param {ASTNode} nodeA The first node # @param {ASTNode} nodeB The second node # @returns {boolean} true if the nodes have identical token representations ### hasSameTokens = (nodeA, nodeB) -> tokensA = sourceCode.getTokens nodeA tokensB = sourceCode.getTokens nodeB tokensA.length is tokensB.length and tokensA.every (token, index) -> token.type is tokensB[index].type and token.value is tokensB[index].value BinaryExpression: (node) -> operators = new Set ['is', '==', 'isnt', '!=', '>', '<', '>=', '<='] if operators.has(node.operator) and hasSameTokens node.left, node.right context.report { node message: 'Comparing to itself is potentially pointless.' }
74120
###* # @fileoverview Rule to flag comparison where left part is the same as the right # part. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow comparisons where both sides are exactly the same' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-self-compare' schema: [] create: (context) -> sourceCode = context.getSourceCode() ###* # Determines whether two nodes are composed of the same tokens. # @param {ASTNode} nodeA The first node # @param {ASTNode} nodeB The second node # @returns {boolean} true if the nodes have identical token representations ### hasSameTokens = (nodeA, nodeB) -> tokensA = sourceCode.getTokens nodeA tokensB = sourceCode.getTokens nodeB tokensA.length is tokensB.length and tokensA.every (token, index) -> token.type is tokensB[index].type and token.value is tokensB[index].value BinaryExpression: (node) -> operators = new Set ['is', '==', 'isnt', '!=', '>', '<', '>=', '<='] if operators.has(node.operator) and hasSameTokens node.left, node.right context.report { node message: 'Comparing to itself is potentially pointless.' }
true
###* # @fileoverview Rule to flag comparison where left part is the same as the right # part. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow comparisons where both sides are exactly the same' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-self-compare' schema: [] create: (context) -> sourceCode = context.getSourceCode() ###* # Determines whether two nodes are composed of the same tokens. # @param {ASTNode} nodeA The first node # @param {ASTNode} nodeB The second node # @returns {boolean} true if the nodes have identical token representations ### hasSameTokens = (nodeA, nodeB) -> tokensA = sourceCode.getTokens nodeA tokensB = sourceCode.getTokens nodeB tokensA.length is tokensB.length and tokensA.every (token, index) -> token.type is tokensB[index].type and token.value is tokensB[index].value BinaryExpression: (node) -> operators = new Set ['is', '==', 'isnt', '!=', '>', '<', '>=', '<='] if operators.has(node.operator) and hasSameTokens node.left, node.right context.report { node message: 'Comparing to itself is potentially pointless.' }
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998615980148315, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/plugins/lists.coffee
git-j/hallo
0
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.hallolists", options: editable: null toolbar: null uuid: '' lists: ordered: true unordered: true buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (type, label) => butten_label = label if ( window.action_list && window.action_list['hallojs_' + label] != undefined ) button_label = window.action_list['hallojs_' + label].title buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label command: "insert#{type}List" icon: "icon-list-#{label.toLowerCase()}" cssClass: @options.buttonCssClass buttonset.append buttonElement buttonize "Ordered", "OL" if @options.lists.ordered buttonize "Unordered", "UL" if @options.lists.unordered buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
155060
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.hallolists", options: editable: null toolbar: null uuid: '' lists: ordered: true unordered: true buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (type, label) => butten_label = label if ( window.action_list && window.action_list['hallojs_' + label] != undefined ) button_label = window.action_list['hallojs_' + label].title buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label command: "insert#{type}List" icon: "icon-list-#{label.toLowerCase()}" cssClass: @options.buttonCssClass buttonset.append buttonElement buttonize "Ordered", "OL" if @options.lists.ordered buttonize "Unordered", "UL" if @options.lists.unordered buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.hallolists", options: editable: null toolbar: null uuid: '' lists: ordered: true unordered: true buttonCssClass: null populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (type, label) => butten_label = label if ( window.action_list && window.action_list['hallojs_' + label] != undefined ) button_label = window.action_list['hallojs_' + label].title buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: button_label command: "insert#{type}List" icon: "icon-list-#{label.toLowerCase()}" cssClass: @options.buttonCssClass buttonset.append buttonElement buttonize "Ordered", "OL" if @options.lists.ordered buttonize "Unordered", "UL" if @options.lists.unordered buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
[ { "context": "\n###\n Script.js - Script that powers 1fiesta. By Andy Chase.\n###\n\nmap = \"\"\ngeocoder = \"\"\nmarkersArray = \"\"\nin", "end": 62, "score": 0.9998190402984619, "start": 52, "tag": "NAME", "value": "Andy Chase" } ]
static/js/src/ascript.coffee
andychase/1fiesta.com
0
 ### Script.js - Script that powers 1fiesta. By Andy Chase. ### map = "" geocoder = "" markersArray = "" infoWindow = "" current_lang = "english" ### Script options ### numberOfMarkersToShowOnPage = 90 getNewEventsRate = 500 ### ^ Milliseconds ### markersTooCloseToBotOfPage = 150 markersTooCloseOnMap = (zoom) -> if zoom > 9 ((-2.4 * zoom) + 41.8) else if zoom > 0 (8000 / Math.pow(2, zoom - 1)) else 20000 iconnametypes = { "animal/agriculture": "birthday", "art festival": "birthday", "brewery": "birthday", "books" : "reading", "charity event": "fundraising", "cultural heritage": "gathering", "exhibit": "screening", "exhibits": "conference", "fair": "birthday", "fairs/festivals": "birthday", "festival": "birthday", "festivals": "birthday", "food": "birthday", "holiday": "deadline", "performing arts": "performance", "sports": "sports", "visual arts": "performance", "winery": "birthday", "artshow": "screening", "concert": "concert", "spin city": "concert", "music calendar, music listing" : "concert", "classical music" : "concert", } window.mousingovernames = false window.beforeenteredcenter = null ### The main script! ### $(document).ready -> ### Set up map ### if $('#mapsection').length setUpMapSection() jumptoLocOrCookieLoc() ### Date filter ### if window.QueryString['date']? $('.datefilter a').removeClass('active'); $('.datefilter #'+window.QueryString['date']).addClass('active'); window.activeDateFilter = window.QueryString['date'] setDateFilter(window.QueryString['date']) $('.datefilter a').click switchDateFilter ### Search bar Autocompleter ### $('#searchbox').keyup -> if $('#searchbox').val() == "" updateResults() return clearMarkers() updateResults() ### Sidebar corrector ### $('#contentcolumn').mouseenter () -> if map.getCenter()? if not window.mousingovernames window.beforeenteredcenter = map.getCenter() window.mousingovernames = true clearTimeout window.mousingovertimer $('#contentcolumn').mouseleave () -> if window.beforeenteredcenter? map.panTo window.beforeenteredcenter window.mousingovertimer = setTimeout (() -> window.mousingovernames = false; updateResults()), 700 setDateFilter = (id) -> $('.datefilter li').removeClass "active" $('.datefilter li #' + id).addClass "active" switchDateFilter = () -> $('.datefilter a').removeClass "active" $(this).addClass "active" window.activeDateFilter = $(this)[0].id clearMarkers() updateResults() jumptoLocOrCookieLoc = () -> jump_location = "" if window.QueryString["type"] == "Location" jump_location = window.QueryString["q"].toString() if jump_location == $.cookie("jump_location") jump_location = "" else $.cookie("jump_location", jump_location) location_value = $.cookie("location") location_zoom = Number($.cookie("location_zoom")) if jump_location != "" centerMapOnAddress jump_location else if not location_value? centerMapOnAddress "Oregon, USA" else lat = location_value.split(',')[0] lng = location_value.split(',')[1] location = new google.maps.LatLng(lat, lng) map.setCenter location map.setZoom location_zoom updateResults = () -> map_bounds = if map.getBounds()? then map.getBounds() else "" center_map_bounds = if map.getCenter()? then map.getCenter().toUrlValue() else "" detect_language(map.getCenter()) $.cookie("location", center_map_bounds) $.cookie("location_zoom", map.getZoom()) queryElasticSearch map_bounds, bounderyQ, (data) -> data = data.hits.hits $('#eventlist').empty() numberToProcess = Math.min(data.length - 1, numberOfMarkersToShowOnPage - 1) if data.length > 0 then for i in [0..numberToProcess] e = data[i]._source e.longitude = e.location.lon e.latitude = e.location.lat e.location = e.address hidden = shouldHideEvent(e) marker = updateMarker(i, e, hidden) if not hidden then listEvent(e, $('#eventlist'), marker) else if current_lang == "chinese" then $('#eventlist').append("<span class='nothing'>&#20160;&#20040;&#20063;&#27809;&#26377;</span>") else $('#eventlist').append("<span class='nothing'>Nothing here, try zooming out or removing filters.</span>") ### Localization ### detect_language = (center_of_map) -> lang = get_location(center_of_map) if lang != current_lang current_lang = lang switch get_location(center_of_map) when "chinese" chinese_nav = [ false, false, "&#35841;", "&#22238;&#39304;"] chinese_cal = ["&#25152;&#26377;&#20107;&#29289;", "&#20170;&#22825;", "&#26126;&#22825;", "&#36889;&#20491;&#26143;&#26399;", "&#36889;&#20491;&#26376;"] chinese_search = "&#23547;&#25214;" chinese_date_title = "&#35745; &#26102;" change_language(chinese_search, chinese_date_title, chinese_nav, chinese_cal) else english_nav = [ false, false, "About", "Feedback"] english_cal = ["All", "Today", "Tomorrow", "Week", "Month"] english_search = "Search" english_date_title = "Date:" change_language(english_search, english_date_title, english_nav, english_cal) change_language = (search, date_title, nav, cal) -> $(".navigationbar form ul li").each (i) -> if nav[i] then $(this).children("a").html(nav[i]) if i == 1 then $(this).children()[1].value = $(document.createElement('div')).html(search).html() $(".datefilter span").html(date_title) $(".datefilter ul li").each (i) -> $(this).children("a").html(cal[i]) get_location = (center_of_map) -> if point_in_rect(center_of_map.lat(), center_of_map.lng(), 1.4552673222585695, 1.2456742607811258, 104.22431479101556, 103.56650839453118) then "chinese" else "english" point_in_rect = (x, y, rect_high_x, rect_low_x, rect_high_y, rect_low_y) -> x < rect_high_x && x > rect_low_x && y < rect_high_y && y > rect_low_y
201452
 ### Script.js - Script that powers 1fiesta. By <NAME>. ### map = "" geocoder = "" markersArray = "" infoWindow = "" current_lang = "english" ### Script options ### numberOfMarkersToShowOnPage = 90 getNewEventsRate = 500 ### ^ Milliseconds ### markersTooCloseToBotOfPage = 150 markersTooCloseOnMap = (zoom) -> if zoom > 9 ((-2.4 * zoom) + 41.8) else if zoom > 0 (8000 / Math.pow(2, zoom - 1)) else 20000 iconnametypes = { "animal/agriculture": "birthday", "art festival": "birthday", "brewery": "birthday", "books" : "reading", "charity event": "fundraising", "cultural heritage": "gathering", "exhibit": "screening", "exhibits": "conference", "fair": "birthday", "fairs/festivals": "birthday", "festival": "birthday", "festivals": "birthday", "food": "birthday", "holiday": "deadline", "performing arts": "performance", "sports": "sports", "visual arts": "performance", "winery": "birthday", "artshow": "screening", "concert": "concert", "spin city": "concert", "music calendar, music listing" : "concert", "classical music" : "concert", } window.mousingovernames = false window.beforeenteredcenter = null ### The main script! ### $(document).ready -> ### Set up map ### if $('#mapsection').length setUpMapSection() jumptoLocOrCookieLoc() ### Date filter ### if window.QueryString['date']? $('.datefilter a').removeClass('active'); $('.datefilter #'+window.QueryString['date']).addClass('active'); window.activeDateFilter = window.QueryString['date'] setDateFilter(window.QueryString['date']) $('.datefilter a').click switchDateFilter ### Search bar Autocompleter ### $('#searchbox').keyup -> if $('#searchbox').val() == "" updateResults() return clearMarkers() updateResults() ### Sidebar corrector ### $('#contentcolumn').mouseenter () -> if map.getCenter()? if not window.mousingovernames window.beforeenteredcenter = map.getCenter() window.mousingovernames = true clearTimeout window.mousingovertimer $('#contentcolumn').mouseleave () -> if window.beforeenteredcenter? map.panTo window.beforeenteredcenter window.mousingovertimer = setTimeout (() -> window.mousingovernames = false; updateResults()), 700 setDateFilter = (id) -> $('.datefilter li').removeClass "active" $('.datefilter li #' + id).addClass "active" switchDateFilter = () -> $('.datefilter a').removeClass "active" $(this).addClass "active" window.activeDateFilter = $(this)[0].id clearMarkers() updateResults() jumptoLocOrCookieLoc = () -> jump_location = "" if window.QueryString["type"] == "Location" jump_location = window.QueryString["q"].toString() if jump_location == $.cookie("jump_location") jump_location = "" else $.cookie("jump_location", jump_location) location_value = $.cookie("location") location_zoom = Number($.cookie("location_zoom")) if jump_location != "" centerMapOnAddress jump_location else if not location_value? centerMapOnAddress "Oregon, USA" else lat = location_value.split(',')[0] lng = location_value.split(',')[1] location = new google.maps.LatLng(lat, lng) map.setCenter location map.setZoom location_zoom updateResults = () -> map_bounds = if map.getBounds()? then map.getBounds() else "" center_map_bounds = if map.getCenter()? then map.getCenter().toUrlValue() else "" detect_language(map.getCenter()) $.cookie("location", center_map_bounds) $.cookie("location_zoom", map.getZoom()) queryElasticSearch map_bounds, bounderyQ, (data) -> data = data.hits.hits $('#eventlist').empty() numberToProcess = Math.min(data.length - 1, numberOfMarkersToShowOnPage - 1) if data.length > 0 then for i in [0..numberToProcess] e = data[i]._source e.longitude = e.location.lon e.latitude = e.location.lat e.location = e.address hidden = shouldHideEvent(e) marker = updateMarker(i, e, hidden) if not hidden then listEvent(e, $('#eventlist'), marker) else if current_lang == "chinese" then $('#eventlist').append("<span class='nothing'>&#20160;&#20040;&#20063;&#27809;&#26377;</span>") else $('#eventlist').append("<span class='nothing'>Nothing here, try zooming out or removing filters.</span>") ### Localization ### detect_language = (center_of_map) -> lang = get_location(center_of_map) if lang != current_lang current_lang = lang switch get_location(center_of_map) when "chinese" chinese_nav = [ false, false, "&#35841;", "&#22238;&#39304;"] chinese_cal = ["&#25152;&#26377;&#20107;&#29289;", "&#20170;&#22825;", "&#26126;&#22825;", "&#36889;&#20491;&#26143;&#26399;", "&#36889;&#20491;&#26376;"] chinese_search = "&#23547;&#25214;" chinese_date_title = "&#35745; &#26102;" change_language(chinese_search, chinese_date_title, chinese_nav, chinese_cal) else english_nav = [ false, false, "About", "Feedback"] english_cal = ["All", "Today", "Tomorrow", "Week", "Month"] english_search = "Search" english_date_title = "Date:" change_language(english_search, english_date_title, english_nav, english_cal) change_language = (search, date_title, nav, cal) -> $(".navigationbar form ul li").each (i) -> if nav[i] then $(this).children("a").html(nav[i]) if i == 1 then $(this).children()[1].value = $(document.createElement('div')).html(search).html() $(".datefilter span").html(date_title) $(".datefilter ul li").each (i) -> $(this).children("a").html(cal[i]) get_location = (center_of_map) -> if point_in_rect(center_of_map.lat(), center_of_map.lng(), 1.4552673222585695, 1.2456742607811258, 104.22431479101556, 103.56650839453118) then "chinese" else "english" point_in_rect = (x, y, rect_high_x, rect_low_x, rect_high_y, rect_low_y) -> x < rect_high_x && x > rect_low_x && y < rect_high_y && y > rect_low_y
true
 ### Script.js - Script that powers 1fiesta. By PI:NAME:<NAME>END_PI. ### map = "" geocoder = "" markersArray = "" infoWindow = "" current_lang = "english" ### Script options ### numberOfMarkersToShowOnPage = 90 getNewEventsRate = 500 ### ^ Milliseconds ### markersTooCloseToBotOfPage = 150 markersTooCloseOnMap = (zoom) -> if zoom > 9 ((-2.4 * zoom) + 41.8) else if zoom > 0 (8000 / Math.pow(2, zoom - 1)) else 20000 iconnametypes = { "animal/agriculture": "birthday", "art festival": "birthday", "brewery": "birthday", "books" : "reading", "charity event": "fundraising", "cultural heritage": "gathering", "exhibit": "screening", "exhibits": "conference", "fair": "birthday", "fairs/festivals": "birthday", "festival": "birthday", "festivals": "birthday", "food": "birthday", "holiday": "deadline", "performing arts": "performance", "sports": "sports", "visual arts": "performance", "winery": "birthday", "artshow": "screening", "concert": "concert", "spin city": "concert", "music calendar, music listing" : "concert", "classical music" : "concert", } window.mousingovernames = false window.beforeenteredcenter = null ### The main script! ### $(document).ready -> ### Set up map ### if $('#mapsection').length setUpMapSection() jumptoLocOrCookieLoc() ### Date filter ### if window.QueryString['date']? $('.datefilter a').removeClass('active'); $('.datefilter #'+window.QueryString['date']).addClass('active'); window.activeDateFilter = window.QueryString['date'] setDateFilter(window.QueryString['date']) $('.datefilter a').click switchDateFilter ### Search bar Autocompleter ### $('#searchbox').keyup -> if $('#searchbox').val() == "" updateResults() return clearMarkers() updateResults() ### Sidebar corrector ### $('#contentcolumn').mouseenter () -> if map.getCenter()? if not window.mousingovernames window.beforeenteredcenter = map.getCenter() window.mousingovernames = true clearTimeout window.mousingovertimer $('#contentcolumn').mouseleave () -> if window.beforeenteredcenter? map.panTo window.beforeenteredcenter window.mousingovertimer = setTimeout (() -> window.mousingovernames = false; updateResults()), 700 setDateFilter = (id) -> $('.datefilter li').removeClass "active" $('.datefilter li #' + id).addClass "active" switchDateFilter = () -> $('.datefilter a').removeClass "active" $(this).addClass "active" window.activeDateFilter = $(this)[0].id clearMarkers() updateResults() jumptoLocOrCookieLoc = () -> jump_location = "" if window.QueryString["type"] == "Location" jump_location = window.QueryString["q"].toString() if jump_location == $.cookie("jump_location") jump_location = "" else $.cookie("jump_location", jump_location) location_value = $.cookie("location") location_zoom = Number($.cookie("location_zoom")) if jump_location != "" centerMapOnAddress jump_location else if not location_value? centerMapOnAddress "Oregon, USA" else lat = location_value.split(',')[0] lng = location_value.split(',')[1] location = new google.maps.LatLng(lat, lng) map.setCenter location map.setZoom location_zoom updateResults = () -> map_bounds = if map.getBounds()? then map.getBounds() else "" center_map_bounds = if map.getCenter()? then map.getCenter().toUrlValue() else "" detect_language(map.getCenter()) $.cookie("location", center_map_bounds) $.cookie("location_zoom", map.getZoom()) queryElasticSearch map_bounds, bounderyQ, (data) -> data = data.hits.hits $('#eventlist').empty() numberToProcess = Math.min(data.length - 1, numberOfMarkersToShowOnPage - 1) if data.length > 0 then for i in [0..numberToProcess] e = data[i]._source e.longitude = e.location.lon e.latitude = e.location.lat e.location = e.address hidden = shouldHideEvent(e) marker = updateMarker(i, e, hidden) if not hidden then listEvent(e, $('#eventlist'), marker) else if current_lang == "chinese" then $('#eventlist').append("<span class='nothing'>&#20160;&#20040;&#20063;&#27809;&#26377;</span>") else $('#eventlist').append("<span class='nothing'>Nothing here, try zooming out or removing filters.</span>") ### Localization ### detect_language = (center_of_map) -> lang = get_location(center_of_map) if lang != current_lang current_lang = lang switch get_location(center_of_map) when "chinese" chinese_nav = [ false, false, "&#35841;", "&#22238;&#39304;"] chinese_cal = ["&#25152;&#26377;&#20107;&#29289;", "&#20170;&#22825;", "&#26126;&#22825;", "&#36889;&#20491;&#26143;&#26399;", "&#36889;&#20491;&#26376;"] chinese_search = "&#23547;&#25214;" chinese_date_title = "&#35745; &#26102;" change_language(chinese_search, chinese_date_title, chinese_nav, chinese_cal) else english_nav = [ false, false, "About", "Feedback"] english_cal = ["All", "Today", "Tomorrow", "Week", "Month"] english_search = "Search" english_date_title = "Date:" change_language(english_search, english_date_title, english_nav, english_cal) change_language = (search, date_title, nav, cal) -> $(".navigationbar form ul li").each (i) -> if nav[i] then $(this).children("a").html(nav[i]) if i == 1 then $(this).children()[1].value = $(document.createElement('div')).html(search).html() $(".datefilter span").html(date_title) $(".datefilter ul li").each (i) -> $(this).children("a").html(cal[i]) get_location = (center_of_map) -> if point_in_rect(center_of_map.lat(), center_of_map.lng(), 1.4552673222585695, 1.2456742607811258, 104.22431479101556, 103.56650839453118) then "chinese" else "english" point_in_rect = (x, y, rect_high_x, rect_low_x, rect_high_y, rect_low_y) -> x < rect_high_x && x > rect_low_x && y < rect_high_y && y > rect_low_y
[ { "context": "cation.href = '/'\n\n login: ->\n username = $('#username').val()\n password = $('#password').val()\n @", "end": 462, "score": 0.6499702334403992, "start": 454, "tag": "USERNAME", "value": "username" }, { "context": "sername = $('#username').val()\n passwor...
app/assets/javascripts/views/users/login.coffee
okapusta/skirace
0
class Skirace.Views.Users.Login extends Backbone.View template: JST['users/login'] loginForm: '#login-from' el: $ '.application-container' events: 'click #login' : 'login' 'click .login-close' : 'loginClose' initialize: -> @user = new Skirace.Models.User() @render() render: -> $(@el).append @template loginClose: -> $('.login-modal').remove() window.location.href = '/' login: -> username = $('#username').val() password = $('#password').val() @user.login(username, password)
158287
class Skirace.Views.Users.Login extends Backbone.View template: JST['users/login'] loginForm: '#login-from' el: $ '.application-container' events: 'click #login' : 'login' 'click .login-close' : 'loginClose' initialize: -> @user = new Skirace.Models.User() @render() render: -> $(@el).append @template loginClose: -> $('.login-modal').remove() window.location.href = '/' login: -> username = $('#username').val() password = $('#<PASSWORD>').val() @user.login(username, password)
true
class Skirace.Views.Users.Login extends Backbone.View template: JST['users/login'] loginForm: '#login-from' el: $ '.application-container' events: 'click #login' : 'login' 'click .login-close' : 'loginClose' initialize: -> @user = new Skirace.Models.User() @render() render: -> $(@el).append @template loginClose: -> $('.login-modal').remove() window.location.href = '/' login: -> username = $('#username').val() password = $('#PI:PASSWORD:<PASSWORD>END_PI').val() @user.login(username, password)
[ { "context": "t.attr('class'), data)\n\n data = { key1: 'value1', key2: 'value2' }\n $tag = affix(\".child", "end": 2075, "score": 0.6993916034698486, "start": 2069, "tag": "KEY", "value": "value1" }, { "context": " data)\n\n data = { key1: 'value1', key2: ...
spec_app/spec/javascripts/up/bus_spec.js.coffee
ktec/unpoly
0
describe 'up.bus', -> describe 'JavaScript functions', -> describe 'up.on', -> it 'registers a delagating event listener to the document body, which passes the $element as a second argument to the listener', asyncSpec (next) -> affix('.container .child') observeClass = jasmine.createSpy() up.on 'click', '.child', (event, $element) -> observeClass($element.attr('class')) Trigger.click($('.container')) Trigger.click($('.child')) next => expect(observeClass).not.toHaveBeenCalledWith('container') expect(observeClass).toHaveBeenCalledWith('child') it 'returns a method that unregisters the event listener when called', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() unsubscribe = up.on 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) unsubscribe() Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error when trying to register the same callback multiple times', -> callback = -> register = -> up.on 'foo', callback register() expect(register).toThrowError(/cannot be registered more than once/i) it 'does not throw an error if a callback is registered, unregistered and registered a second time', -> callback = -> register = -> up.on 'foo', callback unregister = -> up.off 'foo', callback register() unregister() expect(register).not.toThrowError() describe 'passing of [up-data]', -> it 'parses an [up-data] attribute as JSON and passes the parsed object as a third argument to the listener', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) data = { key1: 'value1', key2: 'value2' } $tag = affix(".child").attr('up-data', JSON.stringify(data)) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', data) it 'passes an empty object as a second argument to the listener if there is no [up-data] attribute', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', {}) it 'does not parse an [up-data] attribute if the listener function only takes one argument', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() it 'does not parse an [up-data] attribute if the listener function only takes two arguments', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event, $element) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() describe 'up.off', -> it 'unregisters an event listener previously registered through up.on', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy Trigger.click($('.child')) up.off 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error if the given event listener was not registered through up.on', -> someFunction = -> offing = -> up.off 'click', '.child', someFunction expect(offing).toThrowError(/(not|never) registered/i) it 'reduces the internally tracked list of event listeners (bugfix for memory leak)', -> getCount = -> up.bus.knife.get('Object.keys(liveUpDescriptions).length') oldCount = getCount() expect(oldCount).toBeGreaterThan(0) clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy expect(getCount()).toBe(oldCount + 1) up.off 'click', '.child', clickSpy expect(getCount()).toBe(oldCount) describe 'up.emit', -> it 'triggers an event on the document', -> emittedEvent = undefined emitted$Target = undefined up.on 'foo', (event, $target) -> emittedEvent = event emitted$Target = $target expect(emittedEvent).toBeUndefined() expect(emitted$Target).toBeUndefined() up.emit('foo') expect(emittedEvent).toBeDefined() expect(emittedEvent.preventDefault).toBeDefined() expect(emitted$Target).toEqual($(document)) it 'accepts custom event properties', -> emittedEvent = undefined up.on 'foo', (event) -> emittedEvent = event up.emit('foo', { customField: 'custom-value' }) expect(emittedEvent.customField).toEqual('custom-value') describe 'with .$element option', -> it 'triggers an event on the given element', -> emittedEvent = undefined $emittedTarget = undefined $element = affix('.element').text('foo') up.on 'foo', (event, $target) -> emittedEvent = event $emittedTarget = $target up.emit('foo', $element: $element) expect(emittedEvent).toBeDefined() expect($emittedTarget).toEqual($element) expect(emittedEvent.$element).toEqual($element) describe 'up.bus.deprecateRenamedEvent', -> it 'prints a warning and registers the event listener for the new event name', -> warnSpy = spyOn(up, 'warn') listener = jasmine.createSpy('listener') # Reister listener for the old event name up.on('up:proxy:received', listener) expect(warnSpy).toHaveBeenCalled() # Emit event with new name and see that it invokes the legacy listener up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) # Check that up.off works with the old event name up.off('up:proxy:received', listener) up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) describe 'up.bus.whenEmitted', -> it 'emits the event and fulfills the returned promise when no listener calls event.preventDefault()', (done) -> eventListener = jasmine.createSpy('event listener') up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(eventListener).toHaveBeenCalledWith(jasmine.objectContaining(key: 'value'), jasmine.anything(), jasmine.anything()) expect(result.state).toEqual('fulfilled') done() it 'emits the event and rejects the returned promise when any listener calls event.preventDefault()', (done) -> eventListener = (event) -> event.preventDefault() up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(result.state).toEqual('rejected') done()
145073
describe 'up.bus', -> describe 'JavaScript functions', -> describe 'up.on', -> it 'registers a delagating event listener to the document body, which passes the $element as a second argument to the listener', asyncSpec (next) -> affix('.container .child') observeClass = jasmine.createSpy() up.on 'click', '.child', (event, $element) -> observeClass($element.attr('class')) Trigger.click($('.container')) Trigger.click($('.child')) next => expect(observeClass).not.toHaveBeenCalledWith('container') expect(observeClass).toHaveBeenCalledWith('child') it 'returns a method that unregisters the event listener when called', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() unsubscribe = up.on 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) unsubscribe() Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error when trying to register the same callback multiple times', -> callback = -> register = -> up.on 'foo', callback register() expect(register).toThrowError(/cannot be registered more than once/i) it 'does not throw an error if a callback is registered, unregistered and registered a second time', -> callback = -> register = -> up.on 'foo', callback unregister = -> up.off 'foo', callback register() unregister() expect(register).not.toThrowError() describe 'passing of [up-data]', -> it 'parses an [up-data] attribute as JSON and passes the parsed object as a third argument to the listener', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) data = { key1: '<KEY>', key2: '<KEY>' } $tag = affix(".child").attr('up-data', JSON.stringify(data)) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', data) it 'passes an empty object as a second argument to the listener if there is no [up-data] attribute', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', {}) it 'does not parse an [up-data] attribute if the listener function only takes one argument', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() it 'does not parse an [up-data] attribute if the listener function only takes two arguments', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event, $element) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() describe 'up.off', -> it 'unregisters an event listener previously registered through up.on', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy Trigger.click($('.child')) up.off 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error if the given event listener was not registered through up.on', -> someFunction = -> offing = -> up.off 'click', '.child', someFunction expect(offing).toThrowError(/(not|never) registered/i) it 'reduces the internally tracked list of event listeners (bugfix for memory leak)', -> getCount = -> up.bus.knife.get('Object.keys(liveUpDescriptions).length') oldCount = getCount() expect(oldCount).toBeGreaterThan(0) clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy expect(getCount()).toBe(oldCount + 1) up.off 'click', '.child', clickSpy expect(getCount()).toBe(oldCount) describe 'up.emit', -> it 'triggers an event on the document', -> emittedEvent = undefined emitted$Target = undefined up.on 'foo', (event, $target) -> emittedEvent = event emitted$Target = $target expect(emittedEvent).toBeUndefined() expect(emitted$Target).toBeUndefined() up.emit('foo') expect(emittedEvent).toBeDefined() expect(emittedEvent.preventDefault).toBeDefined() expect(emitted$Target).toEqual($(document)) it 'accepts custom event properties', -> emittedEvent = undefined up.on 'foo', (event) -> emittedEvent = event up.emit('foo', { customField: 'custom-value' }) expect(emittedEvent.customField).toEqual('custom-value') describe 'with .$element option', -> it 'triggers an event on the given element', -> emittedEvent = undefined $emittedTarget = undefined $element = affix('.element').text('foo') up.on 'foo', (event, $target) -> emittedEvent = event $emittedTarget = $target up.emit('foo', $element: $element) expect(emittedEvent).toBeDefined() expect($emittedTarget).toEqual($element) expect(emittedEvent.$element).toEqual($element) describe 'up.bus.deprecateRenamedEvent', -> it 'prints a warning and registers the event listener for the new event name', -> warnSpy = spyOn(up, 'warn') listener = jasmine.createSpy('listener') # Reister listener for the old event name up.on('up:proxy:received', listener) expect(warnSpy).toHaveBeenCalled() # Emit event with new name and see that it invokes the legacy listener up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) # Check that up.off works with the old event name up.off('up:proxy:received', listener) up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) describe 'up.bus.whenEmitted', -> it 'emits the event and fulfills the returned promise when no listener calls event.preventDefault()', (done) -> eventListener = jasmine.createSpy('event listener') up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(eventListener).toHaveBeenCalledWith(jasmine.objectContaining(key: 'value'), jasmine.anything(), jasmine.anything()) expect(result.state).toEqual('fulfilled') done() it 'emits the event and rejects the returned promise when any listener calls event.preventDefault()', (done) -> eventListener = (event) -> event.preventDefault() up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(result.state).toEqual('rejected') done()
true
describe 'up.bus', -> describe 'JavaScript functions', -> describe 'up.on', -> it 'registers a delagating event listener to the document body, which passes the $element as a second argument to the listener', asyncSpec (next) -> affix('.container .child') observeClass = jasmine.createSpy() up.on 'click', '.child', (event, $element) -> observeClass($element.attr('class')) Trigger.click($('.container')) Trigger.click($('.child')) next => expect(observeClass).not.toHaveBeenCalledWith('container') expect(observeClass).toHaveBeenCalledWith('child') it 'returns a method that unregisters the event listener when called', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() unsubscribe = up.on 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) unsubscribe() Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error when trying to register the same callback multiple times', -> callback = -> register = -> up.on 'foo', callback register() expect(register).toThrowError(/cannot be registered more than once/i) it 'does not throw an error if a callback is registered, unregistered and registered a second time', -> callback = -> register = -> up.on 'foo', callback unregister = -> up.off 'foo', callback register() unregister() expect(register).not.toThrowError() describe 'passing of [up-data]', -> it 'parses an [up-data] attribute as JSON and passes the parsed object as a third argument to the listener', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) data = { key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI' } $tag = affix(".child").attr('up-data', JSON.stringify(data)) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', data) it 'passes an empty object as a second argument to the listener if there is no [up-data] attribute', asyncSpec (next) -> $child = affix('.child') observeArgs = jasmine.createSpy() up.on 'click', '.child', (event, $element, data) -> observeArgs($element.attr('class'), data) Trigger.click($('.child')) next => expect(observeArgs).toHaveBeenCalledWith('child', {}) it 'does not parse an [up-data] attribute if the listener function only takes one argument', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() it 'does not parse an [up-data] attribute if the listener function only takes two arguments', asyncSpec (next) -> parseDataSpy = spyOn(up.syntax, 'data').and.returnValue({}) $child = affix('.child') up.on 'click', '.child', (event, $element) -> # no-op Trigger.click($('.child')) next => expect(parseDataSpy).not.toHaveBeenCalled() describe 'up.off', -> it 'unregisters an event listener previously registered through up.on', asyncSpec (next) -> $child = affix('.child') clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy Trigger.click($('.child')) up.off 'click', '.child', clickSpy Trigger.click($('.child')) next => expect(clickSpy.calls.count()).toEqual(1) it 'throws an error if the given event listener was not registered through up.on', -> someFunction = -> offing = -> up.off 'click', '.child', someFunction expect(offing).toThrowError(/(not|never) registered/i) it 'reduces the internally tracked list of event listeners (bugfix for memory leak)', -> getCount = -> up.bus.knife.get('Object.keys(liveUpDescriptions).length') oldCount = getCount() expect(oldCount).toBeGreaterThan(0) clickSpy = jasmine.createSpy() up.on 'click', '.child', clickSpy expect(getCount()).toBe(oldCount + 1) up.off 'click', '.child', clickSpy expect(getCount()).toBe(oldCount) describe 'up.emit', -> it 'triggers an event on the document', -> emittedEvent = undefined emitted$Target = undefined up.on 'foo', (event, $target) -> emittedEvent = event emitted$Target = $target expect(emittedEvent).toBeUndefined() expect(emitted$Target).toBeUndefined() up.emit('foo') expect(emittedEvent).toBeDefined() expect(emittedEvent.preventDefault).toBeDefined() expect(emitted$Target).toEqual($(document)) it 'accepts custom event properties', -> emittedEvent = undefined up.on 'foo', (event) -> emittedEvent = event up.emit('foo', { customField: 'custom-value' }) expect(emittedEvent.customField).toEqual('custom-value') describe 'with .$element option', -> it 'triggers an event on the given element', -> emittedEvent = undefined $emittedTarget = undefined $element = affix('.element').text('foo') up.on 'foo', (event, $target) -> emittedEvent = event $emittedTarget = $target up.emit('foo', $element: $element) expect(emittedEvent).toBeDefined() expect($emittedTarget).toEqual($element) expect(emittedEvent.$element).toEqual($element) describe 'up.bus.deprecateRenamedEvent', -> it 'prints a warning and registers the event listener for the new event name', -> warnSpy = spyOn(up, 'warn') listener = jasmine.createSpy('listener') # Reister listener for the old event name up.on('up:proxy:received', listener) expect(warnSpy).toHaveBeenCalled() # Emit event with new name and see that it invokes the legacy listener up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) # Check that up.off works with the old event name up.off('up:proxy:received', listener) up.emit('up:proxy:loaded') expect(listener.calls.count()).toBe(1) describe 'up.bus.whenEmitted', -> it 'emits the event and fulfills the returned promise when no listener calls event.preventDefault()', (done) -> eventListener = jasmine.createSpy('event listener') up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(eventListener).toHaveBeenCalledWith(jasmine.objectContaining(key: 'value'), jasmine.anything(), jasmine.anything()) expect(result.state).toEqual('fulfilled') done() it 'emits the event and rejects the returned promise when any listener calls event.preventDefault()', (done) -> eventListener = (event) -> event.preventDefault() up.on('my:event', eventListener) promise = up.bus.whenEmitted('my:event', key: 'value') promiseState(promise).then (result) -> expect(result.state).toEqual('rejected') done()
[ { "context": "e database here\n for key of config\n keyU = underscored(humanize(key)).toUpperCase()\n keyC = camelize", "end": 562, "score": 0.7690818309783936, "start": 550, "tag": "KEY", "value": "underscored(" }, { "context": "re\n for key of config\n keyU = u...
src/index.coffee
ndxbxrme/ndx-database-engine
0
'use strict' ObjectID = require 'bson-objectid' settings = require './settings' underscored = require('underscore.string').underscored humanize = require('underscore.string').humanize camelize = require('underscore.string').camelize version = require('../package.json').version callbacks = ready: [] insert: [] update: [] select: [] delete: [] restore: [] safeCallback = (name, obj) -> for cb in callbacks[name] cb obj module.exports = config: (config) -> #configure the database here for key of config keyU = underscored(humanize(key)).toUpperCase() keyC = camelize(humanize(key)).replace(/^./, key[0].toLowerCase()) settings[keyU] = config[keyC] or config[keyU] or settings[keyU] @ start: -> #connect to/start the database @ on: (name, callback) -> #register a callback callbacks[name].push callback @ off: (name, callback) -> #unregister a callback callbacks[name].splice callbacks[name].indexOf(callback), 1 @ serverExec: (type, args) -> #used by ndx-sync exec: (sql, props, notCritical) -> #execute arbitrary sql select: (table, whereObj, page, pageSize, sort, sortDir) -> #return an array of selected objects count: (table, whereObj) -> #returns the number of selected objects update: (table, obj, whereObj) -> #update an object insert: (table, obj) -> #insert an object upsert: (table, obj, whereObj) -> #update or insert an object maintenanceOn: -> maintenanceMode = true maintenanceOff: -> maintenanceMode = false version: -> version maintenance: -> maintenanceMode getDb: -> #returns a copy of the database, used by ndx-database-backup restoreFromBackup: (data) -> #restore the database from a backup consolidate: -> #cleans up the data directory - ndxdb specific uploadDatabase: (cb) -> #save the database immediately into storage cacheSize: -> #used by ndx-profiler resetSqlCache: -> #clears the sql cache - ndxdb specific
120841
'use strict' ObjectID = require 'bson-objectid' settings = require './settings' underscored = require('underscore.string').underscored humanize = require('underscore.string').humanize camelize = require('underscore.string').camelize version = require('../package.json').version callbacks = ready: [] insert: [] update: [] select: [] delete: [] restore: [] safeCallback = (name, obj) -> for cb in callbacks[name] cb obj module.exports = config: (config) -> #configure the database here for key of config keyU = <KEY> <KEY>(key)).<KEY>() keyC = came<KEY>(human<KEY>(key)).replace(/^./, key[0].toLowerCase()) settings[keyU] = config[keyC] or config[keyU] or settings[keyU] @ start: -> #connect to/start the database @ on: (name, callback) -> #register a callback callbacks[name].push callback @ off: (name, callback) -> #unregister a callback callbacks[name].splice callbacks[name].indexOf(callback), 1 @ serverExec: (type, args) -> #used by ndx-sync exec: (sql, props, notCritical) -> #execute arbitrary sql select: (table, whereObj, page, pageSize, sort, sortDir) -> #return an array of selected objects count: (table, whereObj) -> #returns the number of selected objects update: (table, obj, whereObj) -> #update an object insert: (table, obj) -> #insert an object upsert: (table, obj, whereObj) -> #update or insert an object maintenanceOn: -> maintenanceMode = true maintenanceOff: -> maintenanceMode = false version: -> version maintenance: -> maintenanceMode getDb: -> #returns a copy of the database, used by ndx-database-backup restoreFromBackup: (data) -> #restore the database from a backup consolidate: -> #cleans up the data directory - ndxdb specific uploadDatabase: (cb) -> #save the database immediately into storage cacheSize: -> #used by ndx-profiler resetSqlCache: -> #clears the sql cache - ndxdb specific
true
'use strict' ObjectID = require 'bson-objectid' settings = require './settings' underscored = require('underscore.string').underscored humanize = require('underscore.string').humanize camelize = require('underscore.string').camelize version = require('../package.json').version callbacks = ready: [] insert: [] update: [] select: [] delete: [] restore: [] safeCallback = (name, obj) -> for cb in callbacks[name] cb obj module.exports = config: (config) -> #configure the database here for key of config keyU = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI(key)).PI:KEY:<KEY>END_PI() keyC = camePI:KEY:<KEY>END_PI(humanPI:KEY:<KEY>END_PI(key)).replace(/^./, key[0].toLowerCase()) settings[keyU] = config[keyC] or config[keyU] or settings[keyU] @ start: -> #connect to/start the database @ on: (name, callback) -> #register a callback callbacks[name].push callback @ off: (name, callback) -> #unregister a callback callbacks[name].splice callbacks[name].indexOf(callback), 1 @ serverExec: (type, args) -> #used by ndx-sync exec: (sql, props, notCritical) -> #execute arbitrary sql select: (table, whereObj, page, pageSize, sort, sortDir) -> #return an array of selected objects count: (table, whereObj) -> #returns the number of selected objects update: (table, obj, whereObj) -> #update an object insert: (table, obj) -> #insert an object upsert: (table, obj, whereObj) -> #update or insert an object maintenanceOn: -> maintenanceMode = true maintenanceOff: -> maintenanceMode = false version: -> version maintenance: -> maintenanceMode getDb: -> #returns a copy of the database, used by ndx-database-backup restoreFromBackup: (data) -> #restore the database from a backup consolidate: -> #cleans up the data directory - ndxdb specific uploadDatabase: (cb) -> #save the database immediately into storage cacheSize: -> #used by ndx-profiler resetSqlCache: -> #clears the sql cache - ndxdb specific
[ { "context": "rview Enforce props alphabetical sorting\n# @author Yannick Croissant\n###\n\n'use strict'\n\n# ----------------------------", "end": 83, "score": 0.9998615980148315, "start": 66, "tag": "NAME", "value": "Yannick Croissant" } ]
src/tests/rules/jsx-sort-props.coffee
danielbayley/eslint-plugin-coffee
0
###* # @fileoverview Enforce props alphabetical sorting # @author Yannick Croissant ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require 'eslint-plugin-react/lib/rules/jsx-sort-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Props should be sorted alphabetically' type: 'JSXIdentifier' expectedCallbackError = message: 'Callbacks must be listed after all other props' type: 'JSXIdentifier' expectedShorthandFirstError = message: 'Shorthand props must be listed before all other props' type: 'JSXIdentifier' expectedShorthandLastError = message: 'Shorthand props must be listed after all other props' type: 'JSXIdentifier' expectedReservedFirstError = message: 'Reserved props must be listed before all other props' type: 'JSXIdentifier' expectedEmptyReservedFirstError = message: 'A customized reserved first list must not be empty' expectedInvalidReservedFirstError = message: 'A customized reserved first list must only contain a subset of React reserved props. Remove: notReserved' callbacksLastArgs = [callbacksLast: yes] ignoreCaseAndCallbackLastArgs = [ callbacksLast: yes ignoreCase: yes ] shorthandFirstArgs = [shorthandFirst: yes] shorthandLastArgs = [shorthandLast: yes] shorthandAndCallbackLastArgs = [ callbacksLast: yes shorthandLast: yes ] ignoreCaseArgs = [ignoreCase: yes] noSortAlphabeticallyArgs = [noSortAlphabetically: yes] sortAlphabeticallyArgs = [noSortAlphabetically: no] reservedFirstAsBooleanArgs = [reservedFirst: yes] reservedFirstAsArrayArgs = [ reservedFirst: ['children', 'dangerouslySetInnerHTML', 'key'] ] reservedFirstWithNoSortAlphabeticallyArgs = [ noSortAlphabetically: yes reservedFirst: yes ] reservedFirstWithShorthandLast = [ reservedFirst: yes shorthandLast: yes ] reservedFirstAsEmptyArrayArgs = [reservedFirst: []] reservedFirstAsInvalidArrayArgs = [reservedFirst: ['notReserved']] ruleTester.run 'jsx-sort-props', rule, valid: [ code: '<App />' , code: '<App {...this.props} />' , code: '<App a b c />' , code: '<App {...this.props} a b c />' , code: '<App c {...this.props} a b />' , code: '<App a="c" b="b" c="a" />' , code: '<App {...this.props} a="c" b="b" c="a" />' , code: '<App c="a" {...this.props} a="c" b="b" />' , code: '<App a A />' , # Ignoring case code: '<App a A />', options: ignoreCaseArgs , code: '<App a B c />', options: ignoreCaseArgs , code: '<App A b C />', options: ignoreCaseArgs , # Sorting callbacks below all other props code: '<App a z onBar onFoo />', options: callbacksLastArgs , code: '<App z onBar onFoo />', options: ignoreCaseAndCallbackLastArgs , # Sorting shorthand props before others code: '<App a b="b" />', options: shorthandFirstArgs , code: '<App z a="a" />', options: shorthandFirstArgs , code: '<App x y z a="a" b="b" />', options: shorthandFirstArgs , code: '<App a="a" b="b" x y z />', options: shorthandLastArgs , code: '<App a="a" b="b" x y z onBar onFoo />' options: shorthandAndCallbackLastArgs , # noSortAlphabetically code: '<App a b />', options: noSortAlphabeticallyArgs , code: '<App b a />', options: noSortAlphabeticallyArgs , # reservedFirst code: '<App children={<App />} key={0} ref="r" a b c />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} ref="r" a b c dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} a ref="r" />' options: reservedFirstAsArrayArgs , code: '<App children={<App />} key={0} a dangerouslySetInnerHTML={{__html: "EPR"}} ref="r" />' options: reservedFirstAsArrayArgs , code: '<App ref="r" key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<div ref="r" dangerouslySetInnerHTML={{__html: "EPR"}} key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<App key="key" c="c" b />' options: reservedFirstWithShorthandLast ] invalid: [ code: '<App b a />' errors: [expectedError] output: '<App a b />' , code: '<App {...this.props} b a />' errors: [expectedError] output: '<App {...this.props} a b />' , code: '<App c {...this.props} b a />' errors: [expectedError] output: '<App c {...this.props} a b />' , code: '<App A a />' errors: [expectedError] output: '<App a A />' , code: '<App B a />' options: ignoreCaseArgs errors: [expectedError] output: '<App a B />' , code: '<App B A c />' options: ignoreCaseArgs errors: [expectedError] output: '<App A B c />' , code: '<App c="a" a="c" b="b" />' output: '<App a="c" b="b" c="a" />' errors: 2 , code: '<App {...this.props} c="a" a="c" b="b" />' output: '<App {...this.props} a="c" b="b" c="a" />' errors: 2 , code: '<App d="d" b="b" {...this.props} c="a" a="c" />' output: '<App b="b" d="d" {...this.props} a="c" c="a" />' errors: 2 , code: ''' <App a={true} z r _onClick={->} onHandle={->} {...this.props} b={false} {...otherProps} > {test} </App> ''' output: ''' <App _onClick={->} a={true} onHandle={->} r z {...this.props} b={false} {...otherProps} > {test} </App> ''' errors: 3 , code: '<App key="key" b c="c" />' errors: [expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App ref="ref" key="key" isShorthand veryLastAttribute="yes" />' errors: [expectedError, expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App a z onFoo onBar />' errors: [expectedError] options: callbacksLastArgs , code: '<App a onBar onFoo z />' errors: [expectedCallbackError] options: callbacksLastArgs , code: '<App a="a" b />' errors: [expectedShorthandFirstError] options: shorthandFirstArgs , code: '<App z x a="a" />' errors: [expectedError] options: shorthandFirstArgs , code: '<App b a="a" />' errors: [expectedShorthandLastError] options: shorthandLastArgs , code: '<App a="a" onBar onFoo z x />' errors: [shorthandAndCallbackLastArgs] options: shorthandLastArgs , code: '<App b a />' errors: [expectedError] options: sortAlphabeticallyArgs , # reservedFirst code: '<App a key={1} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<div a dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<App ref="r" key={2} b />' options: reservedFirstAsBooleanArgs errors: [expectedError] , code: '<App key={2} b a />' options: reservedFirstAsBooleanArgs output: '<App key={2} a b />' errors: [expectedError] , code: '<App b a />' options: reservedFirstAsBooleanArgs output: '<App a b />' errors: [expectedError] , code: '<App dangerouslySetInnerHTML={{__html: "EPR"}} e key={2} b />' options: reservedFirstAsBooleanArgs output: '<App key={2} b dangerouslySetInnerHTML={{__html: "EPR"}} e />' errors: [expectedReservedFirstError, expectedError] , code: '<App key={3} children={<App />} />' options: reservedFirstAsArrayArgs errors: [expectedError] , code: '<App z ref="r" />' options: reservedFirstWithNoSortAlphabeticallyArgs errors: [expectedReservedFirstError] , code: '<App key={4} />' options: reservedFirstAsEmptyArrayArgs errors: [expectedEmptyReservedFirstError] , code: '<App key={5} />' options: reservedFirstAsInvalidArrayArgs errors: [expectedInvalidReservedFirstError] ]
85707
###* # @fileoverview Enforce props alphabetical sorting # @author <NAME> ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require 'eslint-plugin-react/lib/rules/jsx-sort-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Props should be sorted alphabetically' type: 'JSXIdentifier' expectedCallbackError = message: 'Callbacks must be listed after all other props' type: 'JSXIdentifier' expectedShorthandFirstError = message: 'Shorthand props must be listed before all other props' type: 'JSXIdentifier' expectedShorthandLastError = message: 'Shorthand props must be listed after all other props' type: 'JSXIdentifier' expectedReservedFirstError = message: 'Reserved props must be listed before all other props' type: 'JSXIdentifier' expectedEmptyReservedFirstError = message: 'A customized reserved first list must not be empty' expectedInvalidReservedFirstError = message: 'A customized reserved first list must only contain a subset of React reserved props. Remove: notReserved' callbacksLastArgs = [callbacksLast: yes] ignoreCaseAndCallbackLastArgs = [ callbacksLast: yes ignoreCase: yes ] shorthandFirstArgs = [shorthandFirst: yes] shorthandLastArgs = [shorthandLast: yes] shorthandAndCallbackLastArgs = [ callbacksLast: yes shorthandLast: yes ] ignoreCaseArgs = [ignoreCase: yes] noSortAlphabeticallyArgs = [noSortAlphabetically: yes] sortAlphabeticallyArgs = [noSortAlphabetically: no] reservedFirstAsBooleanArgs = [reservedFirst: yes] reservedFirstAsArrayArgs = [ reservedFirst: ['children', 'dangerouslySetInnerHTML', 'key'] ] reservedFirstWithNoSortAlphabeticallyArgs = [ noSortAlphabetically: yes reservedFirst: yes ] reservedFirstWithShorthandLast = [ reservedFirst: yes shorthandLast: yes ] reservedFirstAsEmptyArrayArgs = [reservedFirst: []] reservedFirstAsInvalidArrayArgs = [reservedFirst: ['notReserved']] ruleTester.run 'jsx-sort-props', rule, valid: [ code: '<App />' , code: '<App {...this.props} />' , code: '<App a b c />' , code: '<App {...this.props} a b c />' , code: '<App c {...this.props} a b />' , code: '<App a="c" b="b" c="a" />' , code: '<App {...this.props} a="c" b="b" c="a" />' , code: '<App c="a" {...this.props} a="c" b="b" />' , code: '<App a A />' , # Ignoring case code: '<App a A />', options: ignoreCaseArgs , code: '<App a B c />', options: ignoreCaseArgs , code: '<App A b C />', options: ignoreCaseArgs , # Sorting callbacks below all other props code: '<App a z onBar onFoo />', options: callbacksLastArgs , code: '<App z onBar onFoo />', options: ignoreCaseAndCallbackLastArgs , # Sorting shorthand props before others code: '<App a b="b" />', options: shorthandFirstArgs , code: '<App z a="a" />', options: shorthandFirstArgs , code: '<App x y z a="a" b="b" />', options: shorthandFirstArgs , code: '<App a="a" b="b" x y z />', options: shorthandLastArgs , code: '<App a="a" b="b" x y z onBar onFoo />' options: shorthandAndCallbackLastArgs , # noSortAlphabetically code: '<App a b />', options: noSortAlphabeticallyArgs , code: '<App b a />', options: noSortAlphabeticallyArgs , # reservedFirst code: '<App children={<App />} key={0} ref="r" a b c />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} ref="r" a b c dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} a ref="r" />' options: reservedFirstAsArrayArgs , code: '<App children={<App />} key={0} a dangerouslySetInnerHTML={{__html: "EPR"}} ref="r" />' options: reservedFirstAsArrayArgs , code: '<App ref="r" key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<div ref="r" dangerouslySetInnerHTML={{__html: "EPR"}} key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<App key="key" c="c" b />' options: reservedFirstWithShorthandLast ] invalid: [ code: '<App b a />' errors: [expectedError] output: '<App a b />' , code: '<App {...this.props} b a />' errors: [expectedError] output: '<App {...this.props} a b />' , code: '<App c {...this.props} b a />' errors: [expectedError] output: '<App c {...this.props} a b />' , code: '<App A a />' errors: [expectedError] output: '<App a A />' , code: '<App B a />' options: ignoreCaseArgs errors: [expectedError] output: '<App a B />' , code: '<App B A c />' options: ignoreCaseArgs errors: [expectedError] output: '<App A B c />' , code: '<App c="a" a="c" b="b" />' output: '<App a="c" b="b" c="a" />' errors: 2 , code: '<App {...this.props} c="a" a="c" b="b" />' output: '<App {...this.props} a="c" b="b" c="a" />' errors: 2 , code: '<App d="d" b="b" {...this.props} c="a" a="c" />' output: '<App b="b" d="d" {...this.props} a="c" c="a" />' errors: 2 , code: ''' <App a={true} z r _onClick={->} onHandle={->} {...this.props} b={false} {...otherProps} > {test} </App> ''' output: ''' <App _onClick={->} a={true} onHandle={->} r z {...this.props} b={false} {...otherProps} > {test} </App> ''' errors: 3 , code: '<App key="key" b c="c" />' errors: [expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App ref="ref" key="key" isShorthand veryLastAttribute="yes" />' errors: [expectedError, expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App a z onFoo onBar />' errors: [expectedError] options: callbacksLastArgs , code: '<App a onBar onFoo z />' errors: [expectedCallbackError] options: callbacksLastArgs , code: '<App a="a" b />' errors: [expectedShorthandFirstError] options: shorthandFirstArgs , code: '<App z x a="a" />' errors: [expectedError] options: shorthandFirstArgs , code: '<App b a="a" />' errors: [expectedShorthandLastError] options: shorthandLastArgs , code: '<App a="a" onBar onFoo z x />' errors: [shorthandAndCallbackLastArgs] options: shorthandLastArgs , code: '<App b a />' errors: [expectedError] options: sortAlphabeticallyArgs , # reservedFirst code: '<App a key={1} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<div a dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<App ref="r" key={2} b />' options: reservedFirstAsBooleanArgs errors: [expectedError] , code: '<App key={2} b a />' options: reservedFirstAsBooleanArgs output: '<App key={2} a b />' errors: [expectedError] , code: '<App b a />' options: reservedFirstAsBooleanArgs output: '<App a b />' errors: [expectedError] , code: '<App dangerouslySetInnerHTML={{__html: "EPR"}} e key={2} b />' options: reservedFirstAsBooleanArgs output: '<App key={2} b dangerouslySetInnerHTML={{__html: "EPR"}} e />' errors: [expectedReservedFirstError, expectedError] , code: '<App key={3} children={<App />} />' options: reservedFirstAsArrayArgs errors: [expectedError] , code: '<App z ref="r" />' options: reservedFirstWithNoSortAlphabeticallyArgs errors: [expectedReservedFirstError] , code: '<App key={4} />' options: reservedFirstAsEmptyArrayArgs errors: [expectedEmptyReservedFirstError] , code: '<App key={5} />' options: reservedFirstAsInvalidArrayArgs errors: [expectedInvalidReservedFirstError] ]
true
###* # @fileoverview Enforce props alphabetical sorting # @author PI:NAME:<NAME>END_PI ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require 'eslint-plugin-react/lib/rules/jsx-sort-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Props should be sorted alphabetically' type: 'JSXIdentifier' expectedCallbackError = message: 'Callbacks must be listed after all other props' type: 'JSXIdentifier' expectedShorthandFirstError = message: 'Shorthand props must be listed before all other props' type: 'JSXIdentifier' expectedShorthandLastError = message: 'Shorthand props must be listed after all other props' type: 'JSXIdentifier' expectedReservedFirstError = message: 'Reserved props must be listed before all other props' type: 'JSXIdentifier' expectedEmptyReservedFirstError = message: 'A customized reserved first list must not be empty' expectedInvalidReservedFirstError = message: 'A customized reserved first list must only contain a subset of React reserved props. Remove: notReserved' callbacksLastArgs = [callbacksLast: yes] ignoreCaseAndCallbackLastArgs = [ callbacksLast: yes ignoreCase: yes ] shorthandFirstArgs = [shorthandFirst: yes] shorthandLastArgs = [shorthandLast: yes] shorthandAndCallbackLastArgs = [ callbacksLast: yes shorthandLast: yes ] ignoreCaseArgs = [ignoreCase: yes] noSortAlphabeticallyArgs = [noSortAlphabetically: yes] sortAlphabeticallyArgs = [noSortAlphabetically: no] reservedFirstAsBooleanArgs = [reservedFirst: yes] reservedFirstAsArrayArgs = [ reservedFirst: ['children', 'dangerouslySetInnerHTML', 'key'] ] reservedFirstWithNoSortAlphabeticallyArgs = [ noSortAlphabetically: yes reservedFirst: yes ] reservedFirstWithShorthandLast = [ reservedFirst: yes shorthandLast: yes ] reservedFirstAsEmptyArrayArgs = [reservedFirst: []] reservedFirstAsInvalidArrayArgs = [reservedFirst: ['notReserved']] ruleTester.run 'jsx-sort-props', rule, valid: [ code: '<App />' , code: '<App {...this.props} />' , code: '<App a b c />' , code: '<App {...this.props} a b c />' , code: '<App c {...this.props} a b />' , code: '<App a="c" b="b" c="a" />' , code: '<App {...this.props} a="c" b="b" c="a" />' , code: '<App c="a" {...this.props} a="c" b="b" />' , code: '<App a A />' , # Ignoring case code: '<App a A />', options: ignoreCaseArgs , code: '<App a B c />', options: ignoreCaseArgs , code: '<App A b C />', options: ignoreCaseArgs , # Sorting callbacks below all other props code: '<App a z onBar onFoo />', options: callbacksLastArgs , code: '<App z onBar onFoo />', options: ignoreCaseAndCallbackLastArgs , # Sorting shorthand props before others code: '<App a b="b" />', options: shorthandFirstArgs , code: '<App z a="a" />', options: shorthandFirstArgs , code: '<App x y z a="a" b="b" />', options: shorthandFirstArgs , code: '<App a="a" b="b" x y z />', options: shorthandLastArgs , code: '<App a="a" b="b" x y z onBar onFoo />' options: shorthandAndCallbackLastArgs , # noSortAlphabetically code: '<App a b />', options: noSortAlphabeticallyArgs , code: '<App b a />', options: noSortAlphabeticallyArgs , # reservedFirst code: '<App children={<App />} key={0} ref="r" a b c />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} ref="r" a b c dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs , code: '<App children={<App />} key={0} a ref="r" />' options: reservedFirstAsArrayArgs , code: '<App children={<App />} key={0} a dangerouslySetInnerHTML={{__html: "EPR"}} ref="r" />' options: reservedFirstAsArrayArgs , code: '<App ref="r" key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<div ref="r" dangerouslySetInnerHTML={{__html: "EPR"}} key={0} children={<App />} b a c />' options: reservedFirstWithNoSortAlphabeticallyArgs , code: '<App key="key" c="c" b />' options: reservedFirstWithShorthandLast ] invalid: [ code: '<App b a />' errors: [expectedError] output: '<App a b />' , code: '<App {...this.props} b a />' errors: [expectedError] output: '<App {...this.props} a b />' , code: '<App c {...this.props} b a />' errors: [expectedError] output: '<App c {...this.props} a b />' , code: '<App A a />' errors: [expectedError] output: '<App a A />' , code: '<App B a />' options: ignoreCaseArgs errors: [expectedError] output: '<App a B />' , code: '<App B A c />' options: ignoreCaseArgs errors: [expectedError] output: '<App A B c />' , code: '<App c="a" a="c" b="b" />' output: '<App a="c" b="b" c="a" />' errors: 2 , code: '<App {...this.props} c="a" a="c" b="b" />' output: '<App {...this.props} a="c" b="b" c="a" />' errors: 2 , code: '<App d="d" b="b" {...this.props} c="a" a="c" />' output: '<App b="b" d="d" {...this.props} a="c" c="a" />' errors: 2 , code: ''' <App a={true} z r _onClick={->} onHandle={->} {...this.props} b={false} {...otherProps} > {test} </App> ''' output: ''' <App _onClick={->} a={true} onHandle={->} r z {...this.props} b={false} {...otherProps} > {test} </App> ''' errors: 3 , code: '<App key="key" b c="c" />' errors: [expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App ref="ref" key="key" isShorthand veryLastAttribute="yes" />' errors: [expectedError, expectedShorthandLastError] options: reservedFirstWithShorthandLast , code: '<App a z onFoo onBar />' errors: [expectedError] options: callbacksLastArgs , code: '<App a onBar onFoo z />' errors: [expectedCallbackError] options: callbacksLastArgs , code: '<App a="a" b />' errors: [expectedShorthandFirstError] options: shorthandFirstArgs , code: '<App z x a="a" />' errors: [expectedError] options: shorthandFirstArgs , code: '<App b a="a" />' errors: [expectedShorthandLastError] options: shorthandLastArgs , code: '<App a="a" onBar onFoo z x />' errors: [shorthandAndCallbackLastArgs] options: shorthandLastArgs , code: '<App b a />' errors: [expectedError] options: sortAlphabeticallyArgs , # reservedFirst code: '<App a key={1} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<div a dangerouslySetInnerHTML={{__html: "EPR"}} />' options: reservedFirstAsBooleanArgs errors: [expectedReservedFirstError] , code: '<App ref="r" key={2} b />' options: reservedFirstAsBooleanArgs errors: [expectedError] , code: '<App key={2} b a />' options: reservedFirstAsBooleanArgs output: '<App key={2} a b />' errors: [expectedError] , code: '<App b a />' options: reservedFirstAsBooleanArgs output: '<App a b />' errors: [expectedError] , code: '<App dangerouslySetInnerHTML={{__html: "EPR"}} e key={2} b />' options: reservedFirstAsBooleanArgs output: '<App key={2} b dangerouslySetInnerHTML={{__html: "EPR"}} e />' errors: [expectedReservedFirstError, expectedError] , code: '<App key={3} children={<App />} />' options: reservedFirstAsArrayArgs errors: [expectedError] , code: '<App z ref="r" />' options: reservedFirstWithNoSortAlphabeticallyArgs errors: [expectedReservedFirstError] , code: '<App key={4} />' options: reservedFirstAsEmptyArrayArgs errors: [expectedEmptyReservedFirstError] , code: '<App key={5} />' options: reservedFirstAsInvalidArrayArgs errors: [expectedInvalidReservedFirstError] ]
[ { "context": "l\", () ->\n myModel = @myEntity.create(name: 'Luccas Marks')\n\n expect(myModel.isNew()).toBe(true)\n ", "end": 2418, "score": 0.999880313873291, "start": 2406, "tag": "NAME", "value": "Luccas Marks" }, { "context": "oBe(true)\n expect(myModel.get('n...
spec/javascripts/core/entities/entity.spec.coffee
houzelio/houzel
2
import Entity from 'javascripts/core/entities/entity' import sinon from 'sinon' describe("Entity", () -> MyEntity = Entity.extend({ urlRoot: "/foo-model" url: "/foo-collection" }) beforeEach -> @server = sinon.fakeServer.create() @myEntity = new MyEntity afterEach -> @server.restore() describe("with model and/or collection class", () -> beforeEach -> @MyModel = Backbone.Model.extend(urlRoot: "/foo-model") @MyCollection = Backbone.Collection.extend(url: "/foo-collection") MyOtherEntity = MyEntity.extend({ modelClass: @MyModel collectionClass: @MyCollection }) @myEntity = new MyOtherEntity it("shoud associate the model class defined with the entity", () -> expect(@myEntity._getModel()).toBeInstanceOf(@MyModel) ) it("shoud associate the collection class defined with the entity", () -> expect(@myEntity._getCollection()).toBeInstanceOf(@MyCollection) ) ) describe("without a model and/or collection class", () -> it("should set up a model class with the urlRoot", () -> myModel = @myEntity._getModel() expect(myModel).toBeInstanceOf(Backbone.Model) expect(myModel.urlRoot).toBe("/foo-model") ) it("should set up a collection class with the url", () -> myCollection = @myEntity._getCollection() expect(myCollection).toBeInstanceOf(Backbone.Collection) expect(myCollection.url).toBe("/foo-collection") ) it("should use the urlRoot as default when setting up a collection class whithout the url option", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" }) myEntity = new MyOtherEntity myCollection = myEntity._getCollection() expect(myCollection.url).toBe("/foo") ) it("should set up a model class with validation when it's set", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" validation: patient_id: required: true msg: "Required field" }) myEntity = new MyOtherEntity myModel = myEntity._getModel() expect(_.allKeys(myModel)).toContain('validation') ) ) describe("::create", () -> beforeEach -> MyOtherEntity = Entity.extend(urlRoot: "/foo/model") @myEntity = new MyOtherEntity it("creates a new model", () -> myModel = @myEntity.create(name: 'Luccas Marks') expect(myModel.isNew()).toBe(true) expect(myModel.get('name')).toBe('Luccas Marks') ) it("creates a new model fetching data from server", () -> url = new RegExp("/foo\\/model\\/new\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({name: "Joseane Fogaça"}) ]) myModel = @myEntity.create(null, {urlRoot: "/foo/model/new", fetch: true}) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("Joseane Fogaça") ) ) describe("::get", () -> it("gets a model", () -> url = new RegExp("/foo-model\\/2\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({id:2, name: "Ella Fay"}) ]) myModel = @myEntity.get(2) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("Ella Fay") ) ) describe("::getList", () -> it("gets a collection", () -> url = new RegExp("/foo-collection\\?page\\=1&per_page\\=10\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({ items: [{id: 1, name: "Joseane Fogaça"}, {id: 2, name: "Ella Fay"}] }) ]) myCollection = @myEntity.getList() @server.respond() expect(myCollection.length).toBe(2) expect(myCollection.get(2).get('name')).toBe("Ella Fay") ) ) )
98870
import Entity from 'javascripts/core/entities/entity' import sinon from 'sinon' describe("Entity", () -> MyEntity = Entity.extend({ urlRoot: "/foo-model" url: "/foo-collection" }) beforeEach -> @server = sinon.fakeServer.create() @myEntity = new MyEntity afterEach -> @server.restore() describe("with model and/or collection class", () -> beforeEach -> @MyModel = Backbone.Model.extend(urlRoot: "/foo-model") @MyCollection = Backbone.Collection.extend(url: "/foo-collection") MyOtherEntity = MyEntity.extend({ modelClass: @MyModel collectionClass: @MyCollection }) @myEntity = new MyOtherEntity it("shoud associate the model class defined with the entity", () -> expect(@myEntity._getModel()).toBeInstanceOf(@MyModel) ) it("shoud associate the collection class defined with the entity", () -> expect(@myEntity._getCollection()).toBeInstanceOf(@MyCollection) ) ) describe("without a model and/or collection class", () -> it("should set up a model class with the urlRoot", () -> myModel = @myEntity._getModel() expect(myModel).toBeInstanceOf(Backbone.Model) expect(myModel.urlRoot).toBe("/foo-model") ) it("should set up a collection class with the url", () -> myCollection = @myEntity._getCollection() expect(myCollection).toBeInstanceOf(Backbone.Collection) expect(myCollection.url).toBe("/foo-collection") ) it("should use the urlRoot as default when setting up a collection class whithout the url option", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" }) myEntity = new MyOtherEntity myCollection = myEntity._getCollection() expect(myCollection.url).toBe("/foo") ) it("should set up a model class with validation when it's set", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" validation: patient_id: required: true msg: "Required field" }) myEntity = new MyOtherEntity myModel = myEntity._getModel() expect(_.allKeys(myModel)).toContain('validation') ) ) describe("::create", () -> beforeEach -> MyOtherEntity = Entity.extend(urlRoot: "/foo/model") @myEntity = new MyOtherEntity it("creates a new model", () -> myModel = @myEntity.create(name: '<NAME>') expect(myModel.isNew()).toBe(true) expect(myModel.get('name')).toBe('<NAME>') ) it("creates a new model fetching data from server", () -> url = new RegExp("/foo\\/model\\/new\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({name: "<NAME>"}) ]) myModel = @myEntity.create(null, {urlRoot: "/foo/model/new", fetch: true}) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("<NAME>") ) ) describe("::get", () -> it("gets a model", () -> url = new RegExp("/foo-model\\/2\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({id:2, name: "<NAME>"}) ]) myModel = @myEntity.get(2) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("<NAME>") ) ) describe("::getList", () -> it("gets a collection", () -> url = new RegExp("/foo-collection\\?page\\=1&per_page\\=10\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({ items: [{id: 1, name: "<NAME>"}, {id: 2, name: "<NAME>"}] }) ]) myCollection = @myEntity.getList() @server.respond() expect(myCollection.length).toBe(2) expect(myCollection.get(2).get('name')).toBe("<NAME>") ) ) )
true
import Entity from 'javascripts/core/entities/entity' import sinon from 'sinon' describe("Entity", () -> MyEntity = Entity.extend({ urlRoot: "/foo-model" url: "/foo-collection" }) beforeEach -> @server = sinon.fakeServer.create() @myEntity = new MyEntity afterEach -> @server.restore() describe("with model and/or collection class", () -> beforeEach -> @MyModel = Backbone.Model.extend(urlRoot: "/foo-model") @MyCollection = Backbone.Collection.extend(url: "/foo-collection") MyOtherEntity = MyEntity.extend({ modelClass: @MyModel collectionClass: @MyCollection }) @myEntity = new MyOtherEntity it("shoud associate the model class defined with the entity", () -> expect(@myEntity._getModel()).toBeInstanceOf(@MyModel) ) it("shoud associate the collection class defined with the entity", () -> expect(@myEntity._getCollection()).toBeInstanceOf(@MyCollection) ) ) describe("without a model and/or collection class", () -> it("should set up a model class with the urlRoot", () -> myModel = @myEntity._getModel() expect(myModel).toBeInstanceOf(Backbone.Model) expect(myModel.urlRoot).toBe("/foo-model") ) it("should set up a collection class with the url", () -> myCollection = @myEntity._getCollection() expect(myCollection).toBeInstanceOf(Backbone.Collection) expect(myCollection.url).toBe("/foo-collection") ) it("should use the urlRoot as default when setting up a collection class whithout the url option", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" }) myEntity = new MyOtherEntity myCollection = myEntity._getCollection() expect(myCollection.url).toBe("/foo") ) it("should set up a model class with validation when it's set", () -> MyOtherEntity = Entity.extend({ urlRoot: "/foo" validation: patient_id: required: true msg: "Required field" }) myEntity = new MyOtherEntity myModel = myEntity._getModel() expect(_.allKeys(myModel)).toContain('validation') ) ) describe("::create", () -> beforeEach -> MyOtherEntity = Entity.extend(urlRoot: "/foo/model") @myEntity = new MyOtherEntity it("creates a new model", () -> myModel = @myEntity.create(name: 'PI:NAME:<NAME>END_PI') expect(myModel.isNew()).toBe(true) expect(myModel.get('name')).toBe('PI:NAME:<NAME>END_PI') ) it("creates a new model fetching data from server", () -> url = new RegExp("/foo\\/model\\/new\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({name: "PI:NAME:<NAME>END_PI"}) ]) myModel = @myEntity.create(null, {urlRoot: "/foo/model/new", fetch: true}) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("PI:NAME:<NAME>END_PI") ) ) describe("::get", () -> it("gets a model", () -> url = new RegExp("/foo-model\\/2\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({id:2, name: "PI:NAME:<NAME>END_PI"}) ]) myModel = @myEntity.get(2) @server.respond() expect(myModel._fetch.status).toBe(200) expect(myModel.get('name')).toBe("PI:NAME:<NAME>END_PI") ) ) describe("::getList", () -> it("gets a collection", () -> url = new RegExp("/foo-collection\\?page\\=1&per_page\\=10\\w*") @server.respondWith("GET", url, [ 200, { "Content-Type": "application/json" }, JSON.stringify({ items: [{id: 1, name: "PI:NAME:<NAME>END_PI"}, {id: 2, name: "PI:NAME:<NAME>END_PI"}] }) ]) myCollection = @myEntity.getList() @server.respond() expect(myCollection.length).toBe(2) expect(myCollection.get(2).get('name')).toBe("PI:NAME:<NAME>END_PI") ) ) )
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993383288383484, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "n \"linux\"\n filter = (e) ->\n e.address is \"127.0.0.1\"\n\n actual = interfaces....
test/simple/test-os.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") os = require("os") process.env.TMPDIR = "/tmpdir" process.env.TMP = "/tmp" process.env.TEMP = "/temp" if process.platform is "win32" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" expected = (process.env.SystemRoot or process.env.windir) + "\\temp" assert.equal os.tmpdir(), expected else assert.equal os.tmpdir(), "/tmpdir" process.env.TMPDIR = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" endianness = os.endianness() console.log "endianness = %s", endianness assert.ok /[BL]E/.test(endianness) hostname = os.hostname() console.log "hostname = %s", hostname assert.ok hostname.length > 0 uptime = os.uptime() console.log "uptime = %d", uptime assert.ok uptime > 0 cpus = os.cpus() console.log "cpus = ", cpus assert.ok cpus.length > 0 type = os.type() console.log "type = ", type assert.ok type.length > 0 release = os.release() console.log "release = ", release assert.ok release.length > 0 platform = os.platform() console.log "platform = ", platform assert.ok platform.length > 0 arch = os.arch() console.log "arch = ", arch assert.ok arch.length > 0 unless process.platform is "sunos" # not implemeneted yet assert.ok os.loadavg().length > 0 assert.ok os.freemem() > 0 assert.ok os.totalmem() > 0 interfaces = os.networkInterfaces() console.error interfaces switch platform when "linux" filter = (e) -> e.address is "127.0.0.1" actual = interfaces.lo.filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected when "win32" filter = (e) -> e.address is "127.0.0.1" actual = interfaces["Loopback Pseudo-Interface 1"].filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected EOL = os.EOL assert.ok EOL.length > 0
107673
# 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") os = require("os") process.env.TMPDIR = "/tmpdir" process.env.TMP = "/tmp" process.env.TEMP = "/temp" if process.platform is "win32" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" expected = (process.env.SystemRoot or process.env.windir) + "\\temp" assert.equal os.tmpdir(), expected else assert.equal os.tmpdir(), "/tmpdir" process.env.TMPDIR = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" endianness = os.endianness() console.log "endianness = %s", endianness assert.ok /[BL]E/.test(endianness) hostname = os.hostname() console.log "hostname = %s", hostname assert.ok hostname.length > 0 uptime = os.uptime() console.log "uptime = %d", uptime assert.ok uptime > 0 cpus = os.cpus() console.log "cpus = ", cpus assert.ok cpus.length > 0 type = os.type() console.log "type = ", type assert.ok type.length > 0 release = os.release() console.log "release = ", release assert.ok release.length > 0 platform = os.platform() console.log "platform = ", platform assert.ok platform.length > 0 arch = os.arch() console.log "arch = ", arch assert.ok arch.length > 0 unless process.platform is "sunos" # not implemeneted yet assert.ok os.loadavg().length > 0 assert.ok os.freemem() > 0 assert.ok os.totalmem() > 0 interfaces = os.networkInterfaces() console.error interfaces switch platform when "linux" filter = (e) -> e.address is "127.0.0.1" actual = interfaces.lo.filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected when "win32" filter = (e) -> e.address is "127.0.0.1" actual = interfaces["Loopback Pseudo-Interface 1"].filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected EOL = os.EOL assert.ok EOL.length > 0
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") os = require("os") process.env.TMPDIR = "/tmpdir" process.env.TMP = "/tmp" process.env.TEMP = "/temp" if process.platform is "win32" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" expected = (process.env.SystemRoot or process.env.windir) + "\\temp" assert.equal os.tmpdir(), expected else assert.equal os.tmpdir(), "/tmpdir" process.env.TMPDIR = "" assert.equal os.tmpdir(), "/tmp" process.env.TMP = "" assert.equal os.tmpdir(), "/temp" process.env.TEMP = "" assert.equal os.tmpdir(), "/tmp" endianness = os.endianness() console.log "endianness = %s", endianness assert.ok /[BL]E/.test(endianness) hostname = os.hostname() console.log "hostname = %s", hostname assert.ok hostname.length > 0 uptime = os.uptime() console.log "uptime = %d", uptime assert.ok uptime > 0 cpus = os.cpus() console.log "cpus = ", cpus assert.ok cpus.length > 0 type = os.type() console.log "type = ", type assert.ok type.length > 0 release = os.release() console.log "release = ", release assert.ok release.length > 0 platform = os.platform() console.log "platform = ", platform assert.ok platform.length > 0 arch = os.arch() console.log "arch = ", arch assert.ok arch.length > 0 unless process.platform is "sunos" # not implemeneted yet assert.ok os.loadavg().length > 0 assert.ok os.freemem() > 0 assert.ok os.totalmem() > 0 interfaces = os.networkInterfaces() console.error interfaces switch platform when "linux" filter = (e) -> e.address is "127.0.0.1" actual = interfaces.lo.filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected when "win32" filter = (e) -> e.address is "127.0.0.1" actual = interfaces["Loopback Pseudo-Interface 1"].filter(filter) expected = [ address: "127.0.0.1" netmask: "255.0.0.0" mac: "00:00:00:00:00:00" family: "IPv4" internal: true ] assert.deepEqual actual, expected EOL = os.EOL assert.ok EOL.length > 0
[ { "context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle Wid", "end": 28, "score": 0.9998713135719299, "start": 14, "tag": "NAME", "value": "Takahiro INOUE" }, { "context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle...
extras/src/sw-extra-visualizer.coffee
ongacrest/songle-widget-api-examples
16
### @author Takahiro INOUE <takahiro.inoue@aist.go.jp> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "songle-ml@aist.go.jp". ### __swExtra__.initializeAllModule onReady: (songleWidget) -> if !window.createjs progress = 0 # Require thread party library. Please see "https://code.createjs.com/easeljs". easelElement = document.createElement("script") easelElement.async = false easelElement.defer = false easelElement.src = "https://code.createjs.com/easeljs-0.8.1.min.js" easelElement.type = "text/javascript" easelElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(easelElement) # Require thread party library. Please see "https://code.createjs.com/tweenjs". tweenElement = document.createElement("script") tweenElement.async = false tweenElement.defer = false tweenElement.src = "https://code.createjs.com/tweenjs-0.6.1.min.js" tweenElement.type = "text/javascript" tweenElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(tweenElement) else readySongleWidget(songleWidget) ### @function @private ### readySongleWidget = (songleWidget) -> rootElement = document.querySelector("[class*=sw-extra-visualizer") setTimeout -> # ---- Intiailize EaselJs and TweenJs. stageElement = document.createElement("canvas") stageElement.className = "sw-extra-visualizer" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() stageElement.style.position = "absolute" stageElement.style.left = 0 + "px" stageElement.style.top = 0 + "px" stageElement.style.zIndex = -1 if !rootElement then document.body.appendChild(stageElement) else rootElement.appendChild(stageElement) addEventListener "scroll", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false addEventListener "resize", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false stage = new createjs.Stage(stageElement) createjs.Ticker.addEventListener "tick", (e) -> stage.update(e) createjs.Ticker.setFPS(60) # ---- # ---- If you comment out, you can disable visualizer for beat. songleWidget.on "beatPlay", (e) -> if e.beat.position == 1 switch __swExtra__.random(MIN_TRAP_ID, MAX_TRAP_ID) when 1 invokeTriangleTrap(stage) when 2 invokeSquareTrap(stage) when 3 invoke5StarTrap(stage) when 4 invoke7StarTrap(stage) when 5 invokeCircleTrap(stage) # ---- # ---- If you comment out, you can disable visualizer for chord. songleWidget.on "chordPlay", (e) -> prevChord = e.chord.prev nextChord = e.chord if prevChord matchedChordName = prevChord.name.match(/^([A-G#]{1,2})/) || [] prevChordName = matchedChordName[ 1 ] || "N" else prevChordName = "N" prevChordColor = SONGLE_CHORD_COLOR_LIST[ prevChordName ] if nextChord matchedChordName = nextChord.name.match(/^([A-G#]{1,2})/) || [] nextChordName = matchedChordName[ 1 ] || "N" else nextChordName = "N" nextChordColor = SONGLE_CHORD_COLOR_LIST[ nextChordName ] createjs.Tween.get(prevChordColor) .to(nextChordColor, 250) .addEventListener "change", (e) -> backgroundColor = e.target.target backgroundColor.r = Math.floor(backgroundColor.r) backgroundColor.g = Math.floor(backgroundColor.g) backgroundColor.b = Math.floor(backgroundColor.b) stageElement.style.backgroundColor = "rgb(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + ")" # ---- # ---- If you comment out, you can disable visualizer for chorus. songleWidget.on "chorusSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_CHORUS_SEGMENT_COLOR direction: "L" # ---- # ---- If you comment out, you can disable visualizer for repeat. songleWidget.on "repeatSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_REPEAT_SEGMENT_COLOR direction: "R" # ---- songleWidget.on "play", -> resetState(stage) songleWidget.on "seek", -> resetState(stage) songleWidget.on "finish", -> resetState(stage) , 0 # [ms] ### @constant @private ### MIN_TRAP_ID = 1 ### @constant @private ### MAX_TRAP_ID = 5 ### @constant @private ### SONGLE_THEME_COLOR = "#e17" ### @constant @private ### SONGLE_CHORD_COLOR_LIST = "A": r: 0xcc g: 0xcc b: 0xee "A#": r: 0xcc g: 0xcc b: 0xff "B": r: 0xcc g: 0xee b: 0xcc "C": r: 0xcc g: 0xee b: 0xee "C#": r: 0xcc g: 0xff b: 0xff "D": r: 0xee g: 0xcc b: 0xcc "D#": r: 0xff g: 0xcc b: 0xcc "E": r: 0xee g: 0xcc b: 0xee "F": r: 0xee g: 0xee b: 0xcc "F#": r: 0xff g: 0xff b: 0xcc "G": r: 0xee g: 0xee b: 0xee "G#": r: 0xff g: 0xff b: 0xff "N": r: 0xff g: 0xff b: 0xff ### @constant @private ### SONGLE_CHORUS_SEGMENT_COLOR = "#f84" ### @constant @private ### SONGLE_REPEAT_SEGMENT_COLOR = "#48f" ### @function @private ### getScreenSizeW = -> return if rootElement then rootElement.clientWidth else window.innerWidth ### @function @private ### getScreenSizeH = -> return if rootElement then rootElement.clientHeight else window.innerHeight ### @function @private ### invokeGeometryTrap = (stage, options = {}) -> options.r ?= 0 options.vertexCount ?= 0 geometry = new createjs.Shape geometry.graphics.beginStroke(SONGLE_THEME_COLOR).drawPolyStar(0, 0, 20, options.vertexCount, options.r, __swExtra__.random(0, 360)) geometry.x = __swExtra__.random(0, getScreenSizeW()) geometry.y = __swExtra__.random(0, getScreenSizeH()) createjs.Tween.get(geometry) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(geometry) ### @function @private ### invokeTriangleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 3 ### @function @private ### invokeSquareTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 4 ### @function @private ### invoke5StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 5 ### @function @private ### invoke7StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 7 ### @function @private ### invokeCircleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 100 ### @function @private ### invokeWaveTrap = (stage, options = {}) -> options.color ?= SONGLE_THEME_COLOR options.direction ?= "L" for index in [0...10] ((index) -> circle = new createjs.Shape circle.graphics.beginStroke(options.color).drawCircle(0, 0, 20) switch options.direction when "L" circle.x = getScreenSizeW() / 10 * index circle.y = getScreenSizeH() / 2 when "R" circle.x = getScreenSizeW() / 10 * (10 - index) circle.y = getScreenSizeH() / 2 setTimeout -> createjs.Tween.get(circle) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(circle) , 200 * index # [ms] )(index) ### @function @private ### resetState = (stage) -> stage.removeAllChildren()
30979
### @author <NAME> <<EMAIL>> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "<EMAIL>". ### __swExtra__.initializeAllModule onReady: (songleWidget) -> if !window.createjs progress = 0 # Require thread party library. Please see "https://code.createjs.com/easeljs". easelElement = document.createElement("script") easelElement.async = false easelElement.defer = false easelElement.src = "https://code.createjs.com/easeljs-0.8.1.min.js" easelElement.type = "text/javascript" easelElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(easelElement) # Require thread party library. Please see "https://code.createjs.com/tweenjs". tweenElement = document.createElement("script") tweenElement.async = false tweenElement.defer = false tweenElement.src = "https://code.createjs.com/tweenjs-0.6.1.min.js" tweenElement.type = "text/javascript" tweenElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(tweenElement) else readySongleWidget(songleWidget) ### @function @private ### readySongleWidget = (songleWidget) -> rootElement = document.querySelector("[class*=sw-extra-visualizer") setTimeout -> # ---- Intiailize EaselJs and TweenJs. stageElement = document.createElement("canvas") stageElement.className = "sw-extra-visualizer" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() stageElement.style.position = "absolute" stageElement.style.left = 0 + "px" stageElement.style.top = 0 + "px" stageElement.style.zIndex = -1 if !rootElement then document.body.appendChild(stageElement) else rootElement.appendChild(stageElement) addEventListener "scroll", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false addEventListener "resize", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false stage = new createjs.Stage(stageElement) createjs.Ticker.addEventListener "tick", (e) -> stage.update(e) createjs.Ticker.setFPS(60) # ---- # ---- If you comment out, you can disable visualizer for beat. songleWidget.on "beatPlay", (e) -> if e.beat.position == 1 switch __swExtra__.random(MIN_TRAP_ID, MAX_TRAP_ID) when 1 invokeTriangleTrap(stage) when 2 invokeSquareTrap(stage) when 3 invoke5StarTrap(stage) when 4 invoke7StarTrap(stage) when 5 invokeCircleTrap(stage) # ---- # ---- If you comment out, you can disable visualizer for chord. songleWidget.on "chordPlay", (e) -> prevChord = e.chord.prev nextChord = e.chord if prevChord matchedChordName = prevChord.name.match(/^([A-G#]{1,2})/) || [] prevChordName = matchedChordName[ 1 ] || "N" else prevChordName = "N" prevChordColor = SONGLE_CHORD_COLOR_LIST[ prevChordName ] if nextChord matchedChordName = nextChord.name.match(/^([A-G#]{1,2})/) || [] nextChordName = matchedChordName[ 1 ] || "N" else nextChordName = "N" nextChordColor = SONGLE_CHORD_COLOR_LIST[ nextChordName ] createjs.Tween.get(prevChordColor) .to(nextChordColor, 250) .addEventListener "change", (e) -> backgroundColor = e.target.target backgroundColor.r = Math.floor(backgroundColor.r) backgroundColor.g = Math.floor(backgroundColor.g) backgroundColor.b = Math.floor(backgroundColor.b) stageElement.style.backgroundColor = "rgb(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + ")" # ---- # ---- If you comment out, you can disable visualizer for chorus. songleWidget.on "chorusSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_CHORUS_SEGMENT_COLOR direction: "L" # ---- # ---- If you comment out, you can disable visualizer for repeat. songleWidget.on "repeatSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_REPEAT_SEGMENT_COLOR direction: "R" # ---- songleWidget.on "play", -> resetState(stage) songleWidget.on "seek", -> resetState(stage) songleWidget.on "finish", -> resetState(stage) , 0 # [ms] ### @constant @private ### MIN_TRAP_ID = 1 ### @constant @private ### MAX_TRAP_ID = 5 ### @constant @private ### SONGLE_THEME_COLOR = "#e17" ### @constant @private ### SONGLE_CHORD_COLOR_LIST = "A": r: 0xcc g: 0xcc b: 0xee "A#": r: 0xcc g: 0xcc b: 0xff "B": r: 0xcc g: 0xee b: 0xcc "C": r: 0xcc g: 0xee b: 0xee "C#": r: 0xcc g: 0xff b: 0xff "D": r: 0xee g: 0xcc b: 0xcc "D#": r: 0xff g: 0xcc b: 0xcc "E": r: 0xee g: 0xcc b: 0xee "F": r: 0xee g: 0xee b: 0xcc "F#": r: 0xff g: 0xff b: 0xcc "G": r: 0xee g: 0xee b: 0xee "G#": r: 0xff g: 0xff b: 0xff "N": r: 0xff g: 0xff b: 0xff ### @constant @private ### SONGLE_CHORUS_SEGMENT_COLOR = "#f84" ### @constant @private ### SONGLE_REPEAT_SEGMENT_COLOR = "#48f" ### @function @private ### getScreenSizeW = -> return if rootElement then rootElement.clientWidth else window.innerWidth ### @function @private ### getScreenSizeH = -> return if rootElement then rootElement.clientHeight else window.innerHeight ### @function @private ### invokeGeometryTrap = (stage, options = {}) -> options.r ?= 0 options.vertexCount ?= 0 geometry = new createjs.Shape geometry.graphics.beginStroke(SONGLE_THEME_COLOR).drawPolyStar(0, 0, 20, options.vertexCount, options.r, __swExtra__.random(0, 360)) geometry.x = __swExtra__.random(0, getScreenSizeW()) geometry.y = __swExtra__.random(0, getScreenSizeH()) createjs.Tween.get(geometry) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(geometry) ### @function @private ### invokeTriangleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 3 ### @function @private ### invokeSquareTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 4 ### @function @private ### invoke5StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 5 ### @function @private ### invoke7StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 7 ### @function @private ### invokeCircleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 100 ### @function @private ### invokeWaveTrap = (stage, options = {}) -> options.color ?= SONGLE_THEME_COLOR options.direction ?= "L" for index in [0...10] ((index) -> circle = new createjs.Shape circle.graphics.beginStroke(options.color).drawCircle(0, 0, 20) switch options.direction when "L" circle.x = getScreenSizeW() / 10 * index circle.y = getScreenSizeH() / 2 when "R" circle.x = getScreenSizeW() / 10 * (10 - index) circle.y = getScreenSizeH() / 2 setTimeout -> createjs.Tween.get(circle) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(circle) , 200 * index # [ms] )(index) ### @function @private ### resetState = (stage) -> stage.removeAllChildren()
true
### @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "PI:EMAIL:<EMAIL>END_PI". ### __swExtra__.initializeAllModule onReady: (songleWidget) -> if !window.createjs progress = 0 # Require thread party library. Please see "https://code.createjs.com/easeljs". easelElement = document.createElement("script") easelElement.async = false easelElement.defer = false easelElement.src = "https://code.createjs.com/easeljs-0.8.1.min.js" easelElement.type = "text/javascript" easelElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(easelElement) # Require thread party library. Please see "https://code.createjs.com/tweenjs". tweenElement = document.createElement("script") tweenElement.async = false tweenElement.defer = false tweenElement.src = "https://code.createjs.com/tweenjs-0.6.1.min.js" tweenElement.type = "text/javascript" tweenElement.addEventListener "load", -> ++ progress if progress >= 2 readySongleWidget(songleWidget) , false document.body.appendChild(tweenElement) else readySongleWidget(songleWidget) ### @function @private ### readySongleWidget = (songleWidget) -> rootElement = document.querySelector("[class*=sw-extra-visualizer") setTimeout -> # ---- Intiailize EaselJs and TweenJs. stageElement = document.createElement("canvas") stageElement.className = "sw-extra-visualizer" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() stageElement.style.position = "absolute" stageElement.style.left = 0 + "px" stageElement.style.top = 0 + "px" stageElement.style.zIndex = -1 if !rootElement then document.body.appendChild(stageElement) else rootElement.appendChild(stageElement) addEventListener "scroll", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false addEventListener "resize", -> if !rootElement stageElement.style.top = window.scrollY + "px" stageElement.width = getScreenSizeW() stageElement.height = getScreenSizeH() , false stage = new createjs.Stage(stageElement) createjs.Ticker.addEventListener "tick", (e) -> stage.update(e) createjs.Ticker.setFPS(60) # ---- # ---- If you comment out, you can disable visualizer for beat. songleWidget.on "beatPlay", (e) -> if e.beat.position == 1 switch __swExtra__.random(MIN_TRAP_ID, MAX_TRAP_ID) when 1 invokeTriangleTrap(stage) when 2 invokeSquareTrap(stage) when 3 invoke5StarTrap(stage) when 4 invoke7StarTrap(stage) when 5 invokeCircleTrap(stage) # ---- # ---- If you comment out, you can disable visualizer for chord. songleWidget.on "chordPlay", (e) -> prevChord = e.chord.prev nextChord = e.chord if prevChord matchedChordName = prevChord.name.match(/^([A-G#]{1,2})/) || [] prevChordName = matchedChordName[ 1 ] || "N" else prevChordName = "N" prevChordColor = SONGLE_CHORD_COLOR_LIST[ prevChordName ] if nextChord matchedChordName = nextChord.name.match(/^([A-G#]{1,2})/) || [] nextChordName = matchedChordName[ 1 ] || "N" else nextChordName = "N" nextChordColor = SONGLE_CHORD_COLOR_LIST[ nextChordName ] createjs.Tween.get(prevChordColor) .to(nextChordColor, 250) .addEventListener "change", (e) -> backgroundColor = e.target.target backgroundColor.r = Math.floor(backgroundColor.r) backgroundColor.g = Math.floor(backgroundColor.g) backgroundColor.b = Math.floor(backgroundColor.b) stageElement.style.backgroundColor = "rgb(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + ")" # ---- # ---- If you comment out, you can disable visualizer for chorus. songleWidget.on "chorusSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_CHORUS_SEGMENT_COLOR direction: "L" # ---- # ---- If you comment out, you can disable visualizer for repeat. songleWidget.on "repeatSegmentEnter", (e) -> invokeWaveTrap stage, color: SONGLE_REPEAT_SEGMENT_COLOR direction: "R" # ---- songleWidget.on "play", -> resetState(stage) songleWidget.on "seek", -> resetState(stage) songleWidget.on "finish", -> resetState(stage) , 0 # [ms] ### @constant @private ### MIN_TRAP_ID = 1 ### @constant @private ### MAX_TRAP_ID = 5 ### @constant @private ### SONGLE_THEME_COLOR = "#e17" ### @constant @private ### SONGLE_CHORD_COLOR_LIST = "A": r: 0xcc g: 0xcc b: 0xee "A#": r: 0xcc g: 0xcc b: 0xff "B": r: 0xcc g: 0xee b: 0xcc "C": r: 0xcc g: 0xee b: 0xee "C#": r: 0xcc g: 0xff b: 0xff "D": r: 0xee g: 0xcc b: 0xcc "D#": r: 0xff g: 0xcc b: 0xcc "E": r: 0xee g: 0xcc b: 0xee "F": r: 0xee g: 0xee b: 0xcc "F#": r: 0xff g: 0xff b: 0xcc "G": r: 0xee g: 0xee b: 0xee "G#": r: 0xff g: 0xff b: 0xff "N": r: 0xff g: 0xff b: 0xff ### @constant @private ### SONGLE_CHORUS_SEGMENT_COLOR = "#f84" ### @constant @private ### SONGLE_REPEAT_SEGMENT_COLOR = "#48f" ### @function @private ### getScreenSizeW = -> return if rootElement then rootElement.clientWidth else window.innerWidth ### @function @private ### getScreenSizeH = -> return if rootElement then rootElement.clientHeight else window.innerHeight ### @function @private ### invokeGeometryTrap = (stage, options = {}) -> options.r ?= 0 options.vertexCount ?= 0 geometry = new createjs.Shape geometry.graphics.beginStroke(SONGLE_THEME_COLOR).drawPolyStar(0, 0, 20, options.vertexCount, options.r, __swExtra__.random(0, 360)) geometry.x = __swExtra__.random(0, getScreenSizeW()) geometry.y = __swExtra__.random(0, getScreenSizeH()) createjs.Tween.get(geometry) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(geometry) ### @function @private ### invokeTriangleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 3 ### @function @private ### invokeSquareTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 4 ### @function @private ### invoke5StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 5 ### @function @private ### invoke7StarTrap = (stage) -> invokeGeometryTrap stage, r: 0.20 vertexCount: 7 ### @function @private ### invokeCircleTrap = (stage) -> invokeGeometryTrap stage, vertexCount: 100 ### @function @private ### invokeWaveTrap = (stage, options = {}) -> options.color ?= SONGLE_THEME_COLOR options.direction ?= "L" for index in [0...10] ((index) -> circle = new createjs.Shape circle.graphics.beginStroke(options.color).drawCircle(0, 0, 20) switch options.direction when "L" circle.x = getScreenSizeW() / 10 * index circle.y = getScreenSizeH() / 2 when "R" circle.x = getScreenSizeW() / 10 * (10 - index) circle.y = getScreenSizeH() / 2 setTimeout -> createjs.Tween.get(circle) .to alpha: 0 scaleX: 20 scaleY: 20 , 2000 stage.addChild(circle) , 200 * index # [ms] )(index) ### @function @private ### resetState = (stage) -> stage.removeAllChildren()
[ { "context": "# @author supereggbert / http://www.paulbrunt.co.uk/\n# @author ", "end": 13, "score": 0.9936078786849976, "start": 10, "tag": "USERNAME", "value": "sup" }, { "context": "# @author supereggbert / http://www.paulbrunt.co.uk/\n# @author philogb /", "end": 22, "sco...
source/javascripts/new_src/core/vector_4.coffee
andrew-aladev/three.js
0
# @author supereggbert / http://www.paulbrunt.co.uk/ # @author philogb / http://blog.thejit.org/ # @author mikael emtinger / http://gomo.se/ # @author egraether / http://egraether.com/ # @author aladjev.andrew@gmail.com class Vector4 constructor: (x, y, z, w) -> @x = x or 0 @y = y or 0 @z = z or 0 @w = (if (w isnt undefined) then w else 1) set: (x, y, z, w) -> @x = x @y = y @z = z @w = w this copy: (v) -> @x = v.x @y = v.y @z = v.z @w = (if (v.w isnt undefined) then v.w else 1) this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z @w = a.w + b.w this addSelf: (v) -> @x += v.x @y += v.y @z += v.z @w += v.w this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z @w = a.w - b.w this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z @w -= v.w this multiplyScalar: (s) -> @x *= s @y *= s @z *= s @w *= s this divideScalar: (s) -> if s @x /= s @y /= s @z /= s @w /= s else @x = 0 @y = 0 @z = 0 @w = 1 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z + @w * v.w lengthSq: -> @dot this length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha @w += (v.w - @w) * alpha this clone: -> new Vector4 @x, @y, @z, @w namespace "THREE", (exports) -> exports.Vector4 = Vector4
137384
# @author sup<NAME> / http://www.paulbrunt.co.uk/ # @author philogb / http://blog.thejit.org/ # @author <NAME> / http://gomo.se/ # @author egraether / http://egraether.com/ # @author <EMAIL> class Vector4 constructor: (x, y, z, w) -> @x = x or 0 @y = y or 0 @z = z or 0 @w = (if (w isnt undefined) then w else 1) set: (x, y, z, w) -> @x = x @y = y @z = z @w = w this copy: (v) -> @x = v.x @y = v.y @z = v.z @w = (if (v.w isnt undefined) then v.w else 1) this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z @w = a.w + b.w this addSelf: (v) -> @x += v.x @y += v.y @z += v.z @w += v.w this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z @w = a.w - b.w this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z @w -= v.w this multiplyScalar: (s) -> @x *= s @y *= s @z *= s @w *= s this divideScalar: (s) -> if s @x /= s @y /= s @z /= s @w /= s else @x = 0 @y = 0 @z = 0 @w = 1 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z + @w * v.w lengthSq: -> @dot this length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha @w += (v.w - @w) * alpha this clone: -> new Vector4 @x, @y, @z, @w namespace "THREE", (exports) -> exports.Vector4 = Vector4
true
# @author supPI:NAME:<NAME>END_PI / http://www.paulbrunt.co.uk/ # @author philogb / http://blog.thejit.org/ # @author PI:NAME:<NAME>END_PI / http://gomo.se/ # @author egraether / http://egraether.com/ # @author PI:EMAIL:<EMAIL>END_PI class Vector4 constructor: (x, y, z, w) -> @x = x or 0 @y = y or 0 @z = z or 0 @w = (if (w isnt undefined) then w else 1) set: (x, y, z, w) -> @x = x @y = y @z = z @w = w this copy: (v) -> @x = v.x @y = v.y @z = v.z @w = (if (v.w isnt undefined) then v.w else 1) this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y @z = a.z + b.z @w = a.w + b.w this addSelf: (v) -> @x += v.x @y += v.y @z += v.z @w += v.w this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y @z = a.z - b.z @w = a.w - b.w this subSelf: (v) -> @x -= v.x @y -= v.y @z -= v.z @w -= v.w this multiplyScalar: (s) -> @x *= s @y *= s @z *= s @w *= s this divideScalar: (s) -> if s @x /= s @y /= s @z /= s @w /= s else @x = 0 @y = 0 @z = 0 @w = 1 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y + @z * v.z + @w * v.w lengthSq: -> @dot this length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha @z += (v.z - @z) * alpha @w += (v.w - @w) * alpha this clone: -> new Vector4 @x, @y, @z, @w namespace "THREE", (exports) -> exports.Vector4 = Vector4
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998907446861267, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/index.coffee
AbdelhakimRafik/Project
1
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date June 2021 ### express = require 'express' app = do express cors = require 'cors' config = require './config' db = require('./database')(config.db) routes = require('./routes')(app) # use bodyParser for requests params app.use express.urlencoded extended:true # use bodyParser for JSON app.use do express.json # enable cors polycies app.use do cors # start server app.listen config.server.port, -> console.log "Server started on #{config.server.host}:#{config.server.port}" return
60294
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date June 2021 ### express = require 'express' app = do express cors = require 'cors' config = require './config' db = require('./database')(config.db) routes = require('./routes')(app) # use bodyParser for requests params app.use express.urlencoded extended:true # use bodyParser for JSON app.use do express.json # enable cors polycies app.use do cors # start server app.listen config.server.port, -> console.log "Server started on #{config.server.host}:#{config.server.port}" return
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date June 2021 ### express = require 'express' app = do express cors = require 'cors' config = require './config' db = require('./database')(config.db) routes = require('./routes')(app) # use bodyParser for requests params app.use express.urlencoded extended:true # use bodyParser for JSON app.use do express.json # enable cors polycies app.use do cors # start server app.listen config.server.port, -> console.log "Server started on #{config.server.host}:#{config.server.port}" return
[ { "context": "is earned by killing unique players.\n *\n * @name PKer\n * @prerequisite Kill 10*[10*[n-1]+1] unique pla", "end": 185, "score": 0.7147166132926941, "start": 181, "tag": "USERNAME", "value": "PKer" }, { "context": "kValue / killInterval\n item =\n name: \...
src/character/achievements/PKer.coffee
jawsome/IdleLands
3
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" _ = require "lodash" `/** * This achievement is earned by killing unique players. * * @name PKer * @prerequisite Kill 10*[10*[n-1]+1] unique players. * @reward +5 STR * @reward +5 AGI * @reward +5 CON * @reward +5 DEX * @reward +5 INT * @reward +5 WIS * @reward +1 LUCK * @category Achievements * @package Player */` class PKer extends Achievement getAllAchievedFor: (player) -> baseStat = (_.keys player.statistics['calculated kills']).length currentCheckValue = 10 killInterval = 10 achieved = [] while baseStat >= currentCheckValue level = currentCheckValue / killInterval item = name: "PKer #{toRoman level}" desc: "Kill #{currentCheckValue} unique players" reward: "+5 STR/DEX/AGI/CON/WIS/INT, +1 LUCK" agi: -> 5 dex: -> 5 wis: -> 5 con: -> 5 int: -> 5 str: -> 5 luck: -> 1 type: "combat" item.title = "PKer" if level is 10 achieved.push item currentCheckValue += killInterval achieved module.exports = exports = PKer
125321
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" _ = require "lodash" `/** * This achievement is earned by killing unique players. * * @name PKer * @prerequisite Kill 10*[10*[n-1]+1] unique players. * @reward +5 STR * @reward +5 AGI * @reward +5 CON * @reward +5 DEX * @reward +5 INT * @reward +5 WIS * @reward +1 LUCK * @category Achievements * @package Player */` class PKer extends Achievement getAllAchievedFor: (player) -> baseStat = (_.keys player.statistics['calculated kills']).length currentCheckValue = 10 killInterval = 10 achieved = [] while baseStat >= currentCheckValue level = currentCheckValue / killInterval item = name: "<NAME> #{toRoman level}" desc: "Kill #{currentCheckValue} unique players" reward: "+5 STR/DEX/AGI/CON/WIS/INT, +1 LUCK" agi: -> 5 dex: -> 5 wis: -> 5 con: -> 5 int: -> 5 str: -> 5 luck: -> 1 type: "combat" item.title = "PKer" if level is 10 achieved.push item currentCheckValue += killInterval achieved module.exports = exports = PKer
true
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" _ = require "lodash" `/** * This achievement is earned by killing unique players. * * @name PKer * @prerequisite Kill 10*[10*[n-1]+1] unique players. * @reward +5 STR * @reward +5 AGI * @reward +5 CON * @reward +5 DEX * @reward +5 INT * @reward +5 WIS * @reward +1 LUCK * @category Achievements * @package Player */` class PKer extends Achievement getAllAchievedFor: (player) -> baseStat = (_.keys player.statistics['calculated kills']).length currentCheckValue = 10 killInterval = 10 achieved = [] while baseStat >= currentCheckValue level = currentCheckValue / killInterval item = name: "PI:NAME:<NAME>END_PI #{toRoman level}" desc: "Kill #{currentCheckValue} unique players" reward: "+5 STR/DEX/AGI/CON/WIS/INT, +1 LUCK" agi: -> 5 dex: -> 5 wis: -> 5 con: -> 5 int: -> 5 str: -> 5 luck: -> 1 type: "combat" item.title = "PKer" if level is 10 achieved.push item currentCheckValue += killInterval achieved module.exports = exports = PKer
[ { "context": "-grunt-travis-github-pages/\n\t# https://github.com/sindresorhus/grunt-shell\n\t# Needs “pipenv run”, that scripts f", "end": 336, "score": 0.9996150732040405, "start": 324, "tag": "USERNAME", "value": "sindresorhus" }, { "context": " --update”, users have bug:\n\t# htt...
grunt/shell.coffee
Kristinita/SashaPelicanTest
0
################# ## grunt-shell ## ################# # Grunt plugin to run non-Grunt CLI commands. # https://www.npmjs.com/package/grunt-shell module.exports = ############# ## Pelican ## ############# # Build Pelican site: # http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ # https://github.com/sindresorhus/grunt-shell # Needs “pipenv run”, that scripts from pipenv virtual environment successful run; # for example, “pipenv run pelican --help”, not “pelican --help”. # https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv # “--fatal” — exit(1), if any warning or error generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings --verbose' # [DEPRECATED] If “pipenv --update”, users have bug: # https://github.com/pypa/pipenv/issues/1761 # ############ # ## pipenv ## # ############ # # Update Pip and Pipenv # pipenvupdate: # command: 'pipenv --update' # Update all Python Pipenv packages: # https://stackoverflow.com/a/16269635/5951529 # https://github.com/jgonggrijp/pip-review#pip-review pipenvupdateall: command: 'pipenv run pip-review --auto' # Clean unused packages # [WARNING] That “pipenv clean” doesn't remove Python Markdown extensions, you need install them in format: # pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev # https://github.com/pypa/pipenv/issues/1524 # This is “editable” format: # http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e pipenvcleanunused: command: 'pipenv clean --verbose' # Update packages versions to the newest in “Pipfile.lock”, that: # 1. Another users have newest packages versions in their environment: # 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 # https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### # Shrink .git folder # https://stackoverflow.com/a/2116892/5951529 # Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> # After: 341 MB — <https://i.imgur.com/52cQ1AL.png> ######### # Remove reflog entries older, than 90 days: # https://stackoverflow.com/a/3824970/5951529 gitreflog: command: 'git reflog expire --all' # git gc # https://stackoverflow.com/a/55738/5951529 # Prune loose objects older than 2 weeks ago: # https://www.kernel.org/pub/software/scm/git/docgit-gc.html gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### # HTML Tidy scripts for Unix and Linux tidymodify: # Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else # Fix permission denied: # https://stackoverflow.com/a/46818913/5951529 command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ # Generate Code of conduct for project: # https://contributor-covenant.org/ # https://www.npmjs.com/package/covgen # [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: # https://github.com/simonv3/covenant-generator/issues/15 # [WARNING] Unobfuscated plain text e-mail: # https://github.com/ContributorCovenant/contributor_covenant/issues/523 ######### ## npx ## ######### # Tool for running npm CLI commands: # https://www.npmjs.com/package/npx # https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b # https://stackoverflow.com/a/45164863/5951529 covgen: command: 'npx covgen SashaChernykhEmpressOfUniverse$kristinita.ru' ################## ## pip-licenses ## ################## # Output licenses of all PyPI packages: # https://pypi.org/project/pip-licenses/ piplicenses: command: 'pipenv run pip-licenses --format-markdown > python.md' ########################## ## commitlint Travis CI ## ########################## # Commit linting for Travis CI: # http://marionebl.github.io/commitlint/#/guides-ci-setup commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### # Lint “.travis.yml” file locally: # https://stackoverflow.com/a/35607499/5951529 # https://rubygems.org/gems/travis # “-x” argument — exit code 1, if any warning: travislint: command: 'travis lint -x' ########## # EClint # ########## # Lint and fix files for EditorConfig rules: # https://www.npmjs.com/package/eclint # eclint doesn't search files and folders, that ignored in “.gitignore”: # https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 # “eclint infer” — show current statistic: # https://www.npmjs.com/package/eclint#infer # [WARNING] Another eclint check and fix methods doesn't work: # https://github.com/jedmao/eclint/issues/130 # [WARNING] User can get different results for Windows and *NIX: # https://github.com/jedmao/eclint/issues/129#event-1574600632 # [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: # https://github.com/ContributorCovenant/contributor_covenant/issues/528 eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.paths.output_path %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.paths.output_path %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### # Generate license: # https://www.npmjs.com/package/license-generator licensegenerator: command: "npx license-generator install mit -n \"Sasha Chernykh\"" ############## # ShellCheck # ############## # Check “.sh” files: # https://www.shellcheck.net/ shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh'
702
################# ## grunt-shell ## ################# # Grunt plugin to run non-Grunt CLI commands. # https://www.npmjs.com/package/grunt-shell module.exports = ############# ## Pelican ## ############# # Build Pelican site: # http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ # https://github.com/sindresorhus/grunt-shell # Needs “pipenv run”, that scripts from pipenv virtual environment successful run; # for example, “pipenv run pelican --help”, not “pelican --help”. # https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv # “--fatal” — exit(1), if any warning or error generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings --verbose' # [DEPRECATED] If “pipenv --update”, users have bug: # https://github.com/pypa/pipenv/issues/1761 # ############ # ## pipenv ## # ############ # # Update Pip and Pipenv # pipenvupdate: # command: 'pipenv --update' # Update all Python Pipenv packages: # https://stackoverflow.com/a/16269635/5951529 # https://github.com/jgonggrijp/pip-review#pip-review pipenvupdateall: command: 'pipenv run pip-review --auto' # Clean unused packages # [WARNING] That “pipenv clean” doesn't remove Python Markdown extensions, you need install them in format: # pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev # https://github.com/pypa/pipenv/issues/1524 # This is “editable” format: # http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e pipenvcleanunused: command: 'pipenv clean --verbose' # Update packages versions to the newest in “Pipfile.lock”, that: # 1. Another users have newest packages versions in their environment: # 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 # https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### # Shrink .git folder # https://stackoverflow.com/a/2116892/5951529 # Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> # After: 341 MB — <https://i.imgur.com/52cQ1AL.png> ######### # Remove reflog entries older, than 90 days: # https://stackoverflow.com/a/3824970/5951529 gitreflog: command: 'git reflog expire --all' # git gc # https://stackoverflow.com/a/55738/5951529 # Prune loose objects older than 2 weeks ago: # https://www.kernel.org/pub/software/scm/git/docgit-gc.html gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### # HTML Tidy scripts for Unix and Linux tidymodify: # Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else # Fix permission denied: # https://stackoverflow.com/a/46818913/5951529 command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ # Generate Code of conduct for project: # https://contributor-covenant.org/ # https://www.npmjs.com/package/covgen # [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: # https://github.com/simonv3/covenant-generator/issues/15 # [WARNING] Unobfuscated plain text e-mail: # https://github.com/ContributorCovenant/contributor_covenant/issues/523 ######### ## npx ## ######### # Tool for running npm CLI commands: # https://www.npmjs.com/package/npx # https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b # https://stackoverflow.com/a/45164863/5951529 covgen: command: 'npx covgen SashaChernykhEmpressOfUniverse$kristinita.ru' ################## ## pip-licenses ## ################## # Output licenses of all PyPI packages: # https://pypi.org/project/pip-licenses/ piplicenses: command: 'pipenv run pip-licenses --format-markdown > python.md' ########################## ## commitlint Travis CI ## ########################## # Commit linting for Travis CI: # http://marionebl.github.io/commitlint/#/guides-ci-setup commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### # Lint “.travis.yml” file locally: # https://stackoverflow.com/a/35607499/5951529 # https://rubygems.org/gems/travis # “-x” argument — exit code 1, if any warning: travislint: command: 'travis lint -x' ########## # EClint # ########## # Lint and fix files for EditorConfig rules: # https://www.npmjs.com/package/eclint # eclint doesn't search files and folders, that ignored in “.gitignore”: # https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 # “eclint infer” — show current statistic: # https://www.npmjs.com/package/eclint#infer # [WARNING] Another eclint check and fix methods doesn't work: # https://github.com/jedmao/eclint/issues/130 # [WARNING] User can get different results for Windows and *NIX: # https://github.com/jedmao/eclint/issues/129#event-1574600632 # [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: # https://github.com/ContributorCovenant/contributor_covenant/issues/528 eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.paths.output_path %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.paths.output_path %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### # Generate license: # https://www.npmjs.com/package/license-generator licensegenerator: command: "npx license-generator install mit -n \"<NAME>\"" ############## # ShellCheck # ############## # Check “.sh” files: # https://www.shellcheck.net/ shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh'
true
################# ## grunt-shell ## ################# # Grunt plugin to run non-Grunt CLI commands. # https://www.npmjs.com/package/grunt-shell module.exports = ############# ## Pelican ## ############# # Build Pelican site: # http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ # https://github.com/sindresorhus/grunt-shell # Needs “pipenv run”, that scripts from pipenv virtual environment successful run; # for example, “pipenv run pelican --help”, not “pelican --help”. # https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv # “--fatal” — exit(1), if any warning or error generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings --verbose' # [DEPRECATED] If “pipenv --update”, users have bug: # https://github.com/pypa/pipenv/issues/1761 # ############ # ## pipenv ## # ############ # # Update Pip and Pipenv # pipenvupdate: # command: 'pipenv --update' # Update all Python Pipenv packages: # https://stackoverflow.com/a/16269635/5951529 # https://github.com/jgonggrijp/pip-review#pip-review pipenvupdateall: command: 'pipenv run pip-review --auto' # Clean unused packages # [WARNING] That “pipenv clean” doesn't remove Python Markdown extensions, you need install them in format: # pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev # https://github.com/pypa/pipenv/issues/1524 # This is “editable” format: # http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e pipenvcleanunused: command: 'pipenv clean --verbose' # Update packages versions to the newest in “Pipfile.lock”, that: # 1. Another users have newest packages versions in their environment: # 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 # https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### # Shrink .git folder # https://stackoverflow.com/a/2116892/5951529 # Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> # After: 341 MB — <https://i.imgur.com/52cQ1AL.png> ######### # Remove reflog entries older, than 90 days: # https://stackoverflow.com/a/3824970/5951529 gitreflog: command: 'git reflog expire --all' # git gc # https://stackoverflow.com/a/55738/5951529 # Prune loose objects older than 2 weeks ago: # https://www.kernel.org/pub/software/scm/git/docgit-gc.html gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### # HTML Tidy scripts for Unix and Linux tidymodify: # Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else # Fix permission denied: # https://stackoverflow.com/a/46818913/5951529 command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ # Generate Code of conduct for project: # https://contributor-covenant.org/ # https://www.npmjs.com/package/covgen # [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: # https://github.com/simonv3/covenant-generator/issues/15 # [WARNING] Unobfuscated plain text e-mail: # https://github.com/ContributorCovenant/contributor_covenant/issues/523 ######### ## npx ## ######### # Tool for running npm CLI commands: # https://www.npmjs.com/package/npx # https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b # https://stackoverflow.com/a/45164863/5951529 covgen: command: 'npx covgen SashaChernykhEmpressOfUniverse$kristinita.ru' ################## ## pip-licenses ## ################## # Output licenses of all PyPI packages: # https://pypi.org/project/pip-licenses/ piplicenses: command: 'pipenv run pip-licenses --format-markdown > python.md' ########################## ## commitlint Travis CI ## ########################## # Commit linting for Travis CI: # http://marionebl.github.io/commitlint/#/guides-ci-setup commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### # Lint “.travis.yml” file locally: # https://stackoverflow.com/a/35607499/5951529 # https://rubygems.org/gems/travis # “-x” argument — exit code 1, if any warning: travislint: command: 'travis lint -x' ########## # EClint # ########## # Lint and fix files for EditorConfig rules: # https://www.npmjs.com/package/eclint # eclint doesn't search files and folders, that ignored in “.gitignore”: # https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 # “eclint infer” — show current statistic: # https://www.npmjs.com/package/eclint#infer # [WARNING] Another eclint check and fix methods doesn't work: # https://github.com/jedmao/eclint/issues/130 # [WARNING] User can get different results for Windows and *NIX: # https://github.com/jedmao/eclint/issues/129#event-1574600632 # [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: # https://github.com/ContributorCovenant/contributor_covenant/issues/528 eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.paths.output_path %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.paths.output_path %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### # Generate license: # https://www.npmjs.com/package/license-generator licensegenerator: command: "npx license-generator install mit -n \"PI:NAME:<NAME>END_PI\"" ############## # ShellCheck # ############## # Check “.sh” files: # https://www.shellcheck.net/ shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh'
[ { "context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.0 (", "end": 25, "score": 0.9931498765945435, "start": 19, "tag": "NAME", "value": "Balena" } ]
lib/models/config.coffee
josecoelho/balena-sdk
0
### Copyright 2016 Balena Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### once = require('lodash/once') union = require('lodash/union') map = require('lodash/map') getConfigModel = (deps, opts) -> { request } = deps { apiUrl } = opts deviceModel = once -> require('./device')(deps, opts) exports = {} normalizeDeviceTypes = (deviceTypes) -> # Patch device types to be marked as ALPHA and BETA instead # of PREVIEW and EXPERIMENTAL, respectively. # This logic is literally copy and pasted from balena UI, but # there are plans to move this to `resin-device-types` so it # should be a matter of time for this to be removed. return map deviceTypes, (deviceType) -> if deviceType.state is 'DISCONTINUED' deviceType.name = deviceType.name.replace(/(\(PREVIEW|EXPERIMENTAL\))/, '(DISCONTINUED)') if deviceType.state is 'PREVIEW' deviceType.state = 'ALPHA' deviceType.name = deviceType.name.replace('(PREVIEW)', '(ALPHA)') if deviceType.state is 'EXPERIMENTAL' # Keep 'BETA' as the state until the next major, just in case someone is using this # TODO: In the next major change it to 'NEW' deviceType.state = 'BETA' deviceType.name = deviceType.name.replace('(EXPERIMENTAL)', '(NEW)') return deviceType ###* # @summary Get all configuration # @name getAll # @public # @function # @memberof balena.models.config # # @fulfil {Object} - configuration # @returns {Promise} # # @example # balena.models.config.getAll().then(function(config) { # console.log(config); # }); # # @example # balena.models.config.getAll(function(error, config) { # if (error) throw error; # console.log(config); # }); ### exports.getAll = (callback) -> request.send method: 'GET' url: '/config' baseUrl: apiUrl sendToken: false .get('body') .then (body) -> body.deviceTypes = normalizeDeviceTypes(body.deviceTypes) return body .asCallback(callback) ###* # @summary Get device types # @name getDeviceTypes # @public # @function # @memberof balena.models.config # # @fulfil {Object[]} - device types # @returns {Promise} # # @example # balena.models.config.getDeviceTypes().then(function(deviceTypes) { # console.log(deviceTypes); # }); # # @example # balena.models.config.getDeviceTypes(function(error, deviceTypes) { # if (error) throw error; # console.log(deviceTypes); # }) ### exports.getDeviceTypes = (callback) -> request.send method: 'GET' url: '/device-types/v1' baseUrl: apiUrl # optionaly authenticated, so we send the token in all cases .get('body') .tap (deviceTypes) -> if not deviceTypes? throw new Error('No device types') .then normalizeDeviceTypes .asCallback(callback) ###* # @summary Get configuration/initialization options for a device type # @name getDeviceOptions # @public # @function # @memberof balena.models.config # # @param {String} deviceType - device type slug # @fulfil {Object[]} - configuration options # @returns {Promise} # # @example # balena.models.config.getDeviceOptions('raspberry-pi').then(function(options) { # console.log(options); # }); # # @example # balena.models.config.getDeviceOptions('raspberry-pi', function(error, options) { # if (error) throw error; # console.log(options); # }); ### exports.getDeviceOptions = (deviceType, callback) -> deviceModel().getManifestBySlug(deviceType).then (manifest) -> manifest.initialization ?= {} return union(manifest.options, manifest.initialization.options) .asCallback(callback) return exports module.exports = getConfigModel
72217
### Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### once = require('lodash/once') union = require('lodash/union') map = require('lodash/map') getConfigModel = (deps, opts) -> { request } = deps { apiUrl } = opts deviceModel = once -> require('./device')(deps, opts) exports = {} normalizeDeviceTypes = (deviceTypes) -> # Patch device types to be marked as ALPHA and BETA instead # of PREVIEW and EXPERIMENTAL, respectively. # This logic is literally copy and pasted from balena UI, but # there are plans to move this to `resin-device-types` so it # should be a matter of time for this to be removed. return map deviceTypes, (deviceType) -> if deviceType.state is 'DISCONTINUED' deviceType.name = deviceType.name.replace(/(\(PREVIEW|EXPERIMENTAL\))/, '(DISCONTINUED)') if deviceType.state is 'PREVIEW' deviceType.state = 'ALPHA' deviceType.name = deviceType.name.replace('(PREVIEW)', '(ALPHA)') if deviceType.state is 'EXPERIMENTAL' # Keep 'BETA' as the state until the next major, just in case someone is using this # TODO: In the next major change it to 'NEW' deviceType.state = 'BETA' deviceType.name = deviceType.name.replace('(EXPERIMENTAL)', '(NEW)') return deviceType ###* # @summary Get all configuration # @name getAll # @public # @function # @memberof balena.models.config # # @fulfil {Object} - configuration # @returns {Promise} # # @example # balena.models.config.getAll().then(function(config) { # console.log(config); # }); # # @example # balena.models.config.getAll(function(error, config) { # if (error) throw error; # console.log(config); # }); ### exports.getAll = (callback) -> request.send method: 'GET' url: '/config' baseUrl: apiUrl sendToken: false .get('body') .then (body) -> body.deviceTypes = normalizeDeviceTypes(body.deviceTypes) return body .asCallback(callback) ###* # @summary Get device types # @name getDeviceTypes # @public # @function # @memberof balena.models.config # # @fulfil {Object[]} - device types # @returns {Promise} # # @example # balena.models.config.getDeviceTypes().then(function(deviceTypes) { # console.log(deviceTypes); # }); # # @example # balena.models.config.getDeviceTypes(function(error, deviceTypes) { # if (error) throw error; # console.log(deviceTypes); # }) ### exports.getDeviceTypes = (callback) -> request.send method: 'GET' url: '/device-types/v1' baseUrl: apiUrl # optionaly authenticated, so we send the token in all cases .get('body') .tap (deviceTypes) -> if not deviceTypes? throw new Error('No device types') .then normalizeDeviceTypes .asCallback(callback) ###* # @summary Get configuration/initialization options for a device type # @name getDeviceOptions # @public # @function # @memberof balena.models.config # # @param {String} deviceType - device type slug # @fulfil {Object[]} - configuration options # @returns {Promise} # # @example # balena.models.config.getDeviceOptions('raspberry-pi').then(function(options) { # console.log(options); # }); # # @example # balena.models.config.getDeviceOptions('raspberry-pi', function(error, options) { # if (error) throw error; # console.log(options); # }); ### exports.getDeviceOptions = (deviceType, callback) -> deviceModel().getManifestBySlug(deviceType).then (manifest) -> manifest.initialization ?= {} return union(manifest.options, manifest.initialization.options) .asCallback(callback) return exports module.exports = getConfigModel
true
### Copyright 2016 PI:NAME:<NAME>END_PI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### once = require('lodash/once') union = require('lodash/union') map = require('lodash/map') getConfigModel = (deps, opts) -> { request } = deps { apiUrl } = opts deviceModel = once -> require('./device')(deps, opts) exports = {} normalizeDeviceTypes = (deviceTypes) -> # Patch device types to be marked as ALPHA and BETA instead # of PREVIEW and EXPERIMENTAL, respectively. # This logic is literally copy and pasted from balena UI, but # there are plans to move this to `resin-device-types` so it # should be a matter of time for this to be removed. return map deviceTypes, (deviceType) -> if deviceType.state is 'DISCONTINUED' deviceType.name = deviceType.name.replace(/(\(PREVIEW|EXPERIMENTAL\))/, '(DISCONTINUED)') if deviceType.state is 'PREVIEW' deviceType.state = 'ALPHA' deviceType.name = deviceType.name.replace('(PREVIEW)', '(ALPHA)') if deviceType.state is 'EXPERIMENTAL' # Keep 'BETA' as the state until the next major, just in case someone is using this # TODO: In the next major change it to 'NEW' deviceType.state = 'BETA' deviceType.name = deviceType.name.replace('(EXPERIMENTAL)', '(NEW)') return deviceType ###* # @summary Get all configuration # @name getAll # @public # @function # @memberof balena.models.config # # @fulfil {Object} - configuration # @returns {Promise} # # @example # balena.models.config.getAll().then(function(config) { # console.log(config); # }); # # @example # balena.models.config.getAll(function(error, config) { # if (error) throw error; # console.log(config); # }); ### exports.getAll = (callback) -> request.send method: 'GET' url: '/config' baseUrl: apiUrl sendToken: false .get('body') .then (body) -> body.deviceTypes = normalizeDeviceTypes(body.deviceTypes) return body .asCallback(callback) ###* # @summary Get device types # @name getDeviceTypes # @public # @function # @memberof balena.models.config # # @fulfil {Object[]} - device types # @returns {Promise} # # @example # balena.models.config.getDeviceTypes().then(function(deviceTypes) { # console.log(deviceTypes); # }); # # @example # balena.models.config.getDeviceTypes(function(error, deviceTypes) { # if (error) throw error; # console.log(deviceTypes); # }) ### exports.getDeviceTypes = (callback) -> request.send method: 'GET' url: '/device-types/v1' baseUrl: apiUrl # optionaly authenticated, so we send the token in all cases .get('body') .tap (deviceTypes) -> if not deviceTypes? throw new Error('No device types') .then normalizeDeviceTypes .asCallback(callback) ###* # @summary Get configuration/initialization options for a device type # @name getDeviceOptions # @public # @function # @memberof balena.models.config # # @param {String} deviceType - device type slug # @fulfil {Object[]} - configuration options # @returns {Promise} # # @example # balena.models.config.getDeviceOptions('raspberry-pi').then(function(options) { # console.log(options); # }); # # @example # balena.models.config.getDeviceOptions('raspberry-pi', function(error, options) { # if (error) throw error; # console.log(options); # }); ### exports.getDeviceOptions = (deviceType, callback) -> deviceModel().getManifestBySlug(deviceType).then (manifest) -> manifest.initialization ?= {} return union(manifest.options, manifest.initialization.options) .asCallback(callback) return exports module.exports = getConfigModel
[ { "context": "ute', (done) ->\n model = new Model({name: 'Bob', type: 'thing'})\n model.save (err) ->\n ", "end": 1167, "score": 0.9994315505027771, "start": 1164, "tag": "NAME", "value": "Bob" }, { "context": "tes', (done) ->\n model = new Model({name: 'Bob', ...
test/spec/sync/capabilities/dynamic_attributes.tests.coffee
dk-dev/backbone-orm
54
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? return if not options.sync.capabilities(options.database_url or '').dynamic DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Dynamic Attributes Functionality #{options.$tags} @dynamic", -> Model = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class Model extends Backbone.Model url: "#{DATABASE_URL}/models" sync: SYNC(Model) after (callback) -> Utils.resetSchemas [Model], callback beforeEach (callback) -> Utils.resetSchemas [Model], callback # TODO: these fail when the model cache is enabled describe 'unset', -> it 'should unset an attribute', (done) -> model = new Model({name: 'Bob', type: 'thing'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done() it 'should unset two attributes', (done) -> model = new Model({name: 'Bob', type: 'thing', direction: 'north'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') model.unset('direction') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute 'type' is still unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute 'direction' is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(saved_model.get('direction')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic', direction: 'south'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute 'type' was set") assert.ok(!_.isUndefined(saved_model.get('direction')), "Attribute 'direction' was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done()
161146
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? return if not options.sync.capabilities(options.database_url or '').dynamic DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Dynamic Attributes Functionality #{options.$tags} @dynamic", -> Model = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class Model extends Backbone.Model url: "#{DATABASE_URL}/models" sync: SYNC(Model) after (callback) -> Utils.resetSchemas [Model], callback beforeEach (callback) -> Utils.resetSchemas [Model], callback # TODO: these fail when the model cache is enabled describe 'unset', -> it 'should unset an attribute', (done) -> model = new Model({name: '<NAME>', type: 'thing'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done() it 'should unset two attributes', (done) -> model = new Model({name: '<NAME>', type: 'thing', direction: 'north'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') model.unset('direction') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute 'type' is still unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute 'direction' is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(saved_model.get('direction')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic', direction: 'south'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute 'type' was set") assert.ok(!_.isUndefined(saved_model.get('direction')), "Attribute 'direction' was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done()
true
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? return if not options.sync.capabilities(options.database_url or '').dynamic DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Dynamic Attributes Functionality #{options.$tags} @dynamic", -> Model = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class Model extends Backbone.Model url: "#{DATABASE_URL}/models" sync: SYNC(Model) after (callback) -> Utils.resetSchemas [Model], callback beforeEach (callback) -> Utils.resetSchemas [Model], callback # TODO: these fail when the model cache is enabled describe 'unset', -> it 'should unset an attribute', (done) -> model = new Model({name: 'PI:NAME:<NAME>END_PI', type: 'thing'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done() it 'should unset two attributes', (done) -> model = new Model({name: 'PI:NAME:<NAME>END_PI', type: 'thing', direction: 'north'}) model.save (err) -> assert.ok(!err, "No errors: #{err}") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "1 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # unset and confirm different instances model.unset('type') model.unset('direction') assert.ok(_.isUndefined(model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute was unset") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "2 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(_.isUndefined(model.get('type')), "Attribute 'type' is still unset") assert.ok(_.isUndefined(model.get('direction')), "Attribute 'direction' is still unset") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(_.isUndefined(saved_model.get('type')), "Attribute was unset") assert.ok(_.isUndefined(saved_model.get('direction')), "Attribute was unset") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "3 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") # try resetting model.set({type: 'dynamic', direction: 'south'}) assert.ok(!_.isUndefined(model.get('type')), "Attribute was set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute was set") if options.cache assert.deepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") else assert.notDeepEqual(model.toJSON(), saved_model.toJSON(), "4 Not Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") model.save (err) -> assert.ok(!err, "No errors: #{err}") assert.ok(!_.isUndefined(model.get('type')), "Attribute is still set") assert.ok(!_.isUndefined(model.get('direction')), "Attribute is still set") Model.findOne model.id, (err, saved_model) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!saved_model, "Found model: #{model.id}") assert.ok(!_.isUndefined(saved_model.get('type')), "Attribute 'type' was set") assert.ok(!_.isUndefined(saved_model.get('direction')), "Attribute 'direction' was set") assert.deepEqual(model.toJSON(), saved_model.toJSON(), "5 Expected: #{JSONUtils.stringify(model.toJSON())}. Actual: #{JSONUtils.stringify(saved_model.toJSON())}") done()
[ { "context": "e, @email, @password) ->\n\nlogins = [\n new Login \"ghostrider9511\", \"ghostrider9511@gmail.com\", \"dOg#ibCud!5D\"\n ne", "end": 169, "score": 0.9996634125709534, "start": 155, "tag": "USERNAME", "value": "ghostrider9511" }, { "context": "rd) ->\n\nlogins = [\n ne...
automation/src/index.coffee
codyseibert/random
3
spawn = require('child_process').spawn Promise = require 'bluebird' class Login constructor: (@username, @email, @password) -> logins = [ new Login "ghostrider9511", "ghostrider9511@gmail.com", "dOg#ibCud!5D" new Login "kigostacre", "kigostacre@thrma.com", "dOg#ibCud!5D" new Login "ceriputhic", "ceriputhic@thrma.com", "bad8C_dasc" new Login "jebuchirit", "jebuchirit@thrma.com", "bad8C_dasc" new Login "mupheporos", "mupheporos@thrma.com", "bad8C_dasc" new Login "cricracloc", "cricracloc@thrma.com", "bad8C_dasc" new Login "hoslehahej", "hoslehahej@thrma.com", "bad8C_dasc" ] promises = for login in logins do (login) -> username = login.username password = login.password channel = 'http://www.twitch.tv/officialpcmasterrace' new Promise (resolve, reject) -> watch = spawn 'coffee', ['index.coffee', username, password, channel] watch.stdout.on 'data', (data) -> console.log data watch.stderr.on 'data', (data) -> console.log data watch.on 'close', (code) -> resolve() Promise.all(promises).then -> console.log 'done with all'
206423
spawn = require('child_process').spawn Promise = require 'bluebird' class Login constructor: (@username, @email, @password) -> logins = [ new Login "ghostrider9511", "<EMAIL>", "dOg#ibCud!5D" new Login "kigostacre", "<EMAIL>", "dOg#ibCud!5D" new Login "ceriputhic", "<EMAIL>", "bad8C_dasc" new Login "jebuchirit", "<EMAIL>", "bad8C_dasc" new Login "mupheporos", "<EMAIL>", "bad8C_dasc" new Login "cricracloc", "<EMAIL>", "bad8C_dasc" new Login "hoslehahej", "<EMAIL>", "bad8C_dasc" ] promises = for login in logins do (login) -> username = login.username password = <PASSWORD> channel = 'http://www.twitch.tv/officialpcmasterrace' new Promise (resolve, reject) -> watch = spawn 'coffee', ['index.coffee', username, password, channel] watch.stdout.on 'data', (data) -> console.log data watch.stderr.on 'data', (data) -> console.log data watch.on 'close', (code) -> resolve() Promise.all(promises).then -> console.log 'done with all'
true
spawn = require('child_process').spawn Promise = require 'bluebird' class Login constructor: (@username, @email, @password) -> logins = [ new Login "ghostrider9511", "PI:EMAIL:<EMAIL>END_PI", "dOg#ibCud!5D" new Login "kigostacre", "PI:EMAIL:<EMAIL>END_PI", "dOg#ibCud!5D" new Login "ceriputhic", "PI:EMAIL:<EMAIL>END_PI", "bad8C_dasc" new Login "jebuchirit", "PI:EMAIL:<EMAIL>END_PI", "bad8C_dasc" new Login "mupheporos", "PI:EMAIL:<EMAIL>END_PI", "bad8C_dasc" new Login "cricracloc", "PI:EMAIL:<EMAIL>END_PI", "bad8C_dasc" new Login "hoslehahej", "PI:EMAIL:<EMAIL>END_PI", "bad8C_dasc" ] promises = for login in logins do (login) -> username = login.username password = PI:PASSWORD:<PASSWORD>END_PI channel = 'http://www.twitch.tv/officialpcmasterrace' new Promise (resolve, reject) -> watch = spawn 'coffee', ['index.coffee', username, password, channel] watch.stdout.on 'data', (data) -> console.log data watch.stderr.on 'data', (data) -> console.log data watch.on 'close', (code) -> resolve() Promise.all(promises).then -> console.log 'done with all'
[ { "context": "###\n# lib/seed/archives.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Seed the datab", "end": 53, "score": 0.9996594786643982, "start": 42, "tag": "NAME", "value": "Dan Nichols" } ]
lib/seed/archives.coffee
dlnichols/h_media
0
### # lib/seed/archives.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Seed the database with archives ### 'use strict' # External libs Async = require 'async' # Internal libs Factory = require '../../test/lib/factory' module.exports = [ 'users' (done, results) -> Async.parallel [ Factory.create.bind null, 'archive' # Factory.create.bind null, 'archive' ], (err, results) -> done(err) return ]
76642
### # lib/seed/archives.coffee # # © 2014 <NAME> # See LICENSE for more details # # Seed the database with archives ### 'use strict' # External libs Async = require 'async' # Internal libs Factory = require '../../test/lib/factory' module.exports = [ 'users' (done, results) -> Async.parallel [ Factory.create.bind null, 'archive' # Factory.create.bind null, 'archive' ], (err, results) -> done(err) return ]
true
### # lib/seed/archives.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Seed the database with archives ### 'use strict' # External libs Async = require 'async' # Internal libs Factory = require '../../test/lib/factory' module.exports = [ 'users' (done, results) -> Async.parallel [ Factory.create.bind null, 'archive' # Factory.create.bind null, 'archive' ], (err, results) -> done(err) return ]
[ { "context": "# geodist\n# Copyright (c) 2013 Charles Moncrief <cmoncrief@gmail.com>\n# MIT Licensed\n\nradiusUnits", "end": 47, "score": 0.9998701214790344, "start": 31, "tag": "NAME", "value": "Charles Moncrief" }, { "context": "# geodist\n# Copyright (c) 2013 Charles Moncrief <cmo...
src/geodist.coffee
cmoncrief/geodist
36
# geodist # Copyright (c) 2013 Charles Moncrief <cmoncrief@gmail.com> # MIT Licensed radiusUnits = 'feet': 20908800 'yards': 6969600 'miles': 3960 'mi': 3960 'kilometers': 6371 'km': 6371 'meters': 6371000 # Returns the distance between two points. Takes two points in varying # formats and an options hash. getDistance = (start, end, options = {}) -> [lat1, lon1] = parseCoordinates start [lat2, lon2] = parseCoordinates end earthRadius = getEarthRadius(options.unit) latDelta = (lat2 - lat1) * Math.PI / 180 lonDelta = (lon2 - lon1) * Math.PI / 180 lat1Rad = lat1 * Math.PI / 180 lat2Rad = lat2 * Math.PI / 180 a = Math.sin(latDelta / 2) * Math.sin(latDelta / 2) + Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) distance = earthRadius * c distance = Math.floor(distance) unless options.exact if options.limit if options.limit > distance then return true else return false distance = "#{distance} #{options.unit || 'miles'}" if options.format return distance # Parses the latitude and longitude coordinates from the specfied point # argument and returns an array of [lat, lon]. parseCoordinates = (point = [0,0]) -> coords = [] if point instanceof Array coords = point else if point.lat? and point.lon? coords = [point.lat, point.lon] else if typeof point is 'object' coords.push(val) for key, val of point else coords = point return coords # Returns the radius of the earth in the specfied units. getEarthRadius = (unit = "miles") -> unit = unit.toLowerCase() unit = "miles" unless radiusUnits[unit] radiusUnits[unit] # Expose the getDistance function module.exports = getDistance
157233
# geodist # Copyright (c) 2013 <NAME> <<EMAIL>> # MIT Licensed radiusUnits = 'feet': 20908800 'yards': 6969600 'miles': 3960 'mi': 3960 'kilometers': 6371 'km': 6371 'meters': 6371000 # Returns the distance between two points. Takes two points in varying # formats and an options hash. getDistance = (start, end, options = {}) -> [lat1, lon1] = parseCoordinates start [lat2, lon2] = parseCoordinates end earthRadius = getEarthRadius(options.unit) latDelta = (lat2 - lat1) * Math.PI / 180 lonDelta = (lon2 - lon1) * Math.PI / 180 lat1Rad = lat1 * Math.PI / 180 lat2Rad = lat2 * Math.PI / 180 a = Math.sin(latDelta / 2) * Math.sin(latDelta / 2) + Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) distance = earthRadius * c distance = Math.floor(distance) unless options.exact if options.limit if options.limit > distance then return true else return false distance = "#{distance} #{options.unit || 'miles'}" if options.format return distance # Parses the latitude and longitude coordinates from the specfied point # argument and returns an array of [lat, lon]. parseCoordinates = (point = [0,0]) -> coords = [] if point instanceof Array coords = point else if point.lat? and point.lon? coords = [point.lat, point.lon] else if typeof point is 'object' coords.push(val) for key, val of point else coords = point return coords # Returns the radius of the earth in the specfied units. getEarthRadius = (unit = "miles") -> unit = unit.toLowerCase() unit = "miles" unless radiusUnits[unit] radiusUnits[unit] # Expose the getDistance function module.exports = getDistance
true
# geodist # Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # MIT Licensed radiusUnits = 'feet': 20908800 'yards': 6969600 'miles': 3960 'mi': 3960 'kilometers': 6371 'km': 6371 'meters': 6371000 # Returns the distance between two points. Takes two points in varying # formats and an options hash. getDistance = (start, end, options = {}) -> [lat1, lon1] = parseCoordinates start [lat2, lon2] = parseCoordinates end earthRadius = getEarthRadius(options.unit) latDelta = (lat2 - lat1) * Math.PI / 180 lonDelta = (lon2 - lon1) * Math.PI / 180 lat1Rad = lat1 * Math.PI / 180 lat2Rad = lat2 * Math.PI / 180 a = Math.sin(latDelta / 2) * Math.sin(latDelta / 2) + Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) distance = earthRadius * c distance = Math.floor(distance) unless options.exact if options.limit if options.limit > distance then return true else return false distance = "#{distance} #{options.unit || 'miles'}" if options.format return distance # Parses the latitude and longitude coordinates from the specfied point # argument and returns an array of [lat, lon]. parseCoordinates = (point = [0,0]) -> coords = [] if point instanceof Array coords = point else if point.lat? and point.lon? coords = [point.lat, point.lon] else if typeof point is 'object' coords.push(val) for key, val of point else coords = point return coords # Returns the radius of the earth in the specfied units. getEarthRadius = (unit = "miles") -> unit = unit.toLowerCase() unit = "miles" unless radiusUnits[unit] radiusUnits[unit] # Expose the getDistance function module.exports = getDistance
[ { "context": " @loadFixtures()\n # @user =\n # username: 'foobar1'\n # email: \"foobar1@example.com\"\n # pas", "end": 184, "score": 0.9994755983352661, "start": 177, "tag": "USERNAME", "value": "foobar1" }, { "context": "ser =\n # username: 'foobar1'\n # ...
spec/javascripts/controllers/AuthCtrl_spec.coffee
baberthal/cocktails
0
#= require spec_helper describe 'AuthCtrl', -> beforeEach -> @setupController('AuthCtrl') @Auth = @model('Auth') @loadFixtures() # @user = # username: 'foobar1' # email: "foobar1@example.com" # password: 'foobar1secret' @templateExpectations() describe 'controller initialization', -> describe 'logging in', -> it 'properly calls the backend and logs in the user', -> @scope.login() @http.whenPOST('/users/sign_in.json').respond(201, @newUser) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'registering', -> it 'properly calls the backend and registers the user', -> @scope.user = @newUser @scope.register() @http.whenPOST('/users.json').respond(201) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'cancelling the dialog', -> it 'calls $mdDialog.cancel()', -> mdDialog = @injector.get('$mdDialog') spyOn(mdDialog, 'cancel') @scope.cancel() expect(mdDialog.cancel).toHaveBeenCalled()
144943
#= require spec_helper describe 'AuthCtrl', -> beforeEach -> @setupController('AuthCtrl') @Auth = @model('Auth') @loadFixtures() # @user = # username: 'foobar1' # email: "<EMAIL>" # password: '<PASSWORD>' @templateExpectations() describe 'controller initialization', -> describe 'logging in', -> it 'properly calls the backend and logs in the user', -> @scope.login() @http.whenPOST('/users/sign_in.json').respond(201, @newUser) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'registering', -> it 'properly calls the backend and registers the user', -> @scope.user = @newUser @scope.register() @http.whenPOST('/users.json').respond(201) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'cancelling the dialog', -> it 'calls $mdDialog.cancel()', -> mdDialog = @injector.get('$mdDialog') spyOn(mdDialog, 'cancel') @scope.cancel() expect(mdDialog.cancel).toHaveBeenCalled()
true
#= require spec_helper describe 'AuthCtrl', -> beforeEach -> @setupController('AuthCtrl') @Auth = @model('Auth') @loadFixtures() # @user = # username: 'foobar1' # email: "PI:EMAIL:<EMAIL>END_PI" # password: 'PI:PASSWORD:<PASSWORD>END_PI' @templateExpectations() describe 'controller initialization', -> describe 'logging in', -> it 'properly calls the backend and logs in the user', -> @scope.login() @http.whenPOST('/users/sign_in.json').respond(201, @newUser) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'registering', -> it 'properly calls the backend and registers the user', -> @scope.user = @newUser @scope.register() @http.whenPOST('/users.json').respond(201) @http.flush() expect(@scope.signedIn).toBeTruthy() describe 'cancelling the dialog', -> it 'calls $mdDialog.cancel()', -> mdDialog = @injector.get('$mdDialog') spyOn(mdDialog, 'cancel') @scope.cancel() expect(mdDialog.cancel).toHaveBeenCalled()
[ { "context": "rience\n money: user.money\n username: user.username\n Identities: user.getIdentities().map (ide", "end": 777, "score": 0.9978882670402527, "start": 764, "tag": "USERNAME", "value": "user.username" }, { "context": "upation: identity.occupation\n ...
GOTHAM/Backend/src/Networking/Rooms/UserRoom.coffee
perara/gotham
0
Room = require './Room.coffee' ###* # UserRoom, Room which contains emitter related to user events # @class UserRoom # @module Backend # @submodule Backend.Networking # @extends Room ### class UserRoom extends Room define: -> that = @ ###* # Emitter for getting a user (Defined as class, but is in reality a method inside UserRoom) # @class Emitter_GetUser # @submodule Backend.Emitters ### @addEvent "GetUser", (data) -> client = that.getClient(@id) db_user = Gotham.LocalDatabase.table("User") user = db_user.findOne({id: client.getUser().id}) client.Socket.emit 'GetUser', { id: user.id email: user.email experience: user.experience money: user.money username: user.username Identities: user.getIdentities().map (identity) -> return { active: identity.active address: identity.address birthday: identity.birthday city: identity.city company: identity.company country: identity.country email: identity.email first_name: identity.first_name fk_user: identity.fk_user id: identity.id last_name: identity.last_name lat: identity.lat lng: identity.lng occupation: identity.occupation password: identity.password username: identity.username Networks: identity.getNetworks().map (network) -> return { external_ip_v4: network.external_ip_v4 id: network.id identity: network.identity internal_ip_v4: network.internal_ip_v4 isLocal: network.isLocal lat: network.lat lng: network.lng node: network.node submask: network.submask Node: network.getNode().id Hosts: network.getHosts().map (host) -> return { filesystem: host.filesystem online: host.online id: host.id ip: host.ip mac: host.mac machine_name: host.machine_name network: host.network Filesystem: host.getFilesystem() } # Hosts } # Networks } # Identities } # User Object module.exports = UserRoom
208888
Room = require './Room.coffee' ###* # UserRoom, Room which contains emitter related to user events # @class UserRoom # @module Backend # @submodule Backend.Networking # @extends Room ### class UserRoom extends Room define: -> that = @ ###* # Emitter for getting a user (Defined as class, but is in reality a method inside UserRoom) # @class Emitter_GetUser # @submodule Backend.Emitters ### @addEvent "GetUser", (data) -> client = that.getClient(@id) db_user = Gotham.LocalDatabase.table("User") user = db_user.findOne({id: client.getUser().id}) client.Socket.emit 'GetUser', { id: user.id email: user.email experience: user.experience money: user.money username: user.username Identities: user.getIdentities().map (identity) -> return { active: identity.active address: identity.address birthday: identity.birthday city: identity.city company: identity.company country: identity.country email: identity.email first_name: identity.first_name fk_user: identity.fk_user id: identity.id last_name: identity.last_name lat: identity.lat lng: identity.lng occupation: identity.occupation password: <PASSWORD> username: identity.username Networks: identity.getNetworks().map (network) -> return { external_ip_v4: network.external_ip_v4 id: network.id identity: network.identity internal_ip_v4: network.internal_ip_v4 isLocal: network.isLocal lat: network.lat lng: network.lng node: network.node submask: network.submask Node: network.getNode().id Hosts: network.getHosts().map (host) -> return { filesystem: host.filesystem online: host.online id: host.id ip: host.ip mac: host.mac machine_name: host.machine_name network: host.network Filesystem: host.getFilesystem() } # Hosts } # Networks } # Identities } # User Object module.exports = UserRoom
true
Room = require './Room.coffee' ###* # UserRoom, Room which contains emitter related to user events # @class UserRoom # @module Backend # @submodule Backend.Networking # @extends Room ### class UserRoom extends Room define: -> that = @ ###* # Emitter for getting a user (Defined as class, but is in reality a method inside UserRoom) # @class Emitter_GetUser # @submodule Backend.Emitters ### @addEvent "GetUser", (data) -> client = that.getClient(@id) db_user = Gotham.LocalDatabase.table("User") user = db_user.findOne({id: client.getUser().id}) client.Socket.emit 'GetUser', { id: user.id email: user.email experience: user.experience money: user.money username: user.username Identities: user.getIdentities().map (identity) -> return { active: identity.active address: identity.address birthday: identity.birthday city: identity.city company: identity.company country: identity.country email: identity.email first_name: identity.first_name fk_user: identity.fk_user id: identity.id last_name: identity.last_name lat: identity.lat lng: identity.lng occupation: identity.occupation password: PI:PASSWORD:<PASSWORD>END_PI username: identity.username Networks: identity.getNetworks().map (network) -> return { external_ip_v4: network.external_ip_v4 id: network.id identity: network.identity internal_ip_v4: network.internal_ip_v4 isLocal: network.isLocal lat: network.lat lng: network.lng node: network.node submask: network.submask Node: network.getNode().id Hosts: network.getHosts().map (host) -> return { filesystem: host.filesystem online: host.online id: host.id ip: host.ip mac: host.mac machine_name: host.machine_name network: host.network Filesystem: host.getFilesystem() } # Hosts } # Networks } # Identities } # User Object module.exports = UserRoom
[ { "context": "count\n tom_account = balancesheet.get_account('Tom')\n tom_account.should.be.an.instanceOf(Account", "end": 521, "score": 0.9993647933006287, "start": 518, "tag": "NAME", "value": "Tom" }, { "context": "unt)\n dick_account = balancesheet.get_account('Dick')\n ...
test/datastore/balancesheet.coffee
PartTimeLegend/buttercoin-engine
8
BalanceSheet = require('../../lib/datastore/balancesheet') Account = require('../../lib/datastore/account') describe 'BalanceSheet', -> it 'should initialize with no accounts', -> balancesheet = new BalanceSheet() Object.keys(balancesheet.accounts).should.be.empty it 'should add new account instances as they are requested if and only if they dont already exist', -> balancesheet = new BalanceSheet() # get_account should return instances of Account tom_account = balancesheet.get_account('Tom') tom_account.should.be.an.instanceOf(Account) dick_account = balancesheet.get_account('Dick') dick_account.should.be.an.instanceOf(Account) harry_account = balancesheet.get_account('Harry') harry_account.should.be.an.instanceOf(Account) # accounts should be different instances harry_account.should.not.equal(tom_account) harry_account.should.not.equal(dick_account) tom_account.should.not.equal(dick_account) # get the accounts again and should get the same instances another_tom_account = balancesheet.get_account('Tom') another_tom_account.should.equal(tom_account) another_dick_account = balancesheet.get_account('Dick') another_dick_account.should.equal(dick_account) another_harry_account = balancesheet.get_account('Harry') another_harry_account.should.equal(harry_account)
161454
BalanceSheet = require('../../lib/datastore/balancesheet') Account = require('../../lib/datastore/account') describe 'BalanceSheet', -> it 'should initialize with no accounts', -> balancesheet = new BalanceSheet() Object.keys(balancesheet.accounts).should.be.empty it 'should add new account instances as they are requested if and only if they dont already exist', -> balancesheet = new BalanceSheet() # get_account should return instances of Account tom_account = balancesheet.get_account('<NAME>') tom_account.should.be.an.instanceOf(Account) dick_account = balancesheet.get_account('<NAME>') dick_account.should.be.an.instanceOf(Account) harry_account = balancesheet.get_account('<NAME>') harry_account.should.be.an.instanceOf(Account) # accounts should be different instances harry_account.should.not.equal(tom_account) harry_account.should.not.equal(dick_account) tom_account.should.not.equal(dick_account) # get the accounts again and should get the same instances another_tom_account = balancesheet.get_account('<NAME>') another_tom_account.should.equal(tom_account) another_dick_account = balancesheet.get_account('<NAME>') another_dick_account.should.equal(dick_account) another_harry_account = balancesheet.get_account('<NAME>') another_harry_account.should.equal(harry_account)
true
BalanceSheet = require('../../lib/datastore/balancesheet') Account = require('../../lib/datastore/account') describe 'BalanceSheet', -> it 'should initialize with no accounts', -> balancesheet = new BalanceSheet() Object.keys(balancesheet.accounts).should.be.empty it 'should add new account instances as they are requested if and only if they dont already exist', -> balancesheet = new BalanceSheet() # get_account should return instances of Account tom_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') tom_account.should.be.an.instanceOf(Account) dick_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') dick_account.should.be.an.instanceOf(Account) harry_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') harry_account.should.be.an.instanceOf(Account) # accounts should be different instances harry_account.should.not.equal(tom_account) harry_account.should.not.equal(dick_account) tom_account.should.not.equal(dick_account) # get the accounts again and should get the same instances another_tom_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') another_tom_account.should.equal(tom_account) another_dick_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') another_dick_account.should.equal(dick_account) another_harry_account = balancesheet.get_account('PI:NAME:<NAME>END_PI') another_harry_account.should.equal(harry_account)
[ { "context": "ms with identical hash values\", ->\n key_a = new FunnyKey(257)\n key_b = new FunnyKey(513)\n key_c =", "end": 3762, "score": 0.6667735576629639, "start": 3757, "tag": "KEY", "value": "Funny" }, { "context": "entical hash values\", ->\n key_a = new FunnyKey(...
spec/hash_map_spec.coffee
odf/pazy.js
0
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashMap } = require 'indexed' else { seq, HashMap } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a[0].value - b[0].value describe "A HashMap", -> describe "with two items the first of which is removed", -> hash = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> h = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') expect(hash).not.toBe h describe "when empty", -> hash = new HashMap() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should not return anything on get", -> expect(hash.get("first")).not.toBeDefined() it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashMap(EmptyNode)", -> expect(hash.toString()).toEqual('HashMap(EmptyNode)') describe "containing one item", -> hash = new HashMap().plus(["first", 1]) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(hash.get("first")).toBe 1 it "should not return anything when fed another key", -> expect(hash.get("second")).not.toBeDefined() it "should be empty when the item is removed twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should contain the key-value pair", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", 1]) it "should print as HashMap(first ~> 1)", -> expect(hash.toString()).toEqual('HashMap(first ~> 1)') describe "the value of which is then changed", -> h = hash.plus(["first", "one"]) it "should have size 1", -> expect(h.size()).toBe 1 it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(h.get("first")).toBe "one" it "should not return anything when fed another key", -> expect(h.get("second")).not.toBeDefined() it "should contain the new key-value pair", -> a = h.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", "one"]) describe "containing two items with level one collision", -> key_a = new FunnyKey(1) key_b = new FunnyKey(33) key_c = new FunnyKey(5) hash = new HashMap().plus([key_a, "a"]).plus([key_b, "b"]) it "should contain two elements", -> expect(hash.size()).toBe 2 it "should not return anything when get is called with a third key", -> expect(hash.get(key_c)).not.toBeDefined() it "should not change when an item not included is removed", -> a = hash.minus(key_c).toArray() expect(a.length).toBe 2 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] it "should not be empty when the first item is removed", -> h = hash.minus(key_a) expect(h.size()).toBe 1 it "should be empty when all items are removed", -> h = hash.minus(key_a).minus(key_b) expect(h.size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new FunnyKey(257) key_b = new FunnyKey(513) key_c = new FunnyKey(769) key_d = new FunnyKey(33) hash = new HashMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"]) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toBe 2 expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] it "should contain four items when one with a new hash value is added", -> a = hash.plus([key_d, "d"]).toArray() expect(a.length).toBe 4 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] expect(a).toContain [key_d, "d"] describe "containing a wild mix of items", -> keys = (new FunnyKey(x * 5 + 7) for x in [0..16]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) describe "containing lots of items", -> keys = (new FunnyKey(x) for x in [0..300]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the correct number of items", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should not return anythin when fed another key", -> expect(hash.get("third")).not.toBeDefined() it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) it "should produce an item sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys on calling items()", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(items) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the remaining keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should not return anything for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(items[101..]) describe "from which some keys not included are removed", -> ex_keys = (new FunnyKey(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the original keys", -> expect(h.get(key)).toBe key.value for key in keys it "should not return anything for the 'removed' keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the original items as an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return nothing for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then replaced", -> ex_keys = keys[0..100] newItems = ([k, k.value.toString()] for k in ex_keys) h = hash.plus newItems... it "should have the same size as before", -> expect(h.size()).toBe hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for the untouched keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should return the new values for the modified keys", -> expect(h.get(key)).toBe key.value.toString() for key in ex_keys it "should contain the appropriate key-value pairs", -> a = h.toArray().sort(FunnyKey.sorter) expect(a[101..]).toEqual items[101..] expect(a[0..100]).toEqual ([k, v.toString()] for [k, v] in items[0..100]) describe "some of which are then overwritten with the original value", -> ex_keys = keys[0..100] newItems = ([k, k.value] for k in ex_keys) h = hash.plus newItems... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for all keys", -> expect(h.get(key)).toBe key.value for key in keys it "should contain the appropriate key-value pair", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items
61466
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashMap } = require 'indexed' else { seq, HashMap } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a[0].value - b[0].value describe "A HashMap", -> describe "with two items the first of which is removed", -> hash = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> h = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') expect(hash).not.toBe h describe "when empty", -> hash = new HashMap() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should not return anything on get", -> expect(hash.get("first")).not.toBeDefined() it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashMap(EmptyNode)", -> expect(hash.toString()).toEqual('HashMap(EmptyNode)') describe "containing one item", -> hash = new HashMap().plus(["first", 1]) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(hash.get("first")).toBe 1 it "should not return anything when fed another key", -> expect(hash.get("second")).not.toBeDefined() it "should be empty when the item is removed twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should contain the key-value pair", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", 1]) it "should print as HashMap(first ~> 1)", -> expect(hash.toString()).toEqual('HashMap(first ~> 1)') describe "the value of which is then changed", -> h = hash.plus(["first", "one"]) it "should have size 1", -> expect(h.size()).toBe 1 it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(h.get("first")).toBe "one" it "should not return anything when fed another key", -> expect(h.get("second")).not.toBeDefined() it "should contain the new key-value pair", -> a = h.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", "one"]) describe "containing two items with level one collision", -> key_a = new FunnyKey(1) key_b = new FunnyKey(33) key_c = new FunnyKey(5) hash = new HashMap().plus([key_a, "a"]).plus([key_b, "b"]) it "should contain two elements", -> expect(hash.size()).toBe 2 it "should not return anything when get is called with a third key", -> expect(hash.get(key_c)).not.toBeDefined() it "should not change when an item not included is removed", -> a = hash.minus(key_c).toArray() expect(a.length).toBe 2 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] it "should not be empty when the first item is removed", -> h = hash.minus(key_a) expect(h.size()).toBe 1 it "should be empty when all items are removed", -> h = hash.minus(key_a).minus(key_b) expect(h.size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new <KEY>Key(<KEY>) key_b = new <KEY>Key(<KEY>) key_c = new <KEY>Key(<KEY>) key_d = new <KEY>Key(<KEY>) hash = new HashMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"]) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toBe 2 expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] it "should contain four items when one with a new hash value is added", -> a = hash.plus([key_d, "d"]).toArray() expect(a.length).toBe 4 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] expect(a).toContain [key_d, "d"] describe "containing a wild mix of items", -> keys = (new FunnyKey(x * 5 + 7) for x in [0..16]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) describe "containing lots of items", -> keys = (new FunnyKey(x) for x in [0..300]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the correct number of items", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should not return anythin when fed another key", -> expect(hash.get("third")).not.toBeDefined() it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) it "should produce an item sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys on calling items()", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(items) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the remaining keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should not return anything for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(items[101..]) describe "from which some keys not included are removed", -> ex_keys = (new <KEY>Key(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the original keys", -> expect(h.get(key)).toBe key.value for key in keys it "should not return anything for the 'removed' keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the original items as an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return nothing for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then replaced", -> ex_keys = keys[0..100] newItems = ([k, k.value.toString()] for k in ex_keys) h = hash.plus newItems... it "should have the same size as before", -> expect(h.size()).toBe hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for the untouched keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should return the new values for the modified keys", -> expect(h.get(key)).toBe key.value.toString() for key in ex_keys it "should contain the appropriate key-value pairs", -> a = h.toArray().sort(FunnyKey.sorter) expect(a[101..]).toEqual items[101..] expect(a[0..100]).toEqual ([k, v.toString()] for [k, v] in items[0..100]) describe "some of which are then overwritten with the original value", -> ex_keys = keys[0..100] newItems = ([k, k.value] for k in ex_keys) h = hash.plus newItems... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for all keys", -> expect(h.get(key)).toBe key.value for key in keys it "should contain the appropriate key-value pair", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items
true
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashMap } = require 'indexed' else { seq, HashMap } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a[0].value - b[0].value describe "A HashMap", -> describe "with two items the first of which is removed", -> hash = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> h = new HashMap().plus(['A', true]).plus(['B', true]).minus('A') expect(hash).not.toBe h describe "when empty", -> hash = new HashMap() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should not return anything on get", -> expect(hash.get("first")).not.toBeDefined() it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashMap(EmptyNode)", -> expect(hash.toString()).toEqual('HashMap(EmptyNode)') describe "containing one item", -> hash = new HashMap().plus(["first", 1]) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(hash.get("first")).toBe 1 it "should not return anything when fed another key", -> expect(hash.get("second")).not.toBeDefined() it "should be empty when the item is removed twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should contain the key-value pair", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", 1]) it "should print as HashMap(first ~> 1)", -> expect(hash.toString()).toEqual('HashMap(first ~> 1)') describe "the value of which is then changed", -> h = hash.plus(["first", "one"]) it "should have size 1", -> expect(h.size()).toBe 1 it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated value for the key", -> expect(h.get("first")).toBe "one" it "should not return anything when fed another key", -> expect(h.get("second")).not.toBeDefined() it "should contain the new key-value pair", -> a = h.toArray() expect(a.length).toEqual 1 expect(a).toContain(["first", "one"]) describe "containing two items with level one collision", -> key_a = new FunnyKey(1) key_b = new FunnyKey(33) key_c = new FunnyKey(5) hash = new HashMap().plus([key_a, "a"]).plus([key_b, "b"]) it "should contain two elements", -> expect(hash.size()).toBe 2 it "should not return anything when get is called with a third key", -> expect(hash.get(key_c)).not.toBeDefined() it "should not change when an item not included is removed", -> a = hash.minus(key_c).toArray() expect(a.length).toBe 2 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] it "should not be empty when the first item is removed", -> h = hash.minus(key_a) expect(h.size()).toBe 1 it "should be empty when all items are removed", -> h = hash.minus(key_a).minus(key_b) expect(h.size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new PI:KEY:<KEY>END_PIKey(PI:KEY:<KEY>END_PI) key_b = new PI:KEY:<KEY>END_PIKey(PI:KEY:<KEY>END_PI) key_c = new PI:KEY:<KEY>END_PIKey(PI:KEY:<KEY>END_PI) key_d = new PI:KEY:<KEY>END_PIKey(PI:KEY:<KEY>END_PI) hash = new HashMap().plus([key_a, "a"], [key_b, "b"], [key_c, "c"]) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toBe 2 expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] it "should contain four items when one with a new hash value is added", -> a = hash.plus([key_d, "d"]).toArray() expect(a.length).toBe 4 expect(a).toContain [key_a, "a"] expect(a).toContain [key_b, "b"] expect(a).toContain [key_c, "c"] expect(a).toContain [key_d, "d"] describe "containing a wild mix of items", -> keys = (new FunnyKey(x * 5 + 7) for x in [0..16]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) describe "containing lots of items", -> keys = (new FunnyKey(x) for x in [0..300]) items = ([key, key.value] for key in keys) hash = (new HashMap()).plus items... it "should have the correct number of items", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should retrieve the associated value for each key", -> expect(hash.get(key)).toBe key.value for key in keys it "should not return anythin when fed another key", -> expect(hash.get("third")).not.toBeDefined() it "should contain all the items when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(items) it "should produce an item sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys on calling items()", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(items) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the remaining keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should not return anything for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(items[101..]) describe "from which some keys not included are removed", -> ex_keys = (new PI:KEY:<KEY>END_PIKey(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the associated values for the original keys", -> expect(h.get(key)).toBe key.value for key in keys it "should not return anything for the 'removed' keys", -> expect(h.get(key)).not.toBeDefined() for key in ex_keys it "should have exactly the original items as an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return nothing for the removed keys", -> expect(h.get(key)).not.toBeDefined() for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then replaced", -> ex_keys = keys[0..100] newItems = ([k, k.value.toString()] for k in ex_keys) h = hash.plus newItems... it "should have the same size as before", -> expect(h.size()).toBe hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for the untouched keys", -> expect(h.get(key)).toBe key.value for key in keys when key not in ex_keys it "should return the new values for the modified keys", -> expect(h.get(key)).toBe key.value.toString() for key in ex_keys it "should contain the appropriate key-value pairs", -> a = h.toArray().sort(FunnyKey.sorter) expect(a[101..]).toEqual items[101..] expect(a[0..100]).toEqual ([k, v.toString()] for [k, v] in items[0..100]) describe "some of which are then overwritten with the original value", -> ex_keys = keys[0..100] newItems = ([k, k.value] for k in ex_keys) h = hash.plus newItems... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should retrieve the original values for all keys", -> expect(h.get(key)).toBe key.value for key in keys it "should contain the appropriate key-value pair", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual items
[ { "context": "tist's request)\n JSON.stringify(item).match(/kippenberger|zoe.*leonard/i)\n", "end": 449, "score": 0.9408758282661438, "start": 437, "tag": "NAME", "value": "kippenberger" }, { "context": "t)\n JSON.stringify(item).match(/kippenberger|zoe.*leonard/i)\n", ...
src/desktop/apps/search/collections/global_search_results.coffee
zephraph/force
1
_ = require 'underscore' Backbone = require 'backbone' sd = require('sharify').data SearchResult = require '../../../models/search_result.coffee' module.exports = class GlobalSearchResults extends Backbone.Collection model: SearchResult url: "#{sd.API_URL}/api/v1/match" parse: (response) -> _.reject response, (item) -> # HACK filter out sensitive results (at the artist's request) JSON.stringify(item).match(/kippenberger|zoe.*leonard/i)
25805
_ = require 'underscore' Backbone = require 'backbone' sd = require('sharify').data SearchResult = require '../../../models/search_result.coffee' module.exports = class GlobalSearchResults extends Backbone.Collection model: SearchResult url: "#{sd.API_URL}/api/v1/match" parse: (response) -> _.reject response, (item) -> # HACK filter out sensitive results (at the artist's request) JSON.stringify(item).match(/<NAME>|<NAME>.*<NAME>/i)
true
_ = require 'underscore' Backbone = require 'backbone' sd = require('sharify').data SearchResult = require '../../../models/search_result.coffee' module.exports = class GlobalSearchResults extends Backbone.Collection model: SearchResult url: "#{sd.API_URL}/api/v1/match" parse: (response) -> _.reject response, (item) -> # HACK filter out sensitive results (at the artist's request) JSON.stringify(item).match(/PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI.*PI:NAME:<NAME>END_PI/i)
[ { "context": "a = @getProperties \"email\", \"password\", \"password_confirmation\", \"title\", \"first_name\", \"last_name\", \"role\", \"co", "end": 358, "score": 0.6555001139640808, "start": 346, "tag": "PASSWORD", "value": "confirmation" } ]
app/scripts/controllers/profile/signup_controller.coffee
JulianMiller/opened.io
1
Openedui.ProfileSignupController = Ember.Controller.extend isLoading: false actions: signup: -> self = @ # dont go further if we sending already a request return if self.get('isLoading') self.set('isLoading', true) @set "role", @get("activeTab") data = @getProperties "email", "password", "password_confirmation", "title", "first_name", "last_name", "role", "code" # remove error message from previous attempts @set('errorMessage', null) # create user and get the token from api Ember.$.ajax( url: Openedui.API.url.signup() data: data type: "POST" dataType: 'json' success: (response) -> Openedui.session.authenticate response.api_key.access_token, response.api_key.user_id self.transitionToRoute("/") error: (response) -> self.set("errorMessage", JSON.parse(response.responseText)['errors']) ).always -> self.set('isLoading', false)
120414
Openedui.ProfileSignupController = Ember.Controller.extend isLoading: false actions: signup: -> self = @ # dont go further if we sending already a request return if self.get('isLoading') self.set('isLoading', true) @set "role", @get("activeTab") data = @getProperties "email", "password", "password_<PASSWORD>", "title", "first_name", "last_name", "role", "code" # remove error message from previous attempts @set('errorMessage', null) # create user and get the token from api Ember.$.ajax( url: Openedui.API.url.signup() data: data type: "POST" dataType: 'json' success: (response) -> Openedui.session.authenticate response.api_key.access_token, response.api_key.user_id self.transitionToRoute("/") error: (response) -> self.set("errorMessage", JSON.parse(response.responseText)['errors']) ).always -> self.set('isLoading', false)
true
Openedui.ProfileSignupController = Ember.Controller.extend isLoading: false actions: signup: -> self = @ # dont go further if we sending already a request return if self.get('isLoading') self.set('isLoading', true) @set "role", @get("activeTab") data = @getProperties "email", "password", "password_PI:PASSWORD:<PASSWORD>END_PI", "title", "first_name", "last_name", "role", "code" # remove error message from previous attempts @set('errorMessage', null) # create user and get the token from api Ember.$.ajax( url: Openedui.API.url.signup() data: data type: "POST" dataType: 'json' success: (response) -> Openedui.session.authenticate response.api_key.access_token, response.api_key.user_id self.transitionToRoute("/") error: (response) -> self.set("errorMessage", JSON.parse(response.responseText)['errors']) ).always -> self.set('isLoading', false)
[ { "context": "# Author: Josh Bass\n# Description: The React View for the Header bar ", "end": 19, "score": 0.9998741745948792, "start": 10, "tag": "NAME", "value": "Josh Bass" } ]
src/client/components/header_bar/HeaderBarView.coffee
jbass86/Aroma
0
# Author: Josh Bass # Description: The React View for the Header bar at the top of the mast diagnostic display. React = require("react"); mathjs = require("mathjs"); require("./res/styles/header_bar.scss") module.exports = React.createClass getInitialState: -> {time: "00:00:00", export_data_alert: false}; componentDidMount: -> window.setInterval(() => date = new Date(); @setState({time: date.toTimeString().split(' ')[0]}); , mathjs.unit("1 s").toNumber("ms")); render: -> <div className="header-bar unselectable"> <span className="glyphicon glyphicon-menu-hamburger menu-glyph nav-button" onClick={@menuButtonClicked} /> <span className="user-name">{window.user_info.username}</span> <span className="glyphicon glyphicon-log-out menu-glyph logout-button" onClick={@logout}></span> </div> getAlertClasses: () -> classes = "alert alert-danger box-shadow export-data-alert"; if (@state.export_data_alert) classes = classes + " fade-in"; else classes = classes + " fade-out" menuButtonClicked: (ev) -> @props.nav_model.set("nav_visible", !@props.nav_model.get("nav_visible")); logout: (ev) -> window.sessionStorage.token = undefined; window.location.reload(true);
203772
# Author: <NAME> # Description: The React View for the Header bar at the top of the mast diagnostic display. React = require("react"); mathjs = require("mathjs"); require("./res/styles/header_bar.scss") module.exports = React.createClass getInitialState: -> {time: "00:00:00", export_data_alert: false}; componentDidMount: -> window.setInterval(() => date = new Date(); @setState({time: date.toTimeString().split(' ')[0]}); , mathjs.unit("1 s").toNumber("ms")); render: -> <div className="header-bar unselectable"> <span className="glyphicon glyphicon-menu-hamburger menu-glyph nav-button" onClick={@menuButtonClicked} /> <span className="user-name">{window.user_info.username}</span> <span className="glyphicon glyphicon-log-out menu-glyph logout-button" onClick={@logout}></span> </div> getAlertClasses: () -> classes = "alert alert-danger box-shadow export-data-alert"; if (@state.export_data_alert) classes = classes + " fade-in"; else classes = classes + " fade-out" menuButtonClicked: (ev) -> @props.nav_model.set("nav_visible", !@props.nav_model.get("nav_visible")); logout: (ev) -> window.sessionStorage.token = undefined; window.location.reload(true);
true
# Author: PI:NAME:<NAME>END_PI # Description: The React View for the Header bar at the top of the mast diagnostic display. React = require("react"); mathjs = require("mathjs"); require("./res/styles/header_bar.scss") module.exports = React.createClass getInitialState: -> {time: "00:00:00", export_data_alert: false}; componentDidMount: -> window.setInterval(() => date = new Date(); @setState({time: date.toTimeString().split(' ')[0]}); , mathjs.unit("1 s").toNumber("ms")); render: -> <div className="header-bar unselectable"> <span className="glyphicon glyphicon-menu-hamburger menu-glyph nav-button" onClick={@menuButtonClicked} /> <span className="user-name">{window.user_info.username}</span> <span className="glyphicon glyphicon-log-out menu-glyph logout-button" onClick={@logout}></span> </div> getAlertClasses: () -> classes = "alert alert-danger box-shadow export-data-alert"; if (@state.export_data_alert) classes = classes + " fade-in"; else classes = classes + " fade-out" menuButtonClicked: (ev) -> @props.nav_model.set("nav_visible", !@props.nav_model.get("nav_visible")); logout: (ev) -> window.sessionStorage.token = undefined; window.location.reload(true);
[ { "context": "e-break-on-single-newline': ->\n keyPath = 'markdown-preview-plus.breakOnSingleNewline'\n atom.config.set(keyPath, not atom.config", "end": 4016, "score": 0.9977120757102966, "start": 3974, "tag": "KEY", "value": "markdown-preview-plus.breakOnSingleNewline" } ]
packages/markdown-preview-plus/lib/main.coffee
jarednipper/atom-config
0
url = require 'url' fs = require 'fs-plus' MarkdownPreviewView = null renderer = null mathjaxHelper = null isMarkdownPreviewView = (object) -> MarkdownPreviewView ?= require './markdown-preview-view' object instanceof MarkdownPreviewView module.exports = config: breakOnSingleNewline: type: 'boolean' default: false order: 0 liveUpdate: type: 'boolean' default: true order: 10 openPreviewInSplitPane: type: 'boolean' default: true order: 20 grammars: type: 'array' default: [ 'source.gfm' 'source.litcoffee' 'text.html.basic' 'text.md' 'text.plain' 'text.plain.null-grammar' ] order: 30 enableLatexRenderingByDefault: title: 'Enable Math Rendering By Default' type: 'boolean' default: false order: 40 useLazyHeaders: title: 'Use Lazy Headers' description: 'Require no space after headings #' type: 'boolean' default: true order: 45 useGitHubStyle: title: 'Use GitHub.com style' type: 'boolean' default: false order: 50 enablePandoc: type: 'boolean' default: false title: 'Enable Pandoc Parser' order: 100 pandocPath: type: 'string' default: 'pandoc' title: 'Pandoc Options: Path' description: 'Please specify the correct path to your pandoc executable' dependencies: ['enablePandoc'] order: 110 pandocArguments: type: 'array' default: [] title: 'Pandoc Options: Commandline Arguments' description: 'Comma separated pandoc arguments e.g. `--smart, --filter=/bin/exe`. Please use long argument names.' dependencies: ['enablePandoc'] order: 120 pandocMarkdownFlavor: type: 'string' default: 'markdown-raw_tex+tex_math_single_backslash' title: 'Pandoc Options: Markdown Flavor' description: 'Enter the pandoc markdown flavor you want' dependencies: ['enablePandoc'] order: 130 pandocBibliography: type: 'boolean' default: false title: 'Pandoc Options: Citations' description: 'Enable this for bibliography parsing' dependencies: ['enablePandoc'] order: 140 pandocRemoveReferences: type: 'boolean' default: true title: 'Pandoc Options: Remove References' description: 'Removes references at the end of the HTML preview' dependencies: ['pandocBibliography'] order: 150 pandocBIBFile: type: 'string' default: 'bibliography.bib' title: 'Pandoc Options: Bibliography (bibfile)' description: 'Name of bibfile to search for recursivly' dependencies: ['pandocBibliography'] order: 160 pandocBIBFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography (bibfile)' description: 'Full path to fallback bibfile' dependencies: ['pandocBibliography'] order: 165 pandocCSLFile: type: 'string' default: 'custom.csl' title: 'Pandoc Options: Bibliography Style (cslfile)' description: 'Name of cslfile to search for recursivly' dependencies: ['pandocBibliography'] order: 170 pandocCSLFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography Style (cslfile)' description: 'Full path to fallback cslfile' dependencies: ['pandocBibliography'] order: 175 activate: -> if parseFloat(atom.getVersion()) < 1.7 atom.deserializers.add name: 'MarkdownPreviewView' deserialize: module.exports.createMarkdownPreviewView.bind(module.exports) atom.commands.add 'atom-workspace', 'markdown-preview-plus:toggle': => @toggle() 'markdown-preview-plus:copy-html': => @copyHtml() 'markdown-preview-plus:toggle-break-on-single-newline': -> keyPath = 'markdown-preview-plus.breakOnSingleNewline' atom.config.set(keyPath, not atom.config.get(keyPath)) previewFile = @previewFile.bind(this) atom.commands.add '.tree-view .file .name[data-name$=\\.markdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.md]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkd]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.ron]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.txt]', 'markdown-preview-plus:preview-file', previewFile atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'markdown-preview-plus:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' @createMarkdownPreviewView(editorId: pathname.substring(1)) else @createMarkdownPreviewView(filePath: pathname) createMarkdownPreviewView: (state) -> if state.editorId or fs.isFileSync(state.filePath) MarkdownPreviewView ?= require './markdown-preview-view' new MarkdownPreviewView(state) toggle: -> if isMarkdownPreviewView(atom.workspace.getActivePaneItem()) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveTextEditor() return unless editor? grammars = atom.config.get('markdown-preview-plus.grammars') ? [] return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "markdown-preview-plus://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) previewPane = atom.workspace.paneForURI(uri) if previewPane? preview = previewPane.itemForURI(uri) if preview isnt previewPane.getActiveItem() previewPane.activateItem(preview) return false previewPane.destroyItem(preview) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() options = searchAllPanes: true if atom.config.get('markdown-preview-plus.openPreviewInSplitPane') options.split = 'right' atom.workspace.open(uri, options).then (markdownPreviewView) -> if isMarkdownPreviewView(markdownPreviewView) previousActivePane.activate() previewFile: ({target}) -> filePath = target.dataset.path return unless filePath for editor in atom.workspace.getTextEditors() when editor.getPath() is filePath @addPreviewForEditor(editor) return atom.workspace.open "markdown-preview-plus://#{encodeURI(filePath)}", searchAllPanes: true copyHtml: (callback = atom.clipboard.write.bind(atom.clipboard), scaleMath = 100) -> editor = atom.workspace.getActiveTextEditor() return unless editor? renderer ?= require './renderer' text = editor.getSelectedText() or editor.getText() renderLaTeX = atom.config.get 'markdown-preview-plus.enableLatexRenderingByDefault' renderer.toHTML text, editor.getPath(), editor.getGrammar(), renderLaTeX, true, (error, html) -> if error console.warn('Copying Markdown as HTML failed', error) else if renderLaTeX mathjaxHelper ?= require './mathjax-helper' mathjaxHelper.processHTMLString html, (proHTML) -> proHTML = proHTML.replace /MathJax\_SVG.*?font\-size\: 100%/g, (match) -> match.replace /font\-size\: 100%/, "font-size: #{scaleMath}%" callback(proHTML) else callback(html)
119616
url = require 'url' fs = require 'fs-plus' MarkdownPreviewView = null renderer = null mathjaxHelper = null isMarkdownPreviewView = (object) -> MarkdownPreviewView ?= require './markdown-preview-view' object instanceof MarkdownPreviewView module.exports = config: breakOnSingleNewline: type: 'boolean' default: false order: 0 liveUpdate: type: 'boolean' default: true order: 10 openPreviewInSplitPane: type: 'boolean' default: true order: 20 grammars: type: 'array' default: [ 'source.gfm' 'source.litcoffee' 'text.html.basic' 'text.md' 'text.plain' 'text.plain.null-grammar' ] order: 30 enableLatexRenderingByDefault: title: 'Enable Math Rendering By Default' type: 'boolean' default: false order: 40 useLazyHeaders: title: 'Use Lazy Headers' description: 'Require no space after headings #' type: 'boolean' default: true order: 45 useGitHubStyle: title: 'Use GitHub.com style' type: 'boolean' default: false order: 50 enablePandoc: type: 'boolean' default: false title: 'Enable Pandoc Parser' order: 100 pandocPath: type: 'string' default: 'pandoc' title: 'Pandoc Options: Path' description: 'Please specify the correct path to your pandoc executable' dependencies: ['enablePandoc'] order: 110 pandocArguments: type: 'array' default: [] title: 'Pandoc Options: Commandline Arguments' description: 'Comma separated pandoc arguments e.g. `--smart, --filter=/bin/exe`. Please use long argument names.' dependencies: ['enablePandoc'] order: 120 pandocMarkdownFlavor: type: 'string' default: 'markdown-raw_tex+tex_math_single_backslash' title: 'Pandoc Options: Markdown Flavor' description: 'Enter the pandoc markdown flavor you want' dependencies: ['enablePandoc'] order: 130 pandocBibliography: type: 'boolean' default: false title: 'Pandoc Options: Citations' description: 'Enable this for bibliography parsing' dependencies: ['enablePandoc'] order: 140 pandocRemoveReferences: type: 'boolean' default: true title: 'Pandoc Options: Remove References' description: 'Removes references at the end of the HTML preview' dependencies: ['pandocBibliography'] order: 150 pandocBIBFile: type: 'string' default: 'bibliography.bib' title: 'Pandoc Options: Bibliography (bibfile)' description: 'Name of bibfile to search for recursivly' dependencies: ['pandocBibliography'] order: 160 pandocBIBFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography (bibfile)' description: 'Full path to fallback bibfile' dependencies: ['pandocBibliography'] order: 165 pandocCSLFile: type: 'string' default: 'custom.csl' title: 'Pandoc Options: Bibliography Style (cslfile)' description: 'Name of cslfile to search for recursivly' dependencies: ['pandocBibliography'] order: 170 pandocCSLFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography Style (cslfile)' description: 'Full path to fallback cslfile' dependencies: ['pandocBibliography'] order: 175 activate: -> if parseFloat(atom.getVersion()) < 1.7 atom.deserializers.add name: 'MarkdownPreviewView' deserialize: module.exports.createMarkdownPreviewView.bind(module.exports) atom.commands.add 'atom-workspace', 'markdown-preview-plus:toggle': => @toggle() 'markdown-preview-plus:copy-html': => @copyHtml() 'markdown-preview-plus:toggle-break-on-single-newline': -> keyPath = '<KEY>' atom.config.set(keyPath, not atom.config.get(keyPath)) previewFile = @previewFile.bind(this) atom.commands.add '.tree-view .file .name[data-name$=\\.markdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.md]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkd]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.ron]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.txt]', 'markdown-preview-plus:preview-file', previewFile atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'markdown-preview-plus:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' @createMarkdownPreviewView(editorId: pathname.substring(1)) else @createMarkdownPreviewView(filePath: pathname) createMarkdownPreviewView: (state) -> if state.editorId or fs.isFileSync(state.filePath) MarkdownPreviewView ?= require './markdown-preview-view' new MarkdownPreviewView(state) toggle: -> if isMarkdownPreviewView(atom.workspace.getActivePaneItem()) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveTextEditor() return unless editor? grammars = atom.config.get('markdown-preview-plus.grammars') ? [] return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "markdown-preview-plus://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) previewPane = atom.workspace.paneForURI(uri) if previewPane? preview = previewPane.itemForURI(uri) if preview isnt previewPane.getActiveItem() previewPane.activateItem(preview) return false previewPane.destroyItem(preview) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() options = searchAllPanes: true if atom.config.get('markdown-preview-plus.openPreviewInSplitPane') options.split = 'right' atom.workspace.open(uri, options).then (markdownPreviewView) -> if isMarkdownPreviewView(markdownPreviewView) previousActivePane.activate() previewFile: ({target}) -> filePath = target.dataset.path return unless filePath for editor in atom.workspace.getTextEditors() when editor.getPath() is filePath @addPreviewForEditor(editor) return atom.workspace.open "markdown-preview-plus://#{encodeURI(filePath)}", searchAllPanes: true copyHtml: (callback = atom.clipboard.write.bind(atom.clipboard), scaleMath = 100) -> editor = atom.workspace.getActiveTextEditor() return unless editor? renderer ?= require './renderer' text = editor.getSelectedText() or editor.getText() renderLaTeX = atom.config.get 'markdown-preview-plus.enableLatexRenderingByDefault' renderer.toHTML text, editor.getPath(), editor.getGrammar(), renderLaTeX, true, (error, html) -> if error console.warn('Copying Markdown as HTML failed', error) else if renderLaTeX mathjaxHelper ?= require './mathjax-helper' mathjaxHelper.processHTMLString html, (proHTML) -> proHTML = proHTML.replace /MathJax\_SVG.*?font\-size\: 100%/g, (match) -> match.replace /font\-size\: 100%/, "font-size: #{scaleMath}%" callback(proHTML) else callback(html)
true
url = require 'url' fs = require 'fs-plus' MarkdownPreviewView = null renderer = null mathjaxHelper = null isMarkdownPreviewView = (object) -> MarkdownPreviewView ?= require './markdown-preview-view' object instanceof MarkdownPreviewView module.exports = config: breakOnSingleNewline: type: 'boolean' default: false order: 0 liveUpdate: type: 'boolean' default: true order: 10 openPreviewInSplitPane: type: 'boolean' default: true order: 20 grammars: type: 'array' default: [ 'source.gfm' 'source.litcoffee' 'text.html.basic' 'text.md' 'text.plain' 'text.plain.null-grammar' ] order: 30 enableLatexRenderingByDefault: title: 'Enable Math Rendering By Default' type: 'boolean' default: false order: 40 useLazyHeaders: title: 'Use Lazy Headers' description: 'Require no space after headings #' type: 'boolean' default: true order: 45 useGitHubStyle: title: 'Use GitHub.com style' type: 'boolean' default: false order: 50 enablePandoc: type: 'boolean' default: false title: 'Enable Pandoc Parser' order: 100 pandocPath: type: 'string' default: 'pandoc' title: 'Pandoc Options: Path' description: 'Please specify the correct path to your pandoc executable' dependencies: ['enablePandoc'] order: 110 pandocArguments: type: 'array' default: [] title: 'Pandoc Options: Commandline Arguments' description: 'Comma separated pandoc arguments e.g. `--smart, --filter=/bin/exe`. Please use long argument names.' dependencies: ['enablePandoc'] order: 120 pandocMarkdownFlavor: type: 'string' default: 'markdown-raw_tex+tex_math_single_backslash' title: 'Pandoc Options: Markdown Flavor' description: 'Enter the pandoc markdown flavor you want' dependencies: ['enablePandoc'] order: 130 pandocBibliography: type: 'boolean' default: false title: 'Pandoc Options: Citations' description: 'Enable this for bibliography parsing' dependencies: ['enablePandoc'] order: 140 pandocRemoveReferences: type: 'boolean' default: true title: 'Pandoc Options: Remove References' description: 'Removes references at the end of the HTML preview' dependencies: ['pandocBibliography'] order: 150 pandocBIBFile: type: 'string' default: 'bibliography.bib' title: 'Pandoc Options: Bibliography (bibfile)' description: 'Name of bibfile to search for recursivly' dependencies: ['pandocBibliography'] order: 160 pandocBIBFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography (bibfile)' description: 'Full path to fallback bibfile' dependencies: ['pandocBibliography'] order: 165 pandocCSLFile: type: 'string' default: 'custom.csl' title: 'Pandoc Options: Bibliography Style (cslfile)' description: 'Name of cslfile to search for recursivly' dependencies: ['pandocBibliography'] order: 170 pandocCSLFileFallback: type: 'string' default: '' title: 'Pandoc Options: Fallback Bibliography Style (cslfile)' description: 'Full path to fallback cslfile' dependencies: ['pandocBibliography'] order: 175 activate: -> if parseFloat(atom.getVersion()) < 1.7 atom.deserializers.add name: 'MarkdownPreviewView' deserialize: module.exports.createMarkdownPreviewView.bind(module.exports) atom.commands.add 'atom-workspace', 'markdown-preview-plus:toggle': => @toggle() 'markdown-preview-plus:copy-html': => @copyHtml() 'markdown-preview-plus:toggle-break-on-single-newline': -> keyPath = 'PI:KEY:<KEY>END_PI' atom.config.set(keyPath, not atom.config.get(keyPath)) previewFile = @previewFile.bind(this) atom.commands.add '.tree-view .file .name[data-name$=\\.markdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.md]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkd]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.mkdown]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.ron]', 'markdown-preview-plus:preview-file', previewFile atom.commands.add '.tree-view .file .name[data-name$=\\.txt]', 'markdown-preview-plus:preview-file', previewFile atom.workspace.addOpener (uriToOpen) => try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'markdown-preview-plus:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' @createMarkdownPreviewView(editorId: pathname.substring(1)) else @createMarkdownPreviewView(filePath: pathname) createMarkdownPreviewView: (state) -> if state.editorId or fs.isFileSync(state.filePath) MarkdownPreviewView ?= require './markdown-preview-view' new MarkdownPreviewView(state) toggle: -> if isMarkdownPreviewView(atom.workspace.getActivePaneItem()) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveTextEditor() return unless editor? grammars = atom.config.get('markdown-preview-plus.grammars') ? [] return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "markdown-preview-plus://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) previewPane = atom.workspace.paneForURI(uri) if previewPane? preview = previewPane.itemForURI(uri) if preview isnt previewPane.getActiveItem() previewPane.activateItem(preview) return false previewPane.destroyItem(preview) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() options = searchAllPanes: true if atom.config.get('markdown-preview-plus.openPreviewInSplitPane') options.split = 'right' atom.workspace.open(uri, options).then (markdownPreviewView) -> if isMarkdownPreviewView(markdownPreviewView) previousActivePane.activate() previewFile: ({target}) -> filePath = target.dataset.path return unless filePath for editor in atom.workspace.getTextEditors() when editor.getPath() is filePath @addPreviewForEditor(editor) return atom.workspace.open "markdown-preview-plus://#{encodeURI(filePath)}", searchAllPanes: true copyHtml: (callback = atom.clipboard.write.bind(atom.clipboard), scaleMath = 100) -> editor = atom.workspace.getActiveTextEditor() return unless editor? renderer ?= require './renderer' text = editor.getSelectedText() or editor.getText() renderLaTeX = atom.config.get 'markdown-preview-plus.enableLatexRenderingByDefault' renderer.toHTML text, editor.getPath(), editor.getGrammar(), renderLaTeX, true, (error, html) -> if error console.warn('Copying Markdown as HTML failed', error) else if renderLaTeX mathjaxHelper ?= require './mathjax-helper' mathjaxHelper.processHTMLString html, (proHTML) -> proHTML = proHTML.replace /MathJax\_SVG.*?font\-size\: 100%/g, (match) -> match.replace /font\-size\: 100%/, "font-size: #{scaleMath}%" callback(proHTML) else callback(html)
[ { "context": "sitory('c')\n\n cRepo.save(id: 'xxx', name: 'shin')\n cRepo.save(id: 'yyy', name: 'satake')\n\n", "end": 1149, "score": 0.9994955062866211, "start": 1145, "tag": "NAME", "value": "shin" }, { "context": "ame: 'shin')\n cRepo.save(id: 'yyy', name: 'sa...
spec/lib/includer.coffee
CureApp/base-domain
37
Facade = require '../base-domain' { ValueObject, Entity, BaseAsyncRepository, BaseSyncRepository } = Facade { MemoryResource, Includer } = require '../others' describe 'Includer', -> before -> @facade = require('../create-facade').create() class A extends ValueObject @properties: b: @TYPES.MODEL 'b' c: @TYPES.MODEL 'c' class B extends Entity @properties: c: @TYPES.MODEL 'c' name: @TYPES.STRING class BRepository extends BaseAsyncRepository client: new MemoryResource() class CRepository extends BaseSyncRepository client: new MemoryResource() class C extends Entity @properties: name: @TYPES.STRING @facade.addClass('a', A) @facade.addClass('b', B) @facade.addClass('c', C) @facade.addClass('b-repository', BRepository) @facade.addClass('c-repository', CRepository) bRepo = @facade.createRepository('b') cRepo = @facade.createRepository('c') cRepo.save(id: 'xxx', name: 'shin') cRepo.save(id: 'yyy', name: 'satake') Promise.all([ bRepo.save(id: 'xxx', name: 'shin', cId: 'xxx') bRepo.save(id: 'yyy', name: 'satake', cId: 'yyy') ]) beforeEach -> @a = @facade.createModel('a', { bId: 'xxx', cId: 'xxx' }, include: null) describe 'include', -> it 'includes subEntities', -> class Main extends ValueObject @properties: name: @TYPES.STRING sub: @TYPES.MODEL 'sub-item', 'subId' class SubItem extends Entity @properties: name: @TYPES.STRING class SubItemRepository extends BaseAsyncRepository @modelName: 'sub-item' get: (id) -> item = @facade.createModel('sub-item', {id: id, name: 'mock'}) return Promise.resolve item f = require('../create-facade').create() f.addClass('main', Main) f.addClass('sub-item', SubItem) f.addClass('sub-item-repository', SubItemRepository) main = f.createModel 'main', name: 'xxx' subId: 'abc' main.include().then => assert main.sub instanceof f.getModel 'sub-item'
127493
Facade = require '../base-domain' { ValueObject, Entity, BaseAsyncRepository, BaseSyncRepository } = Facade { MemoryResource, Includer } = require '../others' describe 'Includer', -> before -> @facade = require('../create-facade').create() class A extends ValueObject @properties: b: @TYPES.MODEL 'b' c: @TYPES.MODEL 'c' class B extends Entity @properties: c: @TYPES.MODEL 'c' name: @TYPES.STRING class BRepository extends BaseAsyncRepository client: new MemoryResource() class CRepository extends BaseSyncRepository client: new MemoryResource() class C extends Entity @properties: name: @TYPES.STRING @facade.addClass('a', A) @facade.addClass('b', B) @facade.addClass('c', C) @facade.addClass('b-repository', BRepository) @facade.addClass('c-repository', CRepository) bRepo = @facade.createRepository('b') cRepo = @facade.createRepository('c') cRepo.save(id: 'xxx', name: '<NAME>') cRepo.save(id: 'yyy', name: '<NAME>') Promise.all([ bRepo.save(id: 'xxx', name: '<NAME>', cId: 'xxx') bRepo.save(id: 'yyy', name: '<NAME>', cId: 'yyy') ]) beforeEach -> @a = @facade.createModel('a', { bId: 'xxx', cId: 'xxx' }, include: null) describe 'include', -> it 'includes subEntities', -> class Main extends ValueObject @properties: name: @TYPES.STRING sub: @TYPES.MODEL 'sub-item', 'subId' class SubItem extends Entity @properties: name: @TYPES.STRING class SubItemRepository extends BaseAsyncRepository @modelName: 'sub-item' get: (id) -> item = @facade.createModel('sub-item', {id: id, name: '<NAME>'}) return Promise.resolve item f = require('../create-facade').create() f.addClass('main', Main) f.addClass('sub-item', SubItem) f.addClass('sub-item-repository', SubItemRepository) main = f.createModel 'main', name: '<NAME>' subId: 'abc' main.include().then => assert main.sub instanceof f.getModel 'sub-item'
true
Facade = require '../base-domain' { ValueObject, Entity, BaseAsyncRepository, BaseSyncRepository } = Facade { MemoryResource, Includer } = require '../others' describe 'Includer', -> before -> @facade = require('../create-facade').create() class A extends ValueObject @properties: b: @TYPES.MODEL 'b' c: @TYPES.MODEL 'c' class B extends Entity @properties: c: @TYPES.MODEL 'c' name: @TYPES.STRING class BRepository extends BaseAsyncRepository client: new MemoryResource() class CRepository extends BaseSyncRepository client: new MemoryResource() class C extends Entity @properties: name: @TYPES.STRING @facade.addClass('a', A) @facade.addClass('b', B) @facade.addClass('c', C) @facade.addClass('b-repository', BRepository) @facade.addClass('c-repository', CRepository) bRepo = @facade.createRepository('b') cRepo = @facade.createRepository('c') cRepo.save(id: 'xxx', name: 'PI:NAME:<NAME>END_PI') cRepo.save(id: 'yyy', name: 'PI:NAME:<NAME>END_PI') Promise.all([ bRepo.save(id: 'xxx', name: 'PI:NAME:<NAME>END_PI', cId: 'xxx') bRepo.save(id: 'yyy', name: 'PI:NAME:<NAME>END_PI', cId: 'yyy') ]) beforeEach -> @a = @facade.createModel('a', { bId: 'xxx', cId: 'xxx' }, include: null) describe 'include', -> it 'includes subEntities', -> class Main extends ValueObject @properties: name: @TYPES.STRING sub: @TYPES.MODEL 'sub-item', 'subId' class SubItem extends Entity @properties: name: @TYPES.STRING class SubItemRepository extends BaseAsyncRepository @modelName: 'sub-item' get: (id) -> item = @facade.createModel('sub-item', {id: id, name: 'PI:NAME:<NAME>END_PI'}) return Promise.resolve item f = require('../create-facade').create() f.addClass('main', Main) f.addClass('sub-item', SubItem) f.addClass('sub-item-repository', SubItemRepository) main = f.createModel 'main', name: 'PI:NAME:<NAME>END_PI' subId: 'abc' main.include().then => assert main.sub instanceof f.getModel 'sub-item'
[ { "context": " # source: http://www.flickr.com/photos/virgomerry/315412804/\n # also see: http://www.flick", "end": 15213, "score": 0.9996131062507629, "start": 15203, "tag": "USERNAME", "value": "virgomerry" }, { "context": " # also see: http://www.flickr....
apps/smartgraphs/activity_json/gravity.coffee
concord-consortium/Smartgraphs
0
Smartgraphs.activityDocs ||= {} Smartgraphs.activityDocs["/shared/gravity"] = _id: "gravity.df6" _rev: 1 data_format_version: 6 activity: title: "Was Galileo Right?" url: "/shared/gravity" owner: "shared" pages: [ "/shared/gravity/page/1" "/shared/gravity/page/2" "/shared/gravity/page/3" "/shared/gravity/page/4" "/shared/gravity/page/5" "/shared/gravity/page/6" "/shared/gravity/page/7" "/shared/gravity/page/8" "/shared/gravity/page/9" "/shared/gravity/page/10" "/shared/gravity/page/11" "/shared/gravity/page/12" "/shared/gravity/page/13" "/shared/gravity/page/14" ] pages: [ { name: "Introduction" url: "/shared/gravity/page/1" activity: "/shared/gravity" index: 1 introText: ''' <h1>Introduction</h1> <p>In the 1600s, Galileo Galilei (1564-1642) hypothesized that objects of different masses would fall at the same rate when they were dropped from the same height and allowed to fall freely. According to legend, Galileo dropped an iron cannon ball and a wooden ball from the Leaning Tower of Pisa to test his hypothesis.</p> ''' steps: [ "/shared/gravity/page/1/step/1" ] firstStep: "/shared/gravity/page/1/step/1" } { name: "Predict the Graphs (Light Ball)" url: "/shared/gravity/page/2" activity: "/shared/gravity" index: 2 introText: ''' <h1>Predict the Graphs (Light Ball)</h1> <p>To test Galileo’s hypothesis, you are going to examine data collected when same-sized balls of different masses were dropped from a fixed height.</p> <p>To help you predict the motions, find a light ball and heavy ball that are the same size. (The heavy ball should be at least five times heavier than the light ball.)</p> ''' steps: [ "/shared/gravity/page/2/step/1" "/shared/gravity/page/2/step/2" "/shared/gravity/page/2/step/3" ] firstStep: "/shared/gravity/page/2/step/1" } { name: "Look at the Data (Light Ball)" url: "/shared/gravity/page/3" activity: "/shared/gravity" index: 3 introText: ''' <h1>Look at the Data (Light Ball)</h1> <p>The data to the right was collected when a light softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/3/step/1" ] firstStep: "/shared/gravity/page/3/step/1" } { name: "Reflect on Predictions (Light Ball)" url: "/shared/gravity/page/4" activity: "/shared/gravity" index: 4 introText: ''' <h1>Reflect on Predictions (Light Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the light ball.</p> ''' steps: [ "/shared/gravity/page/4/step/1" ] firstStep: "/shared/gravity/page/4/step/1" } { name: "Predict the Graphs (Heavy Ball)" url: "/shared/gravity/page/5" activity: "/shared/gravity" index: 5 introText: ''' <h1>Predict the Graphs (Heavy Ball)</h1> ''' steps: [ "/shared/gravity/page/5/step/1" "/shared/gravity/page/5/step/2" ] firstStep: "/shared/gravity/page/5/step/1" } { name: "Look at the Data (Heavy Ball)" url: "/shared/gravity/page/6" activity: "/shared/gravity" index: 6 introText: ''' <h1>Look at the Data (Heavy Ball)</h1> <p>The data to the right was collected when a heavier softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/6/step/1" ] firstStep: "/shared/gravity/page/6/step/1" } { name: "Reflect on Prediction (Heavy Ball)" url: "/shared/gravity/page/7" activity: "/shared/gravity" index: 7 introText: ''' <h1>Reflect on Prediction (Heavy Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the heavy ball.</p> ''' steps: [ "/shared/gravity/page/7/step/1" ] firstStep: "/shared/gravity/page/7/step/1" } { name: "Compare the Data" url: "/shared/gravity/page/8" activity: "/shared/gravity" index: 8 introText: ''' <h1>Compare the Data I</h1> <p>Look at the actual data for the light ball and the heavy ball.</p> ''' steps: [ "/shared/gravity/page/8/step/1" "/shared/gravity/page/8/step/2" ] firstStep: "/shared/gravity/page/8/step/1" } { name: "Identify the Interval (Light Ball)" url: "/shared/gravity/page/9" activity: "/shared/gravity" index: 9 introText: ''' <h1>Identify the Interval (Light Ball)</h1> <p>To the right is the actual velocity-time data for the light ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/9/step/p1" "/shared/gravity/page/9/step/p1-incorrect-left" "/shared/gravity/page/9/step/p1-incorrect-right" "/shared/gravity/page/9/step/p2" "/shared/gravity/page/9/step/p2-incorrect-left" "/shared/gravity/page/9/step/p2-incorrect-right" "/shared/gravity/page/9/step/done" ] firstStep: "/shared/gravity/page/9/step/p1" } { name: "Find the Slope (Light Ball)" url: "/shared/gravity/page/10" activity: "/shared/gravity" index: 10 introText: ''' <h1>Find the Slope (Light Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/10/step/p1" "/shared/gravity/page/10/step/p1-incorrect" "/shared/gravity/page/10/step/p2" "/shared/gravity/page/10/step/p2-incorrect" "/shared/gravity/page/10/step/p2-same-as-p1" "/shared/gravity/page/10/step/slope-initial" "/shared/gravity/page/10/step/slope-initial-hint" "/shared/gravity/page/10/step/velocity" "/shared/gravity/page/10/step/velocity-hint" "/shared/gravity/page/10/step/velocity-giveaway" "/shared/gravity/page/10/step/time-velocity-incorrect" "/shared/gravity/page/10/step/time-velocity-correct" "/shared/gravity/page/10/step/time-hint" "/shared/gravity/page/10/step/time-giveaway" "/shared/gravity/page/10/step/slope-final-time-incorrect" "/shared/gravity/page/10/step/slope-final-time-correct" "/shared/gravity/page/10/step/slope-final-giveaway" "/shared/gravity/page/10/step/slope-correct" ] firstStep: "/shared/gravity/page/10/step/p1" } { name: "Identify the Interval (Heavy Ball)" url: "/shared/gravity/page/11" activity: "/shared/gravity" index: 11 introText: ''' <h1>Identify the Interval (Heavy Ball)</h1> <p>To the right is the actual velocity-time data for the heavy ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/11/step/p1" "/shared/gravity/page/11/step/p1-incorrect-left" "/shared/gravity/page/11/step/p1-incorrect-right" "/shared/gravity/page/11/step/p2" "/shared/gravity/page/11/step/p2-incorrect-left" "/shared/gravity/page/11/step/p2-incorrect-right" "/shared/gravity/page/11/step/done" ] firstStep: "/shared/gravity/page/11/step/p1" } { name: "Find the Slope (Heavy Ball)" url: "/shared/gravity/page/12" activity: "/shared/gravity" index: 12 introText: ''' <h1>Find the Slope (Heavy Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/12/step/p1" "/shared/gravity/page/12/step/p1-incorrect" "/shared/gravity/page/12/step/p2" "/shared/gravity/page/12/step/p2-incorrect" "/shared/gravity/page/12/step/p2-same-as-p1" "/shared/gravity/page/12/step/slope-initial" "/shared/gravity/page/12/step/slope-initial-hint" "/shared/gravity/page/12/step/velocity" "/shared/gravity/page/12/step/velocity-hint" "/shared/gravity/page/12/step/velocity-giveaway" "/shared/gravity/page/12/step/time-velocity-incorrect" "/shared/gravity/page/12/step/time-velocity-correct" "/shared/gravity/page/12/step/time-hint" "/shared/gravity/page/12/step/time-giveaway" "/shared/gravity/page/12/step/slope-final-time-incorrect" "/shared/gravity/page/12/step/slope-final-time-correct" "/shared/gravity/page/12/step/slope-final-giveaway" "/shared/gravity/page/12/step/slope-correct" ] firstStep: "/shared/gravity/page/12/step/p1" } { name: "Compare the Accelerations" url: "/shared/gravity/page/13" activity: "/shared/gravity" index: 13 introText: ''' <h1>Compare the Accelerations</h1> <p>The slope of a velocity-time graph is commonly called the acceleration. The acceleration of an object due to gravity is a constant, called <i>g</i>. The accepted value of <i>g</i> for objects near the surface of the Earth is 9.8 m/s<sup>2</sup>.<p> ''' steps: [ "/shared/gravity/page/13/step/1" "/shared/gravity/page/13/step/2" ] firstStep: "/shared/gravity/page/13/step/1" } { name: "Conclusion" url: "/shared/gravity/page/14" activity: "/shared/gravity" index: 14 introText: ''' <h1>Conclusion</h1> <p>Do heavier objects fall faster?</p> <p>In this activity, you predicted and confirmed whether a light ball would fall faster than a heavier ball, just as Galileo likely did.</p> <p>According to legend, Galileo observed that the two balls fell at the same rate. He explained that this phenomenon was due to the effects of gravity acting on the two balls in a similar way.</p> ''' steps: [ "/shared/gravity/page/14/step/1" "/shared/gravity/page/14/step/2" ] firstStep: "/shared/gravity/page/14/step/1" } ] steps: [ { url: "/shared/gravity/page/1/step/1" activityPage: "/shared/gravity/page/1" beforeText: ''' <p>Do heavier objects fall at the same rate as lighter objects?</p> <p>What do you think Galileo observed? Explain your reasoning.<p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ # also see: http://www.flickr.com/photos/virgomerry/315412603/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/2/step/1" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Try dropping each ball from a height of 2 meters.</p> <p>To the right, predict what you think the <b>position-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "light-ball-position" ] submissibilityDependsOn: ["annotation", "light-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-position"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/2" } { url: "/shared/gravity/page/2/step/2" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "light-ball-velocity" ] submissibilityDependsOn: ["annotation", "light-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-velocity"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/3" } { url: "/shared/gravity/page/2/step/3" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Describe how the ball’s motions are represented on your graphs. Try to use as many words from the word bank as possible.</p> <p><b>Word Bank</b>: ball, released, seconds, meters, position, velocity, increased, decreased, stayed the same, fast, slow, stopped, ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/3/step/1" activityPage: "/shared/gravity/page/3" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/4/step/1" activityPage: "/shared/gravity/page/4" beforeText: ''' <p>How does the actual data for the light ball differ from your predicted data?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: ["light-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/5/step/1" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>position-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "heavy-ball-position" ] submitButtonTitle: "OK" submissibilityDependsOn: ["annotation", "heavy-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-position"], 0.2] defaultBranch: "/shared/gravity/page/5/step/2" } { url: "/shared/gravity/page/5/step/2" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["heavy-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "heavy-ball-velocity" ] submissibilityDependsOn: ["annotation", "heavy-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-velocity"], 0.2] nextButtonShouldSubmit: true isFinalStep: true } { url: "/shared/gravity/page/6/step/1" activityPage: "/shared/gravity/page/6" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/7/step/1" activityPage: "/shared/gravity/page/7" beforeText: ''' <p>What happened to the ball's velocity as it approached the ground? Is this what you expected?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/8/step/1" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>How does the velocity-time graph of the light ball compare to the velocity-time graph of the heavy ball?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/8/step/2" } { url: "/shared/gravity/page/8/step/2" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>On each graph, click to label the point where the ball's velocity was fastest.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] tools: [ { name: "label" setup: pane: "top" labelName: "light-ball-label" } { name: "label" setup: pane: "bottom" labelName: "heavy-ball-label" } ] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/9/step/p1" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p2" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/done" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-motion-segment", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" } ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p1-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p2" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-same-as-p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/slope-initial" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "light-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-initial-hint" } { url: "/shared/gravity/page/10/step/slope-initial-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity" } { url: "/shared/gravity/page/10/step/velocity" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] highlightedAnnotations: ["light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-hint" } { url: "/shared/gravity/page/10/step/velocity-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] highlightedAnnotations: ["light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-giveaway" } { url: "/shared/gravity/page/10/step/velocity-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/time-velocity-incorrect" } { url: "/shared/gravity/page/10/step/time-velocity-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] highlightedAnnotations: ["light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-giveaway" } { url: "/shared/gravity/page/10/step/time-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/10/step/slope-final-time-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/slope-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/11/step/p1" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p2" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/done" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-motion-segment", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" } ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p1-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p2" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-same-as-p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/slope-initial" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "heavy-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-initial-hint" } { url: "/shared/gravity/page/12/step/slope-initial-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity" } { url: "/shared/gravity/page/12/step/velocity" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] highlightedAnnotations: ["heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-hint" } { url: "/shared/gravity/page/12/step/velocity-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] highlightedAnnotations: ["heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-giveaway" } { url: "/shared/gravity/page/12/step/velocity-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/time-velocity-incorrect" } { url: "/shared/gravity/page/12/step/time-velocity-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] highlightedAnnotations: ["heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-giveaway" } { url: "/shared/gravity/page/12/step/time-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/12/step/slope-final-time-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/slope-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/13/step/1" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>How does your value compare with the accepted value?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/13/step/2" } { url: "/shared/gravity/page/13/step/2" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>What factors might have caused errors in your measurements?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/14/step/1" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>What did you discover about the velocity of a light ball versus a heavy ball as each falls to the ground?</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/14/step/2" } { url: "/shared/gravity/page/14/step/2" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>This is the conclusion of the activity</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" isFinalStep: true hideSubmitButton: true } ] responseTemplates: [ { url: "/components/response-template/open" templateString: "" fieldTypes: ["textarea"] fieldChoicesList: [null] initialValues: [""] } { url: "/components/response-template/numeric" templateString: "" fieldTypes: ["numeric"] fieldChoicesList: [null] initialValues: [""] } ] axes: [ { url: "/shared/gravity/axes/time" units: "/builtins/units/seconds" min: 0 max: 1.0 nSteps: 10 label: "Time" } { url: "/shared/gravity/axes/position" units: "/builtins/units/meters" min: 0 max: 2.4 nSteps: 12 label: "Position" } { url: "/shared/gravity/axes/velocity" units: "/builtins/units/meters-per-second" min: -6 max: 2 nSteps: 8 label: "Velocity" } ] datadefs: [ { type: "UnorderedDataPoints" records: [ { url: "/shared/gravity/datadefs/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.867], [0.1,1.84], [0.15,1.84], [0.2,1.84], [0.25,1.84], [0.3,1.84], [0.35,1.84], [0.4,1.819], [0.45,1.745], [0.5,1.651], [0.55,1.531], [0.6,1.394], [0.65,1.229], [0.7,1.042], [0.75,.837], [0.8,.607], [0.85,.359]] } { url: "/shared/gravity/datadefs/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.83], [0.1,1.832], [0.15,1.829], [0.2,1.829], [0.25,1.829], [0.3,1.823], [0.35,1.815], [0.4,1.815], [0.45,1.761], [0.5,1.682], [0.55,1.58], [0.6,1.455], [0.65,1.312], [0.7,1.139], [0.75,.942], [0.8,.726], [0.85,.487], [0.9,.244]] } ] } { type: "FirstOrderDifference" records: [ { url: "/shared/gravity/datadefs/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/light-ball-position" windowLength: 4 } { url: "/shared/gravity/datadefs/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/heavy-ball-position" windowLength: 4 } ] } ] tags: [ { url: "/shared/gravity/tag/light-ball-point-1" activity: "/shared/gravity", name: "light-ball-point-1" } { url: "/shared/gravity/tag/light-ball-point-2" activity: "/shared/gravity", name: "light-ball-point-2" } { url: "/shared/gravity/tag/heavy-ball-point-1" activity: "/shared/gravity", name: "heavy-ball-point-1" } { url: "/shared/gravity/tag/heavy-ball-point-2" activity: "/shared/gravity", name: "heavy-ball-point-2" } ] annotations: [ { type: "HighlightedPoint", records: [ { url: "/shared/gravity/anotation/light-ball-point-1" name: "light-ball-point-1" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/light-ball-point-2" name: "light-ball-point-2" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-2" color: "#ff7f0e" } { url: "/shared/gravity/annotation/heavy-ball-point-1" name: "heavy-ball-point-1" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-point-2" name: "heavy-ball-point-2" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#ff7f0e" } ] } { type: "SegmentOverlay" records: [ { url: "/shared/gravity/annotation/light-ball-motion-segment" name: "light-ball-motion-segment" activity: "/shared/gravity" datadefName: "light-ball-velocity" x1Record: 0.45 x2Record: 0.85 } { url: "/shared/gravity/annotation/heavy-ball-motion-segment" name: "heavy-ball-motion-segment" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" x1Record: 0.45 x2Record: 0.9 } ] } { type: "LineThroughPoints" records: [ { url: "/shared/gravity/annotation/light-ball-slope-line" name: "light-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-slope-line" name: "heavy-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#1f77b4" } ] } { type: "RiseArrow" records: [ { url: "/shared/gravity/annotation/light-ball-rise-arrow" name: "light-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-arrow" name: "heavy-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunArrow" records: [ { url: "/shared/gravity/annotation/light-ball-run-arrow" name: "light-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-arrow" name: "heavy-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RiseBracket" records: [ { url: "/shared/gravity/annotation/light-ball-rise-bracket" name: "light-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-bracket" name: "heavy-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunBracket" records: [ { url: "/shared/gravity/annotation/light-ball-run-bracket" name: "light-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-bracket" name: "heavy-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "FreehandSketch" records: [ { url: "/shared/gravity/annotation/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } ] } { type: "Label" records: [ { url: "/shared/gravity/annotation/light-ball-label" name: "light-ball-label" activity: "/shared/gravity" text: "Fastest point" } { url: "/shared/gravity/annotation/heavy-ball-label" name: "heavy-ball-label" activity: "/shared/gravity" text: "Fastest point" } ] } ] variables: [] units: []
94565
Smartgraphs.activityDocs ||= {} Smartgraphs.activityDocs["/shared/gravity"] = _id: "gravity.df6" _rev: 1 data_format_version: 6 activity: title: "Was Galileo Right?" url: "/shared/gravity" owner: "shared" pages: [ "/shared/gravity/page/1" "/shared/gravity/page/2" "/shared/gravity/page/3" "/shared/gravity/page/4" "/shared/gravity/page/5" "/shared/gravity/page/6" "/shared/gravity/page/7" "/shared/gravity/page/8" "/shared/gravity/page/9" "/shared/gravity/page/10" "/shared/gravity/page/11" "/shared/gravity/page/12" "/shared/gravity/page/13" "/shared/gravity/page/14" ] pages: [ { name: "Introduction" url: "/shared/gravity/page/1" activity: "/shared/gravity" index: 1 introText: ''' <h1>Introduction</h1> <p>In the 1600s, Galileo Galilei (1564-1642) hypothesized that objects of different masses would fall at the same rate when they were dropped from the same height and allowed to fall freely. According to legend, Galileo dropped an iron cannon ball and a wooden ball from the Leaning Tower of Pisa to test his hypothesis.</p> ''' steps: [ "/shared/gravity/page/1/step/1" ] firstStep: "/shared/gravity/page/1/step/1" } { name: "Predict the Graphs (Light Ball)" url: "/shared/gravity/page/2" activity: "/shared/gravity" index: 2 introText: ''' <h1>Predict the Graphs (Light Ball)</h1> <p>To test Galileo’s hypothesis, you are going to examine data collected when same-sized balls of different masses were dropped from a fixed height.</p> <p>To help you predict the motions, find a light ball and heavy ball that are the same size. (The heavy ball should be at least five times heavier than the light ball.)</p> ''' steps: [ "/shared/gravity/page/2/step/1" "/shared/gravity/page/2/step/2" "/shared/gravity/page/2/step/3" ] firstStep: "/shared/gravity/page/2/step/1" } { name: "Look at the Data (Light Ball)" url: "/shared/gravity/page/3" activity: "/shared/gravity" index: 3 introText: ''' <h1>Look at the Data (Light Ball)</h1> <p>The data to the right was collected when a light softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/3/step/1" ] firstStep: "/shared/gravity/page/3/step/1" } { name: "Reflect on Predictions (Light Ball)" url: "/shared/gravity/page/4" activity: "/shared/gravity" index: 4 introText: ''' <h1>Reflect on Predictions (Light Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the light ball.</p> ''' steps: [ "/shared/gravity/page/4/step/1" ] firstStep: "/shared/gravity/page/4/step/1" } { name: "Predict the Graphs (Heavy Ball)" url: "/shared/gravity/page/5" activity: "/shared/gravity" index: 5 introText: ''' <h1>Predict the Graphs (Heavy Ball)</h1> ''' steps: [ "/shared/gravity/page/5/step/1" "/shared/gravity/page/5/step/2" ] firstStep: "/shared/gravity/page/5/step/1" } { name: "Look at the Data (Heavy Ball)" url: "/shared/gravity/page/6" activity: "/shared/gravity" index: 6 introText: ''' <h1>Look at the Data (Heavy Ball)</h1> <p>The data to the right was collected when a heavier softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/6/step/1" ] firstStep: "/shared/gravity/page/6/step/1" } { name: "Reflect on Prediction (Heavy Ball)" url: "/shared/gravity/page/7" activity: "/shared/gravity" index: 7 introText: ''' <h1>Reflect on Prediction (Heavy Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the heavy ball.</p> ''' steps: [ "/shared/gravity/page/7/step/1" ] firstStep: "/shared/gravity/page/7/step/1" } { name: "Compare the Data" url: "/shared/gravity/page/8" activity: "/shared/gravity" index: 8 introText: ''' <h1>Compare the Data I</h1> <p>Look at the actual data for the light ball and the heavy ball.</p> ''' steps: [ "/shared/gravity/page/8/step/1" "/shared/gravity/page/8/step/2" ] firstStep: "/shared/gravity/page/8/step/1" } { name: "Identify the Interval (Light Ball)" url: "/shared/gravity/page/9" activity: "/shared/gravity" index: 9 introText: ''' <h1>Identify the Interval (Light Ball)</h1> <p>To the right is the actual velocity-time data for the light ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/9/step/p1" "/shared/gravity/page/9/step/p1-incorrect-left" "/shared/gravity/page/9/step/p1-incorrect-right" "/shared/gravity/page/9/step/p2" "/shared/gravity/page/9/step/p2-incorrect-left" "/shared/gravity/page/9/step/p2-incorrect-right" "/shared/gravity/page/9/step/done" ] firstStep: "/shared/gravity/page/9/step/p1" } { name: "Find the Slope (Light Ball)" url: "/shared/gravity/page/10" activity: "/shared/gravity" index: 10 introText: ''' <h1>Find the Slope (Light Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/10/step/p1" "/shared/gravity/page/10/step/p1-incorrect" "/shared/gravity/page/10/step/p2" "/shared/gravity/page/10/step/p2-incorrect" "/shared/gravity/page/10/step/p2-same-as-p1" "/shared/gravity/page/10/step/slope-initial" "/shared/gravity/page/10/step/slope-initial-hint" "/shared/gravity/page/10/step/velocity" "/shared/gravity/page/10/step/velocity-hint" "/shared/gravity/page/10/step/velocity-giveaway" "/shared/gravity/page/10/step/time-velocity-incorrect" "/shared/gravity/page/10/step/time-velocity-correct" "/shared/gravity/page/10/step/time-hint" "/shared/gravity/page/10/step/time-giveaway" "/shared/gravity/page/10/step/slope-final-time-incorrect" "/shared/gravity/page/10/step/slope-final-time-correct" "/shared/gravity/page/10/step/slope-final-giveaway" "/shared/gravity/page/10/step/slope-correct" ] firstStep: "/shared/gravity/page/10/step/p1" } { name: "Identify the Interval (Heavy Ball)" url: "/shared/gravity/page/11" activity: "/shared/gravity" index: 11 introText: ''' <h1>Identify the Interval (Heavy Ball)</h1> <p>To the right is the actual velocity-time data for the heavy ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/11/step/p1" "/shared/gravity/page/11/step/p1-incorrect-left" "/shared/gravity/page/11/step/p1-incorrect-right" "/shared/gravity/page/11/step/p2" "/shared/gravity/page/11/step/p2-incorrect-left" "/shared/gravity/page/11/step/p2-incorrect-right" "/shared/gravity/page/11/step/done" ] firstStep: "/shared/gravity/page/11/step/p1" } { name: "Find the Slope (Heavy Ball)" url: "/shared/gravity/page/12" activity: "/shared/gravity" index: 12 introText: ''' <h1>Find the Slope (Heavy Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/12/step/p1" "/shared/gravity/page/12/step/p1-incorrect" "/shared/gravity/page/12/step/p2" "/shared/gravity/page/12/step/p2-incorrect" "/shared/gravity/page/12/step/p2-same-as-p1" "/shared/gravity/page/12/step/slope-initial" "/shared/gravity/page/12/step/slope-initial-hint" "/shared/gravity/page/12/step/velocity" "/shared/gravity/page/12/step/velocity-hint" "/shared/gravity/page/12/step/velocity-giveaway" "/shared/gravity/page/12/step/time-velocity-incorrect" "/shared/gravity/page/12/step/time-velocity-correct" "/shared/gravity/page/12/step/time-hint" "/shared/gravity/page/12/step/time-giveaway" "/shared/gravity/page/12/step/slope-final-time-incorrect" "/shared/gravity/page/12/step/slope-final-time-correct" "/shared/gravity/page/12/step/slope-final-giveaway" "/shared/gravity/page/12/step/slope-correct" ] firstStep: "/shared/gravity/page/12/step/p1" } { name: "Compare the Accelerations" url: "/shared/gravity/page/13" activity: "/shared/gravity" index: 13 introText: ''' <h1>Compare the Accelerations</h1> <p>The slope of a velocity-time graph is commonly called the acceleration. The acceleration of an object due to gravity is a constant, called <i>g</i>. The accepted value of <i>g</i> for objects near the surface of the Earth is 9.8 m/s<sup>2</sup>.<p> ''' steps: [ "/shared/gravity/page/13/step/1" "/shared/gravity/page/13/step/2" ] firstStep: "/shared/gravity/page/13/step/1" } { name: "Conclusion" url: "/shared/gravity/page/14" activity: "/shared/gravity" index: 14 introText: ''' <h1>Conclusion</h1> <p>Do heavier objects fall faster?</p> <p>In this activity, you predicted and confirmed whether a light ball would fall faster than a heavier ball, just as Galileo likely did.</p> <p>According to legend, Galileo observed that the two balls fell at the same rate. He explained that this phenomenon was due to the effects of gravity acting on the two balls in a similar way.</p> ''' steps: [ "/shared/gravity/page/14/step/1" "/shared/gravity/page/14/step/2" ] firstStep: "/shared/gravity/page/14/step/1" } ] steps: [ { url: "/shared/gravity/page/1/step/1" activityPage: "/shared/gravity/page/1" beforeText: ''' <p>Do heavier objects fall at the same rate as lighter objects?</p> <p>What do you think Galileo observed? Explain your reasoning.<p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ # also see: http://www.flickr.com/photos/virgomerry/315412603/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/2/step/1" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Try dropping each ball from a height of 2 meters.</p> <p>To the right, predict what you think the <b>position-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "light-ball-position" ] submissibilityDependsOn: ["annotation", "light-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-position"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/2" } { url: "/shared/gravity/page/2/step/2" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "light-ball-velocity" ] submissibilityDependsOn: ["annotation", "light-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-velocity"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/3" } { url: "/shared/gravity/page/2/step/3" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Describe how the ball’s motions are represented on your graphs. Try to use as many words from the word bank as possible.</p> <p><b>Word Bank</b>: ball, released, seconds, meters, position, velocity, increased, decreased, stayed the same, fast, slow, stopped, ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/3/step/1" activityPage: "/shared/gravity/page/3" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/4/step/1" activityPage: "/shared/gravity/page/4" beforeText: ''' <p>How does the actual data for the light ball differ from your predicted data?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: ["light-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/5/step/1" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>position-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "heavy-ball-position" ] submitButtonTitle: "OK" submissibilityDependsOn: ["annotation", "heavy-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-position"], 0.2] defaultBranch: "/shared/gravity/page/5/step/2" } { url: "/shared/gravity/page/5/step/2" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["heavy-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "heavy-ball-velocity" ] submissibilityDependsOn: ["annotation", "heavy-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-velocity"], 0.2] nextButtonShouldSubmit: true isFinalStep: true } { url: "/shared/gravity/page/6/step/1" activityPage: "/shared/gravity/page/6" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/7/step/1" activityPage: "/shared/gravity/page/7" beforeText: ''' <p>What happened to the ball's velocity as it approached the ground? Is this what you expected?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/8/step/1" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>How does the velocity-time graph of the light ball compare to the velocity-time graph of the heavy ball?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/8/step/2" } { url: "/shared/gravity/page/8/step/2" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>On each graph, click to label the point where the ball's velocity was fastest.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] tools: [ { name: "label" setup: pane: "top" labelName: "light-ball-label" } { name: "label" setup: pane: "bottom" labelName: "heavy-ball-label" } ] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/9/step/p1" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p2" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/done" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-motion-segment", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" } ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p1-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p2" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-same-as-p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/slope-initial" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "light-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-initial-hint" } { url: "/shared/gravity/page/10/step/slope-initial-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity" } { url: "/shared/gravity/page/10/step/velocity" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] highlightedAnnotations: ["light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-hint" } { url: "/shared/gravity/page/10/step/velocity-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] highlightedAnnotations: ["light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-giveaway" } { url: "/shared/gravity/page/10/step/velocity-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/time-velocity-incorrect" } { url: "/shared/gravity/page/10/step/time-velocity-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] highlightedAnnotations: ["light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-giveaway" } { url: "/shared/gravity/page/10/step/time-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/10/step/slope-final-time-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/slope-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/11/step/p1" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p2" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/done" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-motion-segment", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" } ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p1-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p2" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-same-as-p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/slope-initial" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "heavy-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-initial-hint" } { url: "/shared/gravity/page/12/step/slope-initial-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity" } { url: "/shared/gravity/page/12/step/velocity" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] highlightedAnnotations: ["heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-hint" } { url: "/shared/gravity/page/12/step/velocity-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] highlightedAnnotations: ["heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-giveaway" } { url: "/shared/gravity/page/12/step/velocity-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/time-velocity-incorrect" } { url: "/shared/gravity/page/12/step/time-velocity-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] highlightedAnnotations: ["heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-giveaway" } { url: "/shared/gravity/page/12/step/time-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/12/step/slope-final-time-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/slope-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/13/step/1" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>How does your value compare with the accepted value?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/13/step/2" } { url: "/shared/gravity/page/13/step/2" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>What factors might have caused errors in your measurements?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/14/step/1" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>What did you discover about the velocity of a light ball versus a heavy ball as each falls to the ground?</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **<NAME>ary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/14/step/2" } { url: "/shared/gravity/page/14/step/2" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>This is the conclusion of the activity</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" isFinalStep: true hideSubmitButton: true } ] responseTemplates: [ { url: "/components/response-template/open" templateString: "" fieldTypes: ["textarea"] fieldChoicesList: [null] initialValues: [""] } { url: "/components/response-template/numeric" templateString: "" fieldTypes: ["numeric"] fieldChoicesList: [null] initialValues: [""] } ] axes: [ { url: "/shared/gravity/axes/time" units: "/builtins/units/seconds" min: 0 max: 1.0 nSteps: 10 label: "Time" } { url: "/shared/gravity/axes/position" units: "/builtins/units/meters" min: 0 max: 2.4 nSteps: 12 label: "Position" } { url: "/shared/gravity/axes/velocity" units: "/builtins/units/meters-per-second" min: -6 max: 2 nSteps: 8 label: "Velocity" } ] datadefs: [ { type: "UnorderedDataPoints" records: [ { url: "/shared/gravity/datadefs/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.867], [0.1,1.84], [0.15,1.84], [0.2,1.84], [0.25,1.84], [0.3,1.84], [0.35,1.84], [0.4,1.819], [0.45,1.745], [0.5,1.651], [0.55,1.531], [0.6,1.394], [0.65,1.229], [0.7,1.042], [0.75,.837], [0.8,.607], [0.85,.359]] } { url: "/shared/gravity/datadefs/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.83], [0.1,1.832], [0.15,1.829], [0.2,1.829], [0.25,1.829], [0.3,1.823], [0.35,1.815], [0.4,1.815], [0.45,1.761], [0.5,1.682], [0.55,1.58], [0.6,1.455], [0.65,1.312], [0.7,1.139], [0.75,.942], [0.8,.726], [0.85,.487], [0.9,.244]] } ] } { type: "FirstOrderDifference" records: [ { url: "/shared/gravity/datadefs/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/light-ball-position" windowLength: 4 } { url: "/shared/gravity/datadefs/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/heavy-ball-position" windowLength: 4 } ] } ] tags: [ { url: "/shared/gravity/tag/light-ball-point-1" activity: "/shared/gravity", name: "light-ball-point-1" } { url: "/shared/gravity/tag/light-ball-point-2" activity: "/shared/gravity", name: "light-ball-point-2" } { url: "/shared/gravity/tag/heavy-ball-point-1" activity: "/shared/gravity", name: "heavy-ball-point-1" } { url: "/shared/gravity/tag/heavy-ball-point-2" activity: "/shared/gravity", name: "heavy-ball-point-2" } ] annotations: [ { type: "HighlightedPoint", records: [ { url: "/shared/gravity/anotation/light-ball-point-1" name: "light-ball-point-1" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/light-ball-point-2" name: "light-ball-point-2" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-2" color: "#ff7f0e" } { url: "/shared/gravity/annotation/heavy-ball-point-1" name: "heavy-ball-point-1" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-point-2" name: "heavy-ball-point-2" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#ff7f0e" } ] } { type: "SegmentOverlay" records: [ { url: "/shared/gravity/annotation/light-ball-motion-segment" name: "light-ball-motion-segment" activity: "/shared/gravity" datadefName: "light-ball-velocity" x1Record: 0.45 x2Record: 0.85 } { url: "/shared/gravity/annotation/heavy-ball-motion-segment" name: "heavy-ball-motion-segment" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" x1Record: 0.45 x2Record: 0.9 } ] } { type: "LineThroughPoints" records: [ { url: "/shared/gravity/annotation/light-ball-slope-line" name: "light-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-slope-line" name: "heavy-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#1f77b4" } ] } { type: "RiseArrow" records: [ { url: "/shared/gravity/annotation/light-ball-rise-arrow" name: "light-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-arrow" name: "heavy-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunArrow" records: [ { url: "/shared/gravity/annotation/light-ball-run-arrow" name: "light-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-arrow" name: "heavy-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RiseBracket" records: [ { url: "/shared/gravity/annotation/light-ball-rise-bracket" name: "light-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-bracket" name: "heavy-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunBracket" records: [ { url: "/shared/gravity/annotation/light-ball-run-bracket" name: "light-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-bracket" name: "heavy-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "FreehandSketch" records: [ { url: "/shared/gravity/annotation/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } ] } { type: "Label" records: [ { url: "/shared/gravity/annotation/light-ball-label" name: "light-ball-label" activity: "/shared/gravity" text: "Fastest point" } { url: "/shared/gravity/annotation/heavy-ball-label" name: "heavy-ball-label" activity: "/shared/gravity" text: "Fastest point" } ] } ] variables: [] units: []
true
Smartgraphs.activityDocs ||= {} Smartgraphs.activityDocs["/shared/gravity"] = _id: "gravity.df6" _rev: 1 data_format_version: 6 activity: title: "Was Galileo Right?" url: "/shared/gravity" owner: "shared" pages: [ "/shared/gravity/page/1" "/shared/gravity/page/2" "/shared/gravity/page/3" "/shared/gravity/page/4" "/shared/gravity/page/5" "/shared/gravity/page/6" "/shared/gravity/page/7" "/shared/gravity/page/8" "/shared/gravity/page/9" "/shared/gravity/page/10" "/shared/gravity/page/11" "/shared/gravity/page/12" "/shared/gravity/page/13" "/shared/gravity/page/14" ] pages: [ { name: "Introduction" url: "/shared/gravity/page/1" activity: "/shared/gravity" index: 1 introText: ''' <h1>Introduction</h1> <p>In the 1600s, Galileo Galilei (1564-1642) hypothesized that objects of different masses would fall at the same rate when they were dropped from the same height and allowed to fall freely. According to legend, Galileo dropped an iron cannon ball and a wooden ball from the Leaning Tower of Pisa to test his hypothesis.</p> ''' steps: [ "/shared/gravity/page/1/step/1" ] firstStep: "/shared/gravity/page/1/step/1" } { name: "Predict the Graphs (Light Ball)" url: "/shared/gravity/page/2" activity: "/shared/gravity" index: 2 introText: ''' <h1>Predict the Graphs (Light Ball)</h1> <p>To test Galileo’s hypothesis, you are going to examine data collected when same-sized balls of different masses were dropped from a fixed height.</p> <p>To help you predict the motions, find a light ball and heavy ball that are the same size. (The heavy ball should be at least five times heavier than the light ball.)</p> ''' steps: [ "/shared/gravity/page/2/step/1" "/shared/gravity/page/2/step/2" "/shared/gravity/page/2/step/3" ] firstStep: "/shared/gravity/page/2/step/1" } { name: "Look at the Data (Light Ball)" url: "/shared/gravity/page/3" activity: "/shared/gravity" index: 3 introText: ''' <h1>Look at the Data (Light Ball)</h1> <p>The data to the right was collected when a light softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/3/step/1" ] firstStep: "/shared/gravity/page/3/step/1" } { name: "Reflect on Predictions (Light Ball)" url: "/shared/gravity/page/4" activity: "/shared/gravity" index: 4 introText: ''' <h1>Reflect on Predictions (Light Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the light ball.</p> ''' steps: [ "/shared/gravity/page/4/step/1" ] firstStep: "/shared/gravity/page/4/step/1" } { name: "Predict the Graphs (Heavy Ball)" url: "/shared/gravity/page/5" activity: "/shared/gravity" index: 5 introText: ''' <h1>Predict the Graphs (Heavy Ball)</h1> ''' steps: [ "/shared/gravity/page/5/step/1" "/shared/gravity/page/5/step/2" ] firstStep: "/shared/gravity/page/5/step/1" } { name: "Look at the Data (Heavy Ball)" url: "/shared/gravity/page/6" activity: "/shared/gravity" index: 6 introText: ''' <h1>Look at the Data (Heavy Ball)</h1> <p>The data to the right was collected when a heavier softball was dropped from a height of about 2 meters. Every second, 20 data samples were collected.</p> ''' steps: [ "/shared/gravity/page/6/step/1" ] firstStep: "/shared/gravity/page/6/step/1" } { name: "Reflect on Prediction (Heavy Ball)" url: "/shared/gravity/page/7" activity: "/shared/gravity" index: 7 introText: ''' <h1>Reflect on Prediction (Heavy Ball)</h1> <p>To the right is your predicted (red) and actual (blue) position-time and velocity-time data for the heavy ball.</p> ''' steps: [ "/shared/gravity/page/7/step/1" ] firstStep: "/shared/gravity/page/7/step/1" } { name: "Compare the Data" url: "/shared/gravity/page/8" activity: "/shared/gravity" index: 8 introText: ''' <h1>Compare the Data I</h1> <p>Look at the actual data for the light ball and the heavy ball.</p> ''' steps: [ "/shared/gravity/page/8/step/1" "/shared/gravity/page/8/step/2" ] firstStep: "/shared/gravity/page/8/step/1" } { name: "Identify the Interval (Light Ball)" url: "/shared/gravity/page/9" activity: "/shared/gravity" index: 9 introText: ''' <h1>Identify the Interval (Light Ball)</h1> <p>To the right is the actual velocity-time data for the light ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/9/step/p1" "/shared/gravity/page/9/step/p1-incorrect-left" "/shared/gravity/page/9/step/p1-incorrect-right" "/shared/gravity/page/9/step/p2" "/shared/gravity/page/9/step/p2-incorrect-left" "/shared/gravity/page/9/step/p2-incorrect-right" "/shared/gravity/page/9/step/done" ] firstStep: "/shared/gravity/page/9/step/p1" } { name: "Find the Slope (Light Ball)" url: "/shared/gravity/page/10" activity: "/shared/gravity" index: 10 introText: ''' <h1>Find the Slope (Light Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "light-ball-point-1", "light-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/10/step/p1" "/shared/gravity/page/10/step/p1-incorrect" "/shared/gravity/page/10/step/p2" "/shared/gravity/page/10/step/p2-incorrect" "/shared/gravity/page/10/step/p2-same-as-p1" "/shared/gravity/page/10/step/slope-initial" "/shared/gravity/page/10/step/slope-initial-hint" "/shared/gravity/page/10/step/velocity" "/shared/gravity/page/10/step/velocity-hint" "/shared/gravity/page/10/step/velocity-giveaway" "/shared/gravity/page/10/step/time-velocity-incorrect" "/shared/gravity/page/10/step/time-velocity-correct" "/shared/gravity/page/10/step/time-hint" "/shared/gravity/page/10/step/time-giveaway" "/shared/gravity/page/10/step/slope-final-time-incorrect" "/shared/gravity/page/10/step/slope-final-time-correct" "/shared/gravity/page/10/step/slope-final-giveaway" "/shared/gravity/page/10/step/slope-correct" ] firstStep: "/shared/gravity/page/10/step/p1" } { name: "Identify the Interval (Heavy Ball)" url: "/shared/gravity/page/11" activity: "/shared/gravity" index: 11 introText: ''' <h1>Identify the Interval (Heavy Ball)</h1> <p>To the right is the actual velocity-time data for the heavy ball. You will identify the interval where the ball was falling.</p> ''' steps: [ "/shared/gravity/page/11/step/p1" "/shared/gravity/page/11/step/p1-incorrect-left" "/shared/gravity/page/11/step/p1-incorrect-right" "/shared/gravity/page/11/step/p2" "/shared/gravity/page/11/step/p2-incorrect-left" "/shared/gravity/page/11/step/p2-incorrect-right" "/shared/gravity/page/11/step/done" ] firstStep: "/shared/gravity/page/11/step/p1" } { name: "Find the Slope (Heavy Ball)" url: "/shared/gravity/page/12" activity: "/shared/gravity" index: 12 introText: ''' <h1>Find the Slope (Heavy Ball)</h1> <p>The slope of a velocity-time graph tells us how the velocity of an object changed over time.</p> <p>You are going to find the slope of a line that you think best represents the data when the ball was falling.</p> ''' contextVars: [ { name: "initial-velocity", value: ["coord", "y", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-velocity-as-string", value: ["toFixedString", ["get", "initial-velocity"], 2] } { name: "final-velocity", value: ["coord", "y", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-velocity-as-string", value: ["toFixedString", ["get", "final-velocity"], 2] } { name: "delta-velocity", value: ["-", ["get", "final-velocity"], ["get", "initial-velocity"]] } { name: "delta-velocity-as-string", value: ["toFixedString", ["get", "delta-velocity"], 2] } { name: "initial-time", value: ["coord", "x", ["listItem", 1, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "initial-time-as-string", value: ["toFixedString", ["get", "initial-time"], 2] } { name: "final-time", value: ["coord", "x", ["listItem", 2, ["slopeToolOrder", "heavy-ball-point-1", "heavy-ball-point-2"]]] } { name: "final-time-as-string", value: ["toFixedString", ["get", "final-time"], 2] } { name: "delta-time", value: ["-", ["get", "final-time"], ["get", "initial-time"]] } { name: "delta-time-as-string", value: ["toFixedString", ["get", "delta-time"], 2] } { name: "slope", value: ["/", ["get", "delta-velocity"], ["get", "delta-time"]] } { name: "slope-as-string", value: ["toFixedString", ["get", "slope"], 2] } ] steps: [ "/shared/gravity/page/12/step/p1" "/shared/gravity/page/12/step/p1-incorrect" "/shared/gravity/page/12/step/p2" "/shared/gravity/page/12/step/p2-incorrect" "/shared/gravity/page/12/step/p2-same-as-p1" "/shared/gravity/page/12/step/slope-initial" "/shared/gravity/page/12/step/slope-initial-hint" "/shared/gravity/page/12/step/velocity" "/shared/gravity/page/12/step/velocity-hint" "/shared/gravity/page/12/step/velocity-giveaway" "/shared/gravity/page/12/step/time-velocity-incorrect" "/shared/gravity/page/12/step/time-velocity-correct" "/shared/gravity/page/12/step/time-hint" "/shared/gravity/page/12/step/time-giveaway" "/shared/gravity/page/12/step/slope-final-time-incorrect" "/shared/gravity/page/12/step/slope-final-time-correct" "/shared/gravity/page/12/step/slope-final-giveaway" "/shared/gravity/page/12/step/slope-correct" ] firstStep: "/shared/gravity/page/12/step/p1" } { name: "Compare the Accelerations" url: "/shared/gravity/page/13" activity: "/shared/gravity" index: 13 introText: ''' <h1>Compare the Accelerations</h1> <p>The slope of a velocity-time graph is commonly called the acceleration. The acceleration of an object due to gravity is a constant, called <i>g</i>. The accepted value of <i>g</i> for objects near the surface of the Earth is 9.8 m/s<sup>2</sup>.<p> ''' steps: [ "/shared/gravity/page/13/step/1" "/shared/gravity/page/13/step/2" ] firstStep: "/shared/gravity/page/13/step/1" } { name: "Conclusion" url: "/shared/gravity/page/14" activity: "/shared/gravity" index: 14 introText: ''' <h1>Conclusion</h1> <p>Do heavier objects fall faster?</p> <p>In this activity, you predicted and confirmed whether a light ball would fall faster than a heavier ball, just as Galileo likely did.</p> <p>According to legend, Galileo observed that the two balls fell at the same rate. He explained that this phenomenon was due to the effects of gravity acting on the two balls in a similar way.</p> ''' steps: [ "/shared/gravity/page/14/step/1" "/shared/gravity/page/14/step/2" ] firstStep: "/shared/gravity/page/14/step/1" } ] steps: [ { url: "/shared/gravity/page/1/step/1" activityPage: "/shared/gravity/page/1" beforeText: ''' <p>Do heavier objects fall at the same rate as lighter objects?</p> <p>What do you think Galileo observed? Explain your reasoning.<p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ # also see: http://www.flickr.com/photos/virgomerry/315412603/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/2/step/1" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Try dropping each ball from a height of 2 meters.</p> <p>To the right, predict what you think the <b>position-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "light-ball-position" ] submissibilityDependsOn: ["annotation", "light-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-position"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/2" } { url: "/shared/gravity/page/2/step/2" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph for the light ball will look like.</p> <p>(Assume that the ground is at 0 meters.)</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "light-ball-velocity" ] submissibilityDependsOn: ["annotation", "light-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "light-ball-velocity"], 0.2] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/2/step/3" } { url: "/shared/gravity/page/2/step/3" activityPage: "/shared/gravity/page/2" beforeText: ''' <p>Describe how the ball’s motions are represented on your graphs. Try to use as many words from the word bank as possible.</p> <p><b>Word Bank</b>: ball, released, seconds, meters, position, velocity, increased, decreased, stayed the same, fast, slow, stopped, ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["light-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/3/step/1" activityPage: "/shared/gravity/page/3" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/4/step/1" activityPage: "/shared/gravity/page/4" beforeText: ''' <p>How does the actual data for the light ball differ from your predicted data?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["light-ball-position"] annotations: ["light-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/5/step/1" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>position-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: [] tools: [ name: "prediction" setup: pane: "top" uiBehavior: "freehand" annotationName: "heavy-ball-position" ] submitButtonTitle: "OK" submissibilityDependsOn: ["annotation", "heavy-ball-position"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-position"], 0.2] defaultBranch: "/shared/gravity/page/5/step/2" } { url: "/shared/gravity/page/5/step/2" activityPage: "/shared/gravity/page/5" beforeText: ''' <p>To the right, predict what you think the <b>velocity-time</b> graph will look like when the heavy ball is dropped from the same height.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Predicted Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: [] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Predicted Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: [] annotations: ["heavy-ball-velocity"] tools: [ name: "prediction" setup: pane: "bottom" uiBehavior: "freehand" annotationName: "heavy-ball-velocity" ] submissibilityDependsOn: ["annotation", "heavy-ball-velocity"] submissibilityCriterion: [">=", ["sketchLength", "heavy-ball-velocity"], 0.2] nextButtonShouldSubmit: true isFinalStep: true } { url: "/shared/gravity/page/6/step/1" activityPage: "/shared/gravity/page/6" beforeText: ''' ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] hideSubmitButton: true isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/7/step/1" activityPage: "/shared/gravity/page/7" beforeText: ''' <p>What happened to the ball's velocity as it approached the ground? Is this what you expected?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Position vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/position" data: ["heavy-ball-position"] annotations: ["heavy-ball-position"] bottom: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-velocity"] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/8/step/1" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>How does the velocity-time graph of the light ball compare to the velocity-time graph of the heavy ball?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/8/step/2" } { url: "/shared/gravity/page/8/step/2" activityPage: "/shared/gravity/page/8" beforeText: ''' <p>On each graph, click to label the point where the ball's velocity was fastest.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] tools: [ { name: "label" setup: pane: "top" labelName: "light-ball-label" } { name: "label" setup: pane: "bottom" labelName: "heavy-ball-label" } ] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/9/step/p1" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p1-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p2" } { criterion: [">", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/9/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p1-incorrect-left" } { url: "/shared/gravity/page/9/step/p2" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-left" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/p2-incorrect-right" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], 0.85] step: "/shared/gravity/page/9/step/done" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/9/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/9/step/p2-incorrect-left" } { url: "/shared/gravity/page/9/step/done" activityPage: "/shared/gravity/page/9" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-label", "light-ball-motion-segment", "light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" } ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p1-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1"] tools: [ name: "tagging" setup: tag: "light-ball-point-1" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "light-ball-point-1"], 0.45] step: "/shared/gravity/page/10/step/p2" ] defaultBranch: "/shared/gravity/page/10/step/p1-incorrect" } { url: "/shared/gravity/page/10/step/p2" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.85 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/p2-same-as-p1" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-motion-segment"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] tools: [ name: "tagging" setup: tag: "light-ball-point-2" data: "light-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "light-ball-point-2"], ["coord", "x", "light-ball-point-1"]] step: "/shared/gravity/page/10/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "light-ball-point-2"], 0.45] step: "/shared/gravity/page/10/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/10/step/p2-incorrect" } { url: "/shared/gravity/page/10/step/slope-initial" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "light-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-initial-hint" } { url: "/shared/gravity/page/10/step/slope-initial-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity" } { url: "/shared/gravity/page/10/step/velocity" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line"] highlightedAnnotations: ["light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-hint" } { url: "/shared/gravity/page/10/step/velocity-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] highlightedAnnotations: ["light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/10/step/velocity-giveaway" } { url: "/shared/gravity/page/10/step/velocity-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/time-velocity-incorrect" } { url: "/shared/gravity/page/10/step/time-velocity-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow"] highlightedAnnotations: ["light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-hint" } { url: "/shared/gravity/page/10/step/time-hint" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket"] highlightedAnnotations: ["light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/10/step/time-giveaway" } { url: "/shared/gravity/page/10/step/time-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/10/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/10/step/slope-final-time-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/10/step/slope-correct" ] defaultBranch: "/shared/gravity/page/10/step/slope-final-giveaway" } { url: "/shared/gravity/page/10/step/slope-final-giveaway" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-slope-line", "light-ball-rise-arrow", "light-ball-run-arrow"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2", "light-ball-rise-bracket", "light-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/10/step/slope-correct" activityPage: "/shared/gravity/page/10" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] bottom: type: "table" data: ["light-ball-velocity"] annotations: ["light-ball-point-1", "light-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/11/step/p1" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. At this point, the ball's velocity was (approximately) 0. Therefore, the ball was not moving. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p1-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. This point does not represent the beginning of the ball's motion. Try again.</p> <p>Click the earliest point at which the ball was in motion.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p2" } { criterion: [">", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/11/step/p1-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p1-incorrect-left" } { url: "/shared/gravity/page/11/step/p2" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct!</p> <p>Now, click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-left" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball had not yet started to fall at this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/p2-incorrect-right" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Incorrect. The ball continued to move closer the ground after this point. Try again.</p> <p>Click the point that best represents the ball's velocity when it was closest to the ground.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], 0.9] step: "/shared/gravity/page/11/step/done" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/11/step/p2-incorrect-right" } ] defaultBranch: "/shared/gravity/page/11/step/p2-incorrect-left" } { url: "/shared/gravity/page/11/step/done" activityPage: "/shared/gravity/page/11" beforeText: ''' <p>Correct! Here is the interval defined by the points you selected. The ball was falling in this interval.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-label", "heavy-ball-motion-segment", "heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select a representative point in the highlighted interval. Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" } ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p1-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-1" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ criterion: [">=", ["coord", "x", "heavy-ball-point-1"], 0.45] step: "/shared/gravity/page/12/step/p2" ] defaultBranch: "/shared/gravity/page/12/step/p1-incorrect" } { url: "/shared/gravity/page/12/step/p2" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Select a point when the ball was falling (between 0.45 and 0.9 seconds). Then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/p2-same-as-p1" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The point you selected is the same as the first point you selected. You need two different points in order to calculate the slope of the line between them. Try again.</p> <p>Select another point in the highlighted interval and then click OK.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-motion-segment"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] tools: [ name: "tagging" setup: tag: "heavy-ball-point-2" data: "heavy-ball-velocity" ] hideSubmitButton: false submitButtonTitle: "OK" responseBranches: [ { criterion: ["=", ["coord", "x", "heavy-ball-point-2"], ["coord", "x", "heavy-ball-point-1"]] step: "/shared/gravity/page/12/step/p2-same-as-p1" } { criterion: [">=", ["coord", "x", "heavy-ball-point-2"], 0.45] step: "/shared/gravity/page/12/step/slope-initial" } ] defaultBranch: "/shared/gravity/page/12/step/p2-incorrect" } { url: "/shared/gravity/page/12/step/slope-initial" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>To the right, a line has been drawn between the points you selected.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" variableAssignments: [ name: "heavy-ball-slope-as-string" value: ["get", "slope-as-string"] ] responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-initial-hint" } { url: "/shared/gravity/page/12/step/slope-initial-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. Hint: Recall that the slope is the change in the velocity at the two points, divided by the change in the time.</p> <p>What is the slope of the line between the points you selected, in m/s<sup>2</sup>?</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity" } { url: "/shared/gravity/page/12/step/velocity" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line"] highlightedAnnotations: ["heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-hint" } { url: "/shared/gravity/page/12/step/velocity-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What was the change in the velocity of the ball, in m/s?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] highlightedAnnotations: ["heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-velocity"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/time-velocity-correct" ] defaultBranch: "/shared/gravity/page/12/step/velocity-giveaway" } { url: "/shared/gravity/page/12/step/velocity-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in the velocity of the ball was %@ m/s - %@ m/s, or %@ m/s</p> ''' substitutedExpressions: ["final-velocity-as-string", "initial-velocity-as-string", "delta-velocity-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/time-velocity-incorrect" } { url: "/shared/gravity/page/12/step/time-velocity-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-velocity-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow"] highlightedAnnotations: ["heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-hint" } { url: "/shared/gravity/page/12/step/time-hint" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. What is the change in time between the points you selected, in seconds?</p> <p>Hint: Look at the table and the graph.</p> ''' paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket"] highlightedAnnotations: ["heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "delta-time"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-final-time-correct" ] defaultBranch: "/shared/gravity/page/12/step/time-giveaway" } { url: "/shared/gravity/page/12/step/time-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. The change in time between the points is %@ s - %@ s, or %@ s.</p> ''' substitutedExpressions: ["final-time-as-string", "initial-time-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/12/step/slope-final-time-incorrect" } { url: "/shared/gravity/page/12/step/slope-final-time-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-time-incorrect" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>If the change in velocity is %@ m/s during a change in time of %@ s, then what is the slope of the velocity-time graph, in m/s<sup>2</sup>?</p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] responseTemplate: "/components/response-template/numeric" submissibilityCriterion: ["isNumeric", ["responseField", 1]] submitButtonTitle: "Check My Answer" responseBranches: [ criterion: ["withinAbsTolerance", ["get", "slope"], ["responseField", 1], 0.1] step: "/shared/gravity/page/12/step/slope-correct" ] defaultBranch: "/shared/gravity/page/12/step/slope-final-giveaway" } { url: "/shared/gravity/page/12/step/slope-final-giveaway" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Incorrect. If the change in velocity is %@ m/s during a change in time of %@ s, then the slope is %@ m/s<sup>2</sup></p> ''' substitutedExpressions: ["delta-velocity-as-string", "delta-time-as-string", "slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-slope-line", "heavy-ball-rise-arrow", "heavy-ball-run-arrow"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2", "heavy-ball-rise-bracket", "heavy-ball-run-bracket"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/12/step/slope-correct" activityPage: "/shared/gravity/page/12" beforeText: ''' <p>Correct! The slope of the velocity-time graph between the points you selected is %@ m/s<sup>2</sup>.</p> ''' substitutedExpressions: ["slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] bottom: type: "table" data: ["heavy-ball-velocity"] annotations: ["heavy-ball-point-1", "heavy-ball-point-2"] isFinalStep: true hideSubmitButton: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/13/step/1" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>How does your value compare with the accepted value?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/13/step/2" } { url: "/shared/gravity/page/13/step/2" activityPage: "/shared/gravity/page/13" beforeText: ''' <p>Here is the value of <i>g</i> that you found for the light ball: <b>%@ m/s<sup>2</sup></p></b> <p>Here is the value of <i>g</i> that you found for the heavy ball: <b>%@ m/s<sup>2</sup></p></b> <p>What factors might have caused errors in your measurements?</p> ''' substitutedExpressions: ["light-ball-slope-as-string", "heavy-ball-slope-as-string"] paneConfig: "split" panes: top: type: "graph" title: "Actual Velocity vs. Time (Light Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["light-ball-velocity"] annotations: [] bottom: type: "graph" title: "Actual Velocity vs. Time (Heavy Ball)" xAxis: "/shared/gravity/axes/time" yAxis: "/shared/gravity/axes/velocity" data: ["heavy-ball-velocity"] annotations: [] responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] isFinalStep: true nextButtonShouldSubmit: true } { url: "/shared/gravity/page/14/step/1" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>What did you discover about the velocity of a light ball versus a heavy ball as each falls to the ground?</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **PI:NAME:<NAME>END_PIary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" responseTemplate: "/components/response-template/open" submissibilityCriterion: ["textLengthIsAtLeast", 1, ["responseField", 1]] submitButtonTitle: "OK" defaultBranch: "/shared/gravity/page/14/step/2" } { url: "/shared/gravity/page/14/step/2" activityPage: "/shared/gravity/page/14" beforeText: ''' <p>This is the conclusion of the activity</p> ''' paneConfig: "single" panes: single: type: "image" # source: http://www.flickr.com/photos/virgomerry/315412804/ path: "/static/smartgraphs/en/current/source/resources/images/leaning-tower-of-pisa-wide.jpg" caption: "Creative Commons BY-NC-SA 2.0 photo courtesy flickr user **Mary** (<a href=\"http://www.flickr.com/photos/virgomerry/315412804/\">link</a>)" isFinalStep: true hideSubmitButton: true } ] responseTemplates: [ { url: "/components/response-template/open" templateString: "" fieldTypes: ["textarea"] fieldChoicesList: [null] initialValues: [""] } { url: "/components/response-template/numeric" templateString: "" fieldTypes: ["numeric"] fieldChoicesList: [null] initialValues: [""] } ] axes: [ { url: "/shared/gravity/axes/time" units: "/builtins/units/seconds" min: 0 max: 1.0 nSteps: 10 label: "Time" } { url: "/shared/gravity/axes/position" units: "/builtins/units/meters" min: 0 max: 2.4 nSteps: 12 label: "Position" } { url: "/shared/gravity/axes/velocity" units: "/builtins/units/meters-per-second" min: -6 max: 2 nSteps: 8 label: "Velocity" } ] datadefs: [ { type: "UnorderedDataPoints" records: [ { url: "/shared/gravity/datadefs/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.867], [0.1,1.84], [0.15,1.84], [0.2,1.84], [0.25,1.84], [0.3,1.84], [0.35,1.84], [0.4,1.819], [0.45,1.745], [0.5,1.651], [0.55,1.531], [0.6,1.394], [0.65,1.229], [0.7,1.042], [0.75,.837], [0.8,.607], [0.85,.359]] } { url: "/shared/gravity/datadefs/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters" yLabel: "Position" yShortLabel: "Position" points: [[0.05,1.83], [0.1,1.832], [0.15,1.829], [0.2,1.829], [0.25,1.829], [0.3,1.823], [0.35,1.815], [0.4,1.815], [0.45,1.761], [0.5,1.682], [0.55,1.58], [0.6,1.455], [0.65,1.312], [0.7,1.139], [0.75,.942], [0.8,.726], [0.85,.487], [0.9,.244]] } ] } { type: "FirstOrderDifference" records: [ { url: "/shared/gravity/datadefs/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/light-ball-position" windowLength: 4 } { url: "/shared/gravity/datadefs/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" xUnits: "/builtins/units/seconds" xLabel: "Time" xShortLabel: "Time" yUnits: "/builtins/units/meters-per-second" yLabel: "Velocity" yShortLabel: "Vel" source: "/shared/gravity/datadefs/heavy-ball-position" windowLength: 4 } ] } ] tags: [ { url: "/shared/gravity/tag/light-ball-point-1" activity: "/shared/gravity", name: "light-ball-point-1" } { url: "/shared/gravity/tag/light-ball-point-2" activity: "/shared/gravity", name: "light-ball-point-2" } { url: "/shared/gravity/tag/heavy-ball-point-1" activity: "/shared/gravity", name: "heavy-ball-point-1" } { url: "/shared/gravity/tag/heavy-ball-point-2" activity: "/shared/gravity", name: "heavy-ball-point-2" } ] annotations: [ { type: "HighlightedPoint", records: [ { url: "/shared/gravity/anotation/light-ball-point-1" name: "light-ball-point-1" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/light-ball-point-2" name: "light-ball-point-2" activity: "/shared/gravity" datadefName: "light-ball-velocity" tag: "/shared/gravity/tag/light-ball-point-2" color: "#ff7f0e" } { url: "/shared/gravity/annotation/heavy-ball-point-1" name: "heavy-ball-point-1" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-1" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-point-2" name: "heavy-ball-point-2" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#ff7f0e" } ] } { type: "SegmentOverlay" records: [ { url: "/shared/gravity/annotation/light-ball-motion-segment" name: "light-ball-motion-segment" activity: "/shared/gravity" datadefName: "light-ball-velocity" x1Record: 0.45 x2Record: 0.85 } { url: "/shared/gravity/annotation/heavy-ball-motion-segment" name: "heavy-ball-motion-segment" activity: "/shared/gravity" datadefName: "heavy-ball-velocity" x1Record: 0.45 x2Record: 0.9 } ] } { type: "LineThroughPoints" records: [ { url: "/shared/gravity/annotation/light-ball-slope-line" name: "light-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" color: "#1f77b4" } { url: "/shared/gravity/annotation/heavy-ball-slope-line" name: "heavy-ball-slope-line" activity: "/shared/gravity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" color: "#1f77b4" } ] } { type: "RiseArrow" records: [ { url: "/shared/gravity/annotation/light-ball-rise-arrow" name: "light-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-arrow" name: "heavy-ball-rise-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunArrow" records: [ { url: "/shared/gravity/annotation/light-ball-run-arrow" name: "light-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-arrow" name: "heavy-ball-run-arrow" activity: "/shared/gravity" color: "#cccccc" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RiseBracket" records: [ { url: "/shared/gravity/annotation/light-ball-rise-bracket" name: "light-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-rise-bracket" name: "heavy-ball-rise-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "RunBracket" records: [ { url: "/shared/gravity/annotation/light-ball-run-bracket" name: "light-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "light-ball-velocity" p1Tag: "/shared/gravity/tag/light-ball-point-1" p2Tag: "/shared/gravity/tag/light-ball-point-2" } { url: "/shared/gravity/annotation/heavy-ball-run-bracket" name: "heavy-ball-run-bracket" activity: "/shared/gravity" color: "#cccccc" datadefName: "heavy-ball-velocity" p1Tag: "/shared/gravity/tag/heavy-ball-point-1" p2Tag: "/shared/gravity/tag/heavy-ball-point-2" } ] } { type: "FreehandSketch" records: [ { url: "/shared/gravity/annotation/light-ball-position" name: "light-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/light-ball-velocity" name: "light-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-position" name: "heavy-ball-position" activity: "/shared/gravity" color: "#CC0000" points: [] } { url: "/shared/gravity/annotation/heavy-ball-velocity" name: "heavy-ball-velocity" activity: "/shared/gravity" color: "#CC0000" points: [] } ] } { type: "Label" records: [ { url: "/shared/gravity/annotation/light-ball-label" name: "light-ball-label" activity: "/shared/gravity" text: "Fastest point" } { url: "/shared/gravity/annotation/heavy-ball-label" name: "heavy-ball-label" activity: "/shared/gravity" text: "Fastest point" } ] } ] variables: [] units: []
[ { "context": "\t\tdiscoverableServices.publishServices([ { name: 'Gopher', identifier: '_noweb._sub._gopher._udp', po", "end": 6442, "score": 0.6847783327102661, "start": 6441, "tag": "NAME", "value": "G" }, { "context": "length(1)\n\t\t\t\t\tgopher = _.find(services, { name: 'Gopher...
tests/discovery.spec.coffee
balena-io-modules/resin-discoverable-services
3
m = require('mochainon') _ = require('lodash') { expect } = m.chai { testServicePath, givenServiceRegistry } = require('./setup') { isAvailable: isAvahiAvailable } = require('../lib/backends/avahi') discoverableServices = require('../lib/discoverable') describe 'Discoverable Services:', -> testServices = [ { service: '_first._sub._ssh._tcp', opts: { name: 'First SSH', port: 1234, type: 'ssh', subtypes: [ 'first' ], protocol: 'tcp' } }, { service: '_second._sub._ssh._tcp', tags: [ 'second_ssh' ], opts: { name: 'Second SSH', port: 2345, type: 'ssh', subtypes: [ 'second' ], protocol: 'tcp' } }, { service: '_noweb._sub._gopher._udp' opts: { name: 'Gopher', port: 3456, type: 'gopher', subtypes: [ 'noweb' ], protocol: 'udp' } } ] givenServiceRegistry(testServices) inspectEnumeratedServices = (services) -> expect(services.length).to.equal(testServices.length) services.forEach (service) -> testService = _.find testServices, (test) -> return if test.service == service.service then true else false expect(service.service).to.equal(testService.service) if testService.tags? expect(service.tags).to.deep.equal(testService.tags) describe '.setRegistryPath()', -> describe 'given invalid parameters', -> it 'should reject them', -> expect(-> discoverableServices.setRegistryPath([])).to.throw('path parameter must be a path string') describe 'using the default path', -> serviceName = '_resin-device._sub._ssh._tcp' tagNames = [ 'resin-ssh' ] beforeEach -> discoverableServices.setRegistryPath(null) it '.enumerateServices() should retrieve the resin-device.ssh service', (done) -> discoverableServices.enumerateServices (error, services) -> services.forEach (service) -> expect(service.service).to.equal(serviceName) expect(service.tags).to.deep.equal(tagNames) done() return it '.enumerateServices() should return a promise that resolves to the registered services', -> promise = discoverableServices.enumerateServices() expect(promise).to.eventually.deep.equal([ { service: serviceName, tags: tagNames } ]) describe 'using a new registry path', -> before -> discoverableServices.setRegistryPath(testServicePath) it '.enumerateServices() should return a promise that enumerates all three valid services', -> discoverableServices.enumerateServices().return(inspectEnumeratedServices) describe '.enumerateServices()', -> describe 'using the test services registry path', -> it 'should return the registered services in a callback', (done) -> discoverableServices.enumerateServices (error, services) -> inspectEnumeratedServices(services) done() return it 'should return a promise that resolves to the registered services', -> discoverableServices.enumerateServices() .return (inspectEnumeratedServices) describe '.findServices()', -> before -> discoverableServices.setRegistryPath(testServicePath) services = testServices.map (service) -> identifier: service.service port: service.opts.port name: service.opts.name .concat # Include a new service that isn't in the registry. We should not # expect to see it. In this case, it's an encompassing SSH type. identifier: '_invalid._sub._ssh._tcp' port: 5678 name: 'Invalid SSH' discoverableServices.publishServices(services) after -> discoverableServices.unpublishServices() describe 'using invalid parameters', -> it '.enumerateServices() should throw an error with an service list', -> promise = discoverableServices.findServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service name strings') it '.enumerateServices() should throw an error with an invalid timeout', -> promise = discoverableServices.findServices([], 'spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'timeout parameter must be a number value in milliseconds') describe 'using a set of published services', -> this.timeout(10000) it 'should return only the gopher and second ssh service using default timeout as a promise', -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(2) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') it 'should return both first and second ssh services using default timeout via a callback', (done) -> discoverableServices.findServices [ '_first._sub._ssh._tcp', 'second_ssh' ], 6000, (error, services) -> expect(services).to.have.length(2) mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') # We didn't explicitly search for the private SSH services # so the subtype is empty and the service is just a vanilla # 'ssh' one. privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') done() return describe '.publishServices()', -> this.timeout(10000) before -> discoverableServices.setRegistryPath(testServicePath) describe 'using invalid parameters', -> it '.publishServices() should throw an error with an service list', -> promise = discoverableServices.publishServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service objects') describe 'using test services', -> it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: 'Gopher', identifier: '_noweb._sub._gopher._udp', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') .finally -> discoverableServices.unpublishServices() it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: 'Gopher', identifier: '_noweb._sub._gopher._udp', host: 'gopher.local', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') discoverableServices.unpublishServices() it 'should publish all services and find them', -> discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH' , port: 1234 } { identifier: 'second_ssh', name: 'Second SSH' , port: 2345 } { identifier: '_noweb._sub._gopher._udp', name: 'Gopher', host: 'gopher.local', port: 3456 } ] .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp', '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(3) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') .finally -> discoverableServices.unpublishServices() it 'should publish single service only to local IPv4 loopback interface', -> # This is a rough check, as by default every Darwin based platform # runs MDNS by default. It is assumed that every other platform (such as # Linux/FreeBSD/Windows) is *not* running a Bonjour based protocol. # If it is, this test will fail as it will not be able to bind to port 5354. if process.platform is 'darwin' return # This doesn't work with Avahi scans, as by default Avahi refuses to use the localhost interface isAvahiAvailable().then (hasAvahi) -> if not hasAvahi discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH', port: 1234 } ], { mdnsInterface: '127.0.0.1' } .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp' ]) .then (services) -> mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') expect(mainSsh.referer.address).to.equal('127.0.0.1') .finally -> discoverableServices.unpublishServices()
158098
m = require('mochainon') _ = require('lodash') { expect } = m.chai { testServicePath, givenServiceRegistry } = require('./setup') { isAvailable: isAvahiAvailable } = require('../lib/backends/avahi') discoverableServices = require('../lib/discoverable') describe 'Discoverable Services:', -> testServices = [ { service: '_first._sub._ssh._tcp', opts: { name: 'First SSH', port: 1234, type: 'ssh', subtypes: [ 'first' ], protocol: 'tcp' } }, { service: '_second._sub._ssh._tcp', tags: [ 'second_ssh' ], opts: { name: 'Second SSH', port: 2345, type: 'ssh', subtypes: [ 'second' ], protocol: 'tcp' } }, { service: '_noweb._sub._gopher._udp' opts: { name: 'Gopher', port: 3456, type: 'gopher', subtypes: [ 'noweb' ], protocol: 'udp' } } ] givenServiceRegistry(testServices) inspectEnumeratedServices = (services) -> expect(services.length).to.equal(testServices.length) services.forEach (service) -> testService = _.find testServices, (test) -> return if test.service == service.service then true else false expect(service.service).to.equal(testService.service) if testService.tags? expect(service.tags).to.deep.equal(testService.tags) describe '.setRegistryPath()', -> describe 'given invalid parameters', -> it 'should reject them', -> expect(-> discoverableServices.setRegistryPath([])).to.throw('path parameter must be a path string') describe 'using the default path', -> serviceName = '_resin-device._sub._ssh._tcp' tagNames = [ 'resin-ssh' ] beforeEach -> discoverableServices.setRegistryPath(null) it '.enumerateServices() should retrieve the resin-device.ssh service', (done) -> discoverableServices.enumerateServices (error, services) -> services.forEach (service) -> expect(service.service).to.equal(serviceName) expect(service.tags).to.deep.equal(tagNames) done() return it '.enumerateServices() should return a promise that resolves to the registered services', -> promise = discoverableServices.enumerateServices() expect(promise).to.eventually.deep.equal([ { service: serviceName, tags: tagNames } ]) describe 'using a new registry path', -> before -> discoverableServices.setRegistryPath(testServicePath) it '.enumerateServices() should return a promise that enumerates all three valid services', -> discoverableServices.enumerateServices().return(inspectEnumeratedServices) describe '.enumerateServices()', -> describe 'using the test services registry path', -> it 'should return the registered services in a callback', (done) -> discoverableServices.enumerateServices (error, services) -> inspectEnumeratedServices(services) done() return it 'should return a promise that resolves to the registered services', -> discoverableServices.enumerateServices() .return (inspectEnumeratedServices) describe '.findServices()', -> before -> discoverableServices.setRegistryPath(testServicePath) services = testServices.map (service) -> identifier: service.service port: service.opts.port name: service.opts.name .concat # Include a new service that isn't in the registry. We should not # expect to see it. In this case, it's an encompassing SSH type. identifier: '_invalid._sub._ssh._tcp' port: 5678 name: 'Invalid SSH' discoverableServices.publishServices(services) after -> discoverableServices.unpublishServices() describe 'using invalid parameters', -> it '.enumerateServices() should throw an error with an service list', -> promise = discoverableServices.findServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service name strings') it '.enumerateServices() should throw an error with an invalid timeout', -> promise = discoverableServices.findServices([], 'spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'timeout parameter must be a number value in milliseconds') describe 'using a set of published services', -> this.timeout(10000) it 'should return only the gopher and second ssh service using default timeout as a promise', -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(2) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') it 'should return both first and second ssh services using default timeout via a callback', (done) -> discoverableServices.findServices [ '_first._sub._ssh._tcp', 'second_ssh' ], 6000, (error, services) -> expect(services).to.have.length(2) mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') # We didn't explicitly search for the private SSH services # so the subtype is empty and the service is just a vanilla # 'ssh' one. privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') done() return describe '.publishServices()', -> this.timeout(10000) before -> discoverableServices.setRegistryPath(testServicePath) describe 'using invalid parameters', -> it '.publishServices() should throw an error with an service list', -> promise = discoverableServices.publishServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service objects') describe 'using test services', -> it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: '<NAME>opher', identifier: '_noweb._sub._gopher._udp', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: '<NAME>opher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') .finally -> discoverableServices.unpublishServices() it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: '<NAME>her', identifier: '_noweb._sub._gopher._udp', host: 'gopher.local', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: '<NAME>' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') discoverableServices.unpublishServices() it 'should publish all services and find them', -> discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH' , port: 1234 } { identifier: 'second_ssh', name: 'Second SSH' , port: 2345 } { identifier: '_noweb._sub._gopher._udp', name: '<NAME>', host: 'gopher.local', port: 3456 } ] .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp', '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(3) gopher = _.find(services, { name: '<NAME>' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') .finally -> discoverableServices.unpublishServices() it 'should publish single service only to local IPv4 loopback interface', -> # This is a rough check, as by default every Darwin based platform # runs MDNS by default. It is assumed that every other platform (such as # Linux/FreeBSD/Windows) is *not* running a Bonjour based protocol. # If it is, this test will fail as it will not be able to bind to port 5354. if process.platform is 'darwin' return # This doesn't work with Avahi scans, as by default Avahi refuses to use the localhost interface isAvahiAvailable().then (hasAvahi) -> if not hasAvahi discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH', port: 1234 } ], { mdnsInterface: '127.0.0.1' } .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp' ]) .then (services) -> mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') expect(mainSsh.referer.address).to.equal('127.0.0.1') .finally -> discoverableServices.unpublishServices()
true
m = require('mochainon') _ = require('lodash') { expect } = m.chai { testServicePath, givenServiceRegistry } = require('./setup') { isAvailable: isAvahiAvailable } = require('../lib/backends/avahi') discoverableServices = require('../lib/discoverable') describe 'Discoverable Services:', -> testServices = [ { service: '_first._sub._ssh._tcp', opts: { name: 'First SSH', port: 1234, type: 'ssh', subtypes: [ 'first' ], protocol: 'tcp' } }, { service: '_second._sub._ssh._tcp', tags: [ 'second_ssh' ], opts: { name: 'Second SSH', port: 2345, type: 'ssh', subtypes: [ 'second' ], protocol: 'tcp' } }, { service: '_noweb._sub._gopher._udp' opts: { name: 'Gopher', port: 3456, type: 'gopher', subtypes: [ 'noweb' ], protocol: 'udp' } } ] givenServiceRegistry(testServices) inspectEnumeratedServices = (services) -> expect(services.length).to.equal(testServices.length) services.forEach (service) -> testService = _.find testServices, (test) -> return if test.service == service.service then true else false expect(service.service).to.equal(testService.service) if testService.tags? expect(service.tags).to.deep.equal(testService.tags) describe '.setRegistryPath()', -> describe 'given invalid parameters', -> it 'should reject them', -> expect(-> discoverableServices.setRegistryPath([])).to.throw('path parameter must be a path string') describe 'using the default path', -> serviceName = '_resin-device._sub._ssh._tcp' tagNames = [ 'resin-ssh' ] beforeEach -> discoverableServices.setRegistryPath(null) it '.enumerateServices() should retrieve the resin-device.ssh service', (done) -> discoverableServices.enumerateServices (error, services) -> services.forEach (service) -> expect(service.service).to.equal(serviceName) expect(service.tags).to.deep.equal(tagNames) done() return it '.enumerateServices() should return a promise that resolves to the registered services', -> promise = discoverableServices.enumerateServices() expect(promise).to.eventually.deep.equal([ { service: serviceName, tags: tagNames } ]) describe 'using a new registry path', -> before -> discoverableServices.setRegistryPath(testServicePath) it '.enumerateServices() should return a promise that enumerates all three valid services', -> discoverableServices.enumerateServices().return(inspectEnumeratedServices) describe '.enumerateServices()', -> describe 'using the test services registry path', -> it 'should return the registered services in a callback', (done) -> discoverableServices.enumerateServices (error, services) -> inspectEnumeratedServices(services) done() return it 'should return a promise that resolves to the registered services', -> discoverableServices.enumerateServices() .return (inspectEnumeratedServices) describe '.findServices()', -> before -> discoverableServices.setRegistryPath(testServicePath) services = testServices.map (service) -> identifier: service.service port: service.opts.port name: service.opts.name .concat # Include a new service that isn't in the registry. We should not # expect to see it. In this case, it's an encompassing SSH type. identifier: '_invalid._sub._ssh._tcp' port: 5678 name: 'Invalid SSH' discoverableServices.publishServices(services) after -> discoverableServices.unpublishServices() describe 'using invalid parameters', -> it '.enumerateServices() should throw an error with an service list', -> promise = discoverableServices.findServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service name strings') it '.enumerateServices() should throw an error with an invalid timeout', -> promise = discoverableServices.findServices([], 'spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'timeout parameter must be a number value in milliseconds') describe 'using a set of published services', -> this.timeout(10000) it 'should return only the gopher and second ssh service using default timeout as a promise', -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(2) gopher = _.find(services, { name: 'Gopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') it 'should return both first and second ssh services using default timeout via a callback', (done) -> discoverableServices.findServices [ '_first._sub._ssh._tcp', 'second_ssh' ], 6000, (error, services) -> expect(services).to.have.length(2) mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') # We didn't explicitly search for the private SSH services # so the subtype is empty and the service is just a vanilla # 'ssh' one. privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') done() return describe '.publishServices()', -> this.timeout(10000) before -> discoverableServices.setRegistryPath(testServicePath) describe 'using invalid parameters', -> it '.publishServices() should throw an error with an service list', -> promise = discoverableServices.publishServices('spoon') expect(promise).to.eventually.be.rejectedWith(Error, 'services parameter must be an array of service objects') describe 'using test services', -> it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: 'PI:NAME:<NAME>END_PIopher', identifier: '_noweb._sub._gopher._udp', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: 'PI:NAME:<NAME>END_PIopher' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.protocol).to.equal('udp') .finally -> discoverableServices.unpublishServices() it 'should publish only the gopher service and find only it', -> discoverableServices.publishServices([ { name: 'PI:NAME:<NAME>END_PIher', identifier: '_noweb._sub._gopher._udp', host: 'gopher.local', port: 3456 } ]) .then -> discoverableServices.findServices([ '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(1) gopher = _.find(services, { name: 'PI:NAME:<NAME>END_PI' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') discoverableServices.unpublishServices() it 'should publish all services and find them', -> discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH' , port: 1234 } { identifier: 'second_ssh', name: 'Second SSH' , port: 2345 } { identifier: '_noweb._sub._gopher._udp', name: 'PI:NAME:<NAME>END_PI', host: 'gopher.local', port: 3456 } ] .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp', '_noweb._sub._gopher._udp', 'second_ssh' ]) .then (services) -> expect(services).to.have.length(3) gopher = _.find(services, { name: 'PI:NAME:<NAME>END_PI' }) expect(gopher.fqdn).to.equal('Gopher._gopher._udp.local') expect(gopher.subtypes).to.deep.equal([ 'noweb' ]) expect(gopher.port).to.equal(3456) expect(gopher.host).to.equal('gopher.local') expect(gopher.protocol).to.equal('udp') mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') privateSsh = _.find(services, { name: 'Second SSH' }) expect(privateSsh.fqdn).to.equal('Second SSH._ssh._tcp.local') expect(privateSsh.subtypes).to.deep.equal([ 'second' ]) expect(privateSsh.port).to.equal(2345) expect(privateSsh.protocol).to.equal('tcp') .finally -> discoverableServices.unpublishServices() it 'should publish single service only to local IPv4 loopback interface', -> # This is a rough check, as by default every Darwin based platform # runs MDNS by default. It is assumed that every other platform (such as # Linux/FreeBSD/Windows) is *not* running a Bonjour based protocol. # If it is, this test will fail as it will not be able to bind to port 5354. if process.platform is 'darwin' return # This doesn't work with Avahi scans, as by default Avahi refuses to use the localhost interface isAvahiAvailable().then (hasAvahi) -> if not hasAvahi discoverableServices.publishServices [ { identifier: '_first._sub._ssh._tcp', name: 'First SSH', port: 1234 } ], { mdnsInterface: '127.0.0.1' } .then -> discoverableServices.findServices([ '_first._sub._ssh._tcp' ]) .then (services) -> mainSsh = _.find(services, { name: 'First SSH' }) expect(mainSsh.fqdn).to.equal('First SSH._ssh._tcp.local') expect(mainSsh.subtypes).to.deep.equal([ 'first' ]) expect(mainSsh.port).to.equal(1234) expect(mainSsh.protocol).to.equal('tcp') expect(mainSsh.referer.address).to.equal('127.0.0.1') .finally -> discoverableServices.unpublishServices()
[ { "context": "get).css('background', \"url('/images/bridal_party/Michael.jpg') no-repeat\")\n $(e.target).css('backgr", "end": 1659, "score": 0.8248655796051025, "start": 1652, "tag": "NAME", "value": "Michael" }, { "context": "\\-\\w+\\.jpg/.exec(image)[0]\n\n michael1Rege...
source/javascripts/script.js.coffee
waysidekoi/richandkristen
0
$ -> $('.girls').on 'click', 'dd', (e)-> $('.girls').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.boys').on 'click', 'dd', (e)-> $('.boys').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.gw').on 'click', 'dd', (e)-> $('.gw').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $("#groomswomen").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.gw').find('dd').removeClass('active') x = $(".gw").find('a[data-orbit-link=gw'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#girls").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.girls').find('dd').removeClass('active') x = $(".girls").find('a[data-orbit-link=g'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#boys").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.boys').find('dd').removeClass('active') x = $(".boys").find('a[data-orbit-link=b'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $(".circular").on "mouseenter", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michaelRegex = /^Michael-\w+.jpg$/ michael1Regex = /^Michael1-\w+.jpg$/ marcRegex = /^Marc-\w+\.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michaelRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Michael1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Michael.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marcRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc.jpg') no-repeat") $(e.target).css('background-size', "cover") $(".circular").on "mouseleave", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michael1Regex = /^Michael1-\w+.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Michael.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc.jpg') no-repeat") $(e.target).css('background-size', "cover")
192341
$ -> $('.girls').on 'click', 'dd', (e)-> $('.girls').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.boys').on 'click', 'dd', (e)-> $('.boys').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.gw').on 'click', 'dd', (e)-> $('.gw').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $("#groomswomen").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.gw').find('dd').removeClass('active') x = $(".gw").find('a[data-orbit-link=gw'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#girls").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.girls').find('dd').removeClass('active') x = $(".girls").find('a[data-orbit-link=g'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#boys").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.boys').find('dd').removeClass('active') x = $(".boys").find('a[data-orbit-link=b'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $(".circular").on "mouseenter", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michaelRegex = /^Michael-\w+.jpg$/ michael1Regex = /^Michael1-\w+.jpg$/ marcRegex = /^Marc-\w+\.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michaelRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Michael1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/<NAME>.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marcRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc.jpg') no-repeat") $(e.target).css('background-size', "cover") $(".circular").on "mouseleave", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michael1Regex = /^<NAME>1-\w+.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/<NAME>.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/<NAME>c.jpg') no-repeat") $(e.target).css('background-size', "cover")
true
$ -> $('.girls').on 'click', 'dd', (e)-> $('.girls').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.boys').on 'click', 'dd', (e)-> $('.boys').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $('.gw').on 'click', 'dd', (e)-> $('.gw').find('dd').removeClass('active') $(e.target).closest('dd').addClass('active') $("#groomswomen").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.gw').find('dd').removeClass('active') x = $(".gw").find('a[data-orbit-link=gw'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#girls").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.girls').find('dd').removeClass('active') x = $(".girls").find('a[data-orbit-link=g'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $("#boys").on "after-slide-change.fndtn.orbit", (event, orbit) -> $('.boys').find('dd').removeClass('active') x = $(".boys").find('a[data-orbit-link=b'+orbit.slide_number+ ']') x.closest('dd').addClass('active') $(".circular").on "mouseenter", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michaelRegex = /^Michael-\w+.jpg$/ michael1Regex = /^Michael1-\w+.jpg$/ marcRegex = /^Marc-\w+\.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michaelRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Michael1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/PI:NAME:<NAME>END_PI.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marcRegex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc1.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/Marc.jpg') no-repeat") $(e.target).css('background-size', "cover") $(".circular").on "mouseleave", (e) -> image = $(e.target).css('background-image') name = /\w+\-\w+\.jpg/.exec(image)[0] michael1Regex = /^PI:NAME:<NAME>END_PI1-\w+.jpg$/ marc1Regex = /^Marc1-\w+\.jpg$/ if michael1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/PI:NAME:<NAME>END_PI.jpg') no-repeat") $(e.target).css('background-size', "cover") else if marc1Regex.test(name) $(e.target).css('background', "url('/images/bridal_party/PI:NAME:<NAME>END_PIc.jpg') no-repeat") $(e.target).css('background-size', "cover")
[ { "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.9998618364334106, "start": 74, "tag": "NAME", "value": "Yasuhiro Okuno" } ]
coffee_lib/crowdutil/command.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 crowdECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # requires log4js = require 'log4js' AtlassianCrowd = require '../atlassian-crowd-ext/atlassian-crowd-ext' cmdlist = require './subcmd/cmdlist' fs = require 'fs' getUserHome = () -> # since %HOME% may exist in some Windows environments, we first check for # %USERPROFILE% then look for $HOME return process.env.USERPROFILE || process.env.HOME ### read config file from current working directory ### readConfig = (opts) -> path = null # PRIORITY 1: CHECK opts['-c'] if( typeof opts['-c'] == 'object' && typeof opts['-c'][0] == 'string' ) if fs.existsSync(opts['-c'][0]) path = opts['-c'][0] else console.log "E, file #{opts['-c'][0]} NOT FOUND!" return null # PRIORITY 2: CHECK process.cwd() + '/crowdutil.json' if( path == null && fs.existsSync(process.cwd() + '/crowdutil.json') ) path = process.cwd() + '/crowdutil.json' # PRIORITY 3: CHECK getUserHome() + '/.crowdutil/config.json' if( path == null && fs.existsSync(getUserHome() + '/.crowdutil/config.json') ) path = getUserHome() + '/.crowdutil/config.json' if path != null global.crowdutil_cfg = path return require path return null ### Connect to Crowd service and save connection object in opts['crowd'] ### connectCrowd = (opts, cfg) -> # Figure out the target directory. # command line option -D taking precedance to default setting. # if no -D option is provided, we check if there is a default directory # directive in the configuration file. if( typeof opts['-D'] == 'object' && typeof opts['-D'][0] == 'string' ) directory = opts['-D'][0] else if typeof cfg['defaultDirectory'] == 'string' directory = cfg['defaultDirectory'] else throw new Error('Directory not specified!') # check if specified directory is valid if typeof cfg['directories'][directory] != 'undefined' try # create connection based on settings opts['crowd'] = new AtlassianCrowd( cfg['directories'][directory] ) catch err throw err else errConfig = new Error('Directory not defined.') throw errConfig return ### Setup global.logger ### initLogger = (opts, cfg) -> if typeof cfg['logConfig'] != 'undefined' logConfig = cfg['logConfig'] else logConfig = appenders: [ { type: 'file' filename: './crowdutil.log' maxLogSize: 20480 backups: 2 category: 'crowdutil' } ] log4js.configure(logConfig) global.logger = log4js.getLogger('crowdutil') if( typeof opts['-v'] == 'object' && typeof opts['-v'][0] == 'boolean' && opts['-v'][0] == true ) logger.setLevel('TRACE') logger.debug 'log level set to trace' else logger.setLevel('INFO') return init = (opts) -> cfg = readConfig(opts) # could not find any valid config file if cfg == null console.log "E, could not load config file" return false rc = true initLogger(opts, cfg) logger.info "===============================================" logger.info "crowdutil: Atlassian CROWD cli utility tool" try connectCrowd(opts, cfg) catch err if err logger.debug err.message rc = false return rc ### cli entrypoint command format: crowdutil command options commands all commands are specified in list exported by subcmd/cmdlist.coffee list key is the command name as well as the require target for the command execution. ### exports.run = () -> cmdlist.start(init) return
89792
### @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 crowdECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # requires log4js = require 'log4js' AtlassianCrowd = require '../atlassian-crowd-ext/atlassian-crowd-ext' cmdlist = require './subcmd/cmdlist' fs = require 'fs' getUserHome = () -> # since %HOME% may exist in some Windows environments, we first check for # %USERPROFILE% then look for $HOME return process.env.USERPROFILE || process.env.HOME ### read config file from current working directory ### readConfig = (opts) -> path = null # PRIORITY 1: CHECK opts['-c'] if( typeof opts['-c'] == 'object' && typeof opts['-c'][0] == 'string' ) if fs.existsSync(opts['-c'][0]) path = opts['-c'][0] else console.log "E, file #{opts['-c'][0]} NOT FOUND!" return null # PRIORITY 2: CHECK process.cwd() + '/crowdutil.json' if( path == null && fs.existsSync(process.cwd() + '/crowdutil.json') ) path = process.cwd() + '/crowdutil.json' # PRIORITY 3: CHECK getUserHome() + '/.crowdutil/config.json' if( path == null && fs.existsSync(getUserHome() + '/.crowdutil/config.json') ) path = getUserHome() + '/.crowdutil/config.json' if path != null global.crowdutil_cfg = path return require path return null ### Connect to Crowd service and save connection object in opts['crowd'] ### connectCrowd = (opts, cfg) -> # Figure out the target directory. # command line option -D taking precedance to default setting. # if no -D option is provided, we check if there is a default directory # directive in the configuration file. if( typeof opts['-D'] == 'object' && typeof opts['-D'][0] == 'string' ) directory = opts['-D'][0] else if typeof cfg['defaultDirectory'] == 'string' directory = cfg['defaultDirectory'] else throw new Error('Directory not specified!') # check if specified directory is valid if typeof cfg['directories'][directory] != 'undefined' try # create connection based on settings opts['crowd'] = new AtlassianCrowd( cfg['directories'][directory] ) catch err throw err else errConfig = new Error('Directory not defined.') throw errConfig return ### Setup global.logger ### initLogger = (opts, cfg) -> if typeof cfg['logConfig'] != 'undefined' logConfig = cfg['logConfig'] else logConfig = appenders: [ { type: 'file' filename: './crowdutil.log' maxLogSize: 20480 backups: 2 category: 'crowdutil' } ] log4js.configure(logConfig) global.logger = log4js.getLogger('crowdutil') if( typeof opts['-v'] == 'object' && typeof opts['-v'][0] == 'boolean' && opts['-v'][0] == true ) logger.setLevel('TRACE') logger.debug 'log level set to trace' else logger.setLevel('INFO') return init = (opts) -> cfg = readConfig(opts) # could not find any valid config file if cfg == null console.log "E, could not load config file" return false rc = true initLogger(opts, cfg) logger.info "===============================================" logger.info "crowdutil: Atlassian CROWD cli utility tool" try connectCrowd(opts, cfg) catch err if err logger.debug err.message rc = false return rc ### cli entrypoint command format: crowdutil command options commands all commands are specified in list exported by subcmd/cmdlist.coffee list key is the command name as well as the require target for the command execution. ### exports.run = () -> cmdlist.start(init) return
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 crowdECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # requires log4js = require 'log4js' AtlassianCrowd = require '../atlassian-crowd-ext/atlassian-crowd-ext' cmdlist = require './subcmd/cmdlist' fs = require 'fs' getUserHome = () -> # since %HOME% may exist in some Windows environments, we first check for # %USERPROFILE% then look for $HOME return process.env.USERPROFILE || process.env.HOME ### read config file from current working directory ### readConfig = (opts) -> path = null # PRIORITY 1: CHECK opts['-c'] if( typeof opts['-c'] == 'object' && typeof opts['-c'][0] == 'string' ) if fs.existsSync(opts['-c'][0]) path = opts['-c'][0] else console.log "E, file #{opts['-c'][0]} NOT FOUND!" return null # PRIORITY 2: CHECK process.cwd() + '/crowdutil.json' if( path == null && fs.existsSync(process.cwd() + '/crowdutil.json') ) path = process.cwd() + '/crowdutil.json' # PRIORITY 3: CHECK getUserHome() + '/.crowdutil/config.json' if( path == null && fs.existsSync(getUserHome() + '/.crowdutil/config.json') ) path = getUserHome() + '/.crowdutil/config.json' if path != null global.crowdutil_cfg = path return require path return null ### Connect to Crowd service and save connection object in opts['crowd'] ### connectCrowd = (opts, cfg) -> # Figure out the target directory. # command line option -D taking precedance to default setting. # if no -D option is provided, we check if there is a default directory # directive in the configuration file. if( typeof opts['-D'] == 'object' && typeof opts['-D'][0] == 'string' ) directory = opts['-D'][0] else if typeof cfg['defaultDirectory'] == 'string' directory = cfg['defaultDirectory'] else throw new Error('Directory not specified!') # check if specified directory is valid if typeof cfg['directories'][directory] != 'undefined' try # create connection based on settings opts['crowd'] = new AtlassianCrowd( cfg['directories'][directory] ) catch err throw err else errConfig = new Error('Directory not defined.') throw errConfig return ### Setup global.logger ### initLogger = (opts, cfg) -> if typeof cfg['logConfig'] != 'undefined' logConfig = cfg['logConfig'] else logConfig = appenders: [ { type: 'file' filename: './crowdutil.log' maxLogSize: 20480 backups: 2 category: 'crowdutil' } ] log4js.configure(logConfig) global.logger = log4js.getLogger('crowdutil') if( typeof opts['-v'] == 'object' && typeof opts['-v'][0] == 'boolean' && opts['-v'][0] == true ) logger.setLevel('TRACE') logger.debug 'log level set to trace' else logger.setLevel('INFO') return init = (opts) -> cfg = readConfig(opts) # could not find any valid config file if cfg == null console.log "E, could not load config file" return false rc = true initLogger(opts, cfg) logger.info "===============================================" logger.info "crowdutil: Atlassian CROWD cli utility tool" try connectCrowd(opts, cfg) catch err if err logger.debug err.message rc = false return rc ### cli entrypoint command format: crowdutil command options commands all commands are specified in list exported by subcmd/cmdlist.coffee list key is the command name as well as the require target for the command execution. ### exports.run = () -> cmdlist.start(init) return
[ { "context": "\n# A CoffeeScript version of Paul Irish's requestAnimationFrame polyfill.\ndo ->\n w = win", "end": 39, "score": 0.999386727809906, "start": 29, "tag": "NAME", "value": "Paul Irish" } ]
coffee/index.coffee
ndrwhr/tumbler
20
# A CoffeeScript version of Paul Irish's requestAnimationFrame polyfill. do -> w = window for vendor in ['ms', 'moz', 'webkit', 'o'] break if w.requestAnimationFrame w.requestAnimationFrame = w["#{vendor}RequestAnimationFrame"] w.cancelAnimationFrame = (w["#{vendor}CancelAnimationFrame"] or w["#{vendor}CancelRequestAnimationFrame"]) # deal with the case where rAF is built in but cAF is not. if w.requestAnimationFrame return if w.cancelAnimationFrame browserRaf = w.requestAnimationFrame canceled = {} w.requestAnimationFrame = (callback) -> id = browserRaf (time) -> if id of canceled then delete canceled[id] else callback time w.cancelAnimationFrame = (id) -> canceled[id] = true # handle legacy browsers which don’t implement rAF else targetTime = 0 w.requestAnimationFrame = (callback) -> targetTime = Math.max targetTime + 16, currentTime = +new Date w.setTimeout (-> callback +new Date), targetTime - currentTime w.cancelAnimationFrame = (id) -> clearTimeout id window.addEventListener('DOMContentLoaded', -> new Loader() document.querySelector('#rate').addEventListener('change', (evt) -> Config.SIMULATION_RATE = parseFloat(evt.target.value) ) muteButton = document.querySelector('#mute') if SoundManager.isSupported muteButton.addEventListener('change', (evt) -> SoundManager.mute(evt.target.checked) ) else muteButton.checked = muteButton.disabled = true document.querySelector('#mute + label').title = "Audio requires the Web Audio API which your browser does not support." )
144023
# A CoffeeScript version of <NAME>'s requestAnimationFrame polyfill. do -> w = window for vendor in ['ms', 'moz', 'webkit', 'o'] break if w.requestAnimationFrame w.requestAnimationFrame = w["#{vendor}RequestAnimationFrame"] w.cancelAnimationFrame = (w["#{vendor}CancelAnimationFrame"] or w["#{vendor}CancelRequestAnimationFrame"]) # deal with the case where rAF is built in but cAF is not. if w.requestAnimationFrame return if w.cancelAnimationFrame browserRaf = w.requestAnimationFrame canceled = {} w.requestAnimationFrame = (callback) -> id = browserRaf (time) -> if id of canceled then delete canceled[id] else callback time w.cancelAnimationFrame = (id) -> canceled[id] = true # handle legacy browsers which don’t implement rAF else targetTime = 0 w.requestAnimationFrame = (callback) -> targetTime = Math.max targetTime + 16, currentTime = +new Date w.setTimeout (-> callback +new Date), targetTime - currentTime w.cancelAnimationFrame = (id) -> clearTimeout id window.addEventListener('DOMContentLoaded', -> new Loader() document.querySelector('#rate').addEventListener('change', (evt) -> Config.SIMULATION_RATE = parseFloat(evt.target.value) ) muteButton = document.querySelector('#mute') if SoundManager.isSupported muteButton.addEventListener('change', (evt) -> SoundManager.mute(evt.target.checked) ) else muteButton.checked = muteButton.disabled = true document.querySelector('#mute + label').title = "Audio requires the Web Audio API which your browser does not support." )
true
# A CoffeeScript version of PI:NAME:<NAME>END_PI's requestAnimationFrame polyfill. do -> w = window for vendor in ['ms', 'moz', 'webkit', 'o'] break if w.requestAnimationFrame w.requestAnimationFrame = w["#{vendor}RequestAnimationFrame"] w.cancelAnimationFrame = (w["#{vendor}CancelAnimationFrame"] or w["#{vendor}CancelRequestAnimationFrame"]) # deal with the case where rAF is built in but cAF is not. if w.requestAnimationFrame return if w.cancelAnimationFrame browserRaf = w.requestAnimationFrame canceled = {} w.requestAnimationFrame = (callback) -> id = browserRaf (time) -> if id of canceled then delete canceled[id] else callback time w.cancelAnimationFrame = (id) -> canceled[id] = true # handle legacy browsers which don’t implement rAF else targetTime = 0 w.requestAnimationFrame = (callback) -> targetTime = Math.max targetTime + 16, currentTime = +new Date w.setTimeout (-> callback +new Date), targetTime - currentTime w.cancelAnimationFrame = (id) -> clearTimeout id window.addEventListener('DOMContentLoaded', -> new Loader() document.querySelector('#rate').addEventListener('change', (evt) -> Config.SIMULATION_RATE = parseFloat(evt.target.value) ) muteButton = document.querySelector('#mute') if SoundManager.isSupported muteButton.addEventListener('change', (evt) -> SoundManager.mute(evt.target.checked) ) else muteButton.checked = muteButton.disabled = true document.querySelector('#mute + label').title = "Audio requires the Web Audio API which your browser does not support." )
[ { "context": " ->\n before -> @product = id: 123, name: \"foo bar\"\n\n it \"is defined\", ->\n expect(Produc", "end": 1003, "score": 0.7279783487319946, "start": 1000, "tag": "NAME", "value": "bar" }, { "context": " product = new Products(id: 4567, name: \"...
client/test/unit/modules/resources_spec.coffee
lucassus/angular-coffee-seed
2
describe "Module `myApp.resources`", -> beforeEach module "myApp.resources" describe "Service `Products`", -> $rootScope = null $httpBackend = null Products = null beforeEach inject (_$rootScope_, _$httpBackend_, _Products_) -> $rootScope = _$rootScope_ $httpBackend = _$httpBackend_ Products = _Products_ it "is defined", -> expect(Products).to.not.be.undefined describe ".query()", -> before -> @products = [{ name: "foo" }, { name: "bar" }] it "is defined", -> expect(Products.query).to.not.be.undefined it "queries for the records", -> $httpBackend.whenGET("/api/products.json").respond(@products) promise = Products.query().$promise $httpBackend.flush() products = null $rootScope.$apply -> promise.then (_products_) -> products = _products_ expect(products).to.have.length 2 describe ".get()", -> before -> @product = id: 123, name: "foo bar" it "is defined", -> expect(Products.get).to.not.be.undefined it "queries for a product", -> $httpBackend.whenGET("/api/products/123.json").respond(@product) promise = Products.get(id: 123).$promise expect(promise).to.not.be.undefined $httpBackend.flush() product = null $rootScope.$apply -> promise.then (_product_) -> product = _product_ expect(product).to.not.be.null expect(product.id).to.equal 123 expect(product.name).to.equal "foo bar" describe "#$save()", -> product = null context "when the `id` is not given", -> beforeEach inject (Products) -> product = new Products(name: "foo") it "creates a new record", -> $httpBackend.whenPOST("/api/products.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() context "when the `id` is given", -> beforeEach inject (Products) -> product = new Products(id: 4567, name: "foo") it "updates the record", -> $httpBackend.whenPOST("/api/products/4567.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() describe "#persisted()", -> product = null beforeEach -> product = new Products() context "when the product has an id", -> beforeEach -> product.id = 123 it "returns true", -> expect(product.persisted()).to.be.true context "when the product does not have an id", -> beforeEach -> product.id = null it "returns false", -> expect(product.persisted()).to.be.false describe "#priceWithDiscount()", -> product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.priceWithDiscount).to.not.be.undefined context "when discount is not defined", -> beforeEach -> product.discount = undefined product.price = 9.99 it "returns the base price", -> expect(product.priceWithDiscount()).to.equal 9.99 context "when discount is defined", -> beforeEach -> product.discount = 22 product.price = 100 it "returns price with discount", -> expect(product.priceWithDiscount()).to.equal 78 describe "#hasDiscount()", -> # custom chai property for checking product's discount chai.Assertion.addProperty "discount", -> subject = @_obj @assert subject.hasDiscount(), "expected #\{this} to have discount", "expected #\{this} to not have discount" product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.hasDiscount).to.not.be.undefined context "when the discount is not defined", -> beforeEach -> product.discount = undefined it "returns false", -> expect(product).to.not.have.discount context "when the @discount is null", -> beforeEach -> product.discount = null it "returns false", -> expect(product).to.not.have.discount context "when the @discount is 0", -> beforeEach -> product.discount = 0 it "returns false", -> expect(product).to.not.have.discount context "when the @discount < 0", -> beforeEach -> product.discount = -10 it "returns false", -> expect(product).to.not.have.discount context "when the @discount is > 0", -> beforeEach -> product.discount = 10 it "returns true", -> expect(product).to.have.discount
25343
describe "Module `myApp.resources`", -> beforeEach module "myApp.resources" describe "Service `Products`", -> $rootScope = null $httpBackend = null Products = null beforeEach inject (_$rootScope_, _$httpBackend_, _Products_) -> $rootScope = _$rootScope_ $httpBackend = _$httpBackend_ Products = _Products_ it "is defined", -> expect(Products).to.not.be.undefined describe ".query()", -> before -> @products = [{ name: "foo" }, { name: "bar" }] it "is defined", -> expect(Products.query).to.not.be.undefined it "queries for the records", -> $httpBackend.whenGET("/api/products.json").respond(@products) promise = Products.query().$promise $httpBackend.flush() products = null $rootScope.$apply -> promise.then (_products_) -> products = _products_ expect(products).to.have.length 2 describe ".get()", -> before -> @product = id: 123, name: "foo <NAME>" it "is defined", -> expect(Products.get).to.not.be.undefined it "queries for a product", -> $httpBackend.whenGET("/api/products/123.json").respond(@product) promise = Products.get(id: 123).$promise expect(promise).to.not.be.undefined $httpBackend.flush() product = null $rootScope.$apply -> promise.then (_product_) -> product = _product_ expect(product).to.not.be.null expect(product.id).to.equal 123 expect(product.name).to.equal "foo bar" describe "#$save()", -> product = null context "when the `id` is not given", -> beforeEach inject (Products) -> product = new Products(name: "foo") it "creates a new record", -> $httpBackend.whenPOST("/api/products.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() context "when the `id` is given", -> beforeEach inject (Products) -> product = new Products(id: 4567, name: "<NAME>") it "updates the record", -> $httpBackend.whenPOST("/api/products/4567.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() describe "#persisted()", -> product = null beforeEach -> product = new Products() context "when the product has an id", -> beforeEach -> product.id = 123 it "returns true", -> expect(product.persisted()).to.be.true context "when the product does not have an id", -> beforeEach -> product.id = null it "returns false", -> expect(product.persisted()).to.be.false describe "#priceWithDiscount()", -> product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.priceWithDiscount).to.not.be.undefined context "when discount is not defined", -> beforeEach -> product.discount = undefined product.price = 9.99 it "returns the base price", -> expect(product.priceWithDiscount()).to.equal 9.99 context "when discount is defined", -> beforeEach -> product.discount = 22 product.price = 100 it "returns price with discount", -> expect(product.priceWithDiscount()).to.equal 78 describe "#hasDiscount()", -> # custom chai property for checking product's discount chai.Assertion.addProperty "discount", -> subject = @_obj @assert subject.hasDiscount(), "expected #\{this} to have discount", "expected #\{this} to not have discount" product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.hasDiscount).to.not.be.undefined context "when the discount is not defined", -> beforeEach -> product.discount = undefined it "returns false", -> expect(product).to.not.have.discount context "when the @discount is null", -> beforeEach -> product.discount = null it "returns false", -> expect(product).to.not.have.discount context "when the @discount is 0", -> beforeEach -> product.discount = 0 it "returns false", -> expect(product).to.not.have.discount context "when the @discount < 0", -> beforeEach -> product.discount = -10 it "returns false", -> expect(product).to.not.have.discount context "when the @discount is > 0", -> beforeEach -> product.discount = 10 it "returns true", -> expect(product).to.have.discount
true
describe "Module `myApp.resources`", -> beforeEach module "myApp.resources" describe "Service `Products`", -> $rootScope = null $httpBackend = null Products = null beforeEach inject (_$rootScope_, _$httpBackend_, _Products_) -> $rootScope = _$rootScope_ $httpBackend = _$httpBackend_ Products = _Products_ it "is defined", -> expect(Products).to.not.be.undefined describe ".query()", -> before -> @products = [{ name: "foo" }, { name: "bar" }] it "is defined", -> expect(Products.query).to.not.be.undefined it "queries for the records", -> $httpBackend.whenGET("/api/products.json").respond(@products) promise = Products.query().$promise $httpBackend.flush() products = null $rootScope.$apply -> promise.then (_products_) -> products = _products_ expect(products).to.have.length 2 describe ".get()", -> before -> @product = id: 123, name: "foo PI:NAME:<NAME>END_PI" it "is defined", -> expect(Products.get).to.not.be.undefined it "queries for a product", -> $httpBackend.whenGET("/api/products/123.json").respond(@product) promise = Products.get(id: 123).$promise expect(promise).to.not.be.undefined $httpBackend.flush() product = null $rootScope.$apply -> promise.then (_product_) -> product = _product_ expect(product).to.not.be.null expect(product.id).to.equal 123 expect(product.name).to.equal "foo bar" describe "#$save()", -> product = null context "when the `id` is not given", -> beforeEach inject (Products) -> product = new Products(name: "foo") it "creates a new record", -> $httpBackend.whenPOST("/api/products.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() context "when the `id` is given", -> beforeEach inject (Products) -> product = new Products(id: 4567, name: "PI:NAME:<NAME>END_PI") it "updates the record", -> $httpBackend.whenPOST("/api/products/4567.json").respond({}) promise = product.$save() expect(promise).to.not.be.undefined $httpBackend.flush() describe "#persisted()", -> product = null beforeEach -> product = new Products() context "when the product has an id", -> beforeEach -> product.id = 123 it "returns true", -> expect(product.persisted()).to.be.true context "when the product does not have an id", -> beforeEach -> product.id = null it "returns false", -> expect(product.persisted()).to.be.false describe "#priceWithDiscount()", -> product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.priceWithDiscount).to.not.be.undefined context "when discount is not defined", -> beforeEach -> product.discount = undefined product.price = 9.99 it "returns the base price", -> expect(product.priceWithDiscount()).to.equal 9.99 context "when discount is defined", -> beforeEach -> product.discount = 22 product.price = 100 it "returns price with discount", -> expect(product.priceWithDiscount()).to.equal 78 describe "#hasDiscount()", -> # custom chai property for checking product's discount chai.Assertion.addProperty "discount", -> subject = @_obj @assert subject.hasDiscount(), "expected #\{this} to have discount", "expected #\{this} to not have discount" product = null beforeEach inject (Products) -> product = new Products() it "is defined", -> expect(product.hasDiscount).to.not.be.undefined context "when the discount is not defined", -> beforeEach -> product.discount = undefined it "returns false", -> expect(product).to.not.have.discount context "when the @discount is null", -> beforeEach -> product.discount = null it "returns false", -> expect(product).to.not.have.discount context "when the @discount is 0", -> beforeEach -> product.discount = 0 it "returns false", -> expect(product).to.not.have.discount context "when the @discount < 0", -> beforeEach -> product.discount = -10 it "returns false", -> expect(product).to.not.have.discount context "when the @discount is > 0", -> beforeEach -> product.discount = 10 it "returns true", -> expect(product).to.have.discount
[ { "context": "force spacing before and after keywords.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 96, "score": 0.9998630881309509, "start": 82, "tag": "NAME", "value": "Toru Nagashima" } ]
src/rules/keyword-spacing.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to enforce spacing before and after keywords. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' keywords = require '../eslint-keywords' #------------------------------------------------------------------------------ # Constants #------------------------------------------------------------------------------ PREV_TOKEN = /// ^ (?: # [-=] > | [ )\]}> ] ) $ /// NEXT_TOKEN = /// ^ (?: [-=] > | [ ([{<~! ] | \+\+? | --? ) $ /// PREV_TOKEN_M = /^[)\]}>*]$/ NEXT_TOKEN_M = /^[{*]$/ TEMPLATE_OPEN_PAREN = /\$\{$/ TEMPLATE_CLOSE_PAREN = /^\}/ CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/ KEYS = keywords.concat [ 'as' 'async' 'await' 'from' 'get' 'let' 'of' 'set' 'yield' 'then' 'when' 'unless' 'until' 'not' ] # check duplications. do -> KEYS.sort() for i in [1...KEYS.length] if KEYS[i] is KEYS[i - 1] throw new Error "Duplication was found in the keyword list: #{KEYS[i]}" #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether or not a given token is a "Template" token ends with "${". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token ends with "${". ### isOpenParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_OPEN_PAREN.test token.value ###* # Checks whether or not a given token is a "Template" token starts with "}". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token starts with "}". ### isCloseParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_CLOSE_PAREN.test token.value #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing before and after keywords' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/keyword-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: before: type: 'boolean' after: type: 'boolean' overrides: type: 'object' properties: KEYS.reduce( (retv, key) -> retv[key] = type: 'object' properties: before: type: 'boolean' after: type: 'boolean' additionalProperties: no retv , {} ) additionalProperties: no additionalProperties: no ] create: (context) -> sourceCode = context.getSourceCode() ###* # Reports a given token if there are not space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### expectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and not sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Expected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.insertTextBefore token, ' ' ###* # Reports a given token if there are space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### unexpectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Unexpected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [prevToken.range[1], token.range[0]] ###* # Reports a given token if there are not space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### expectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and not sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Expected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.insertTextAfter token, ' ' ###* # Reports a given token if there are space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### unexpectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Unexpected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [token.range[1], nextToken.range[0]] ###* # Parses the option object and determines check methods for each keyword. # # @param {Object|undefined} options - The option object to parse. # @returns {Object} - Normalized option object. # Keys are keywords (there are for every keyword). # Values are instances of `{"before": function, "after": function}`. ### parseOptions = (options) -> before = not options or options.before isnt no after = not options or options.after isnt no defaultValue = before: if before then expectSpaceBefore else unexpectSpaceBefore after: if after then expectSpaceAfter else unexpectSpaceAfter overrides = options?.overrides or {} retv = Object.create null for key in KEYS override = overrides[key] if override thisBefore = if 'before' of override then override.before else before thisAfter = if 'after' of override then override.after else after retv[key] = before: if thisBefore expectSpaceBefore else unexpectSpaceBefore after: if thisAfter then expectSpaceAfter else unexpectSpaceAfter else retv[key] = defaultValue retv checkMethodMap = parseOptions context.options[0] ###* # Reports a given token if usage of spacing followed by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the previous # token to check. # @returns {void} ### checkSpacingBefore = (token, pattern) -> checkMethodMap[token.value].before token, pattern or PREV_TOKEN ###* # Reports a given token if usage of spacing preceded by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the next # token to check. # @returns {void} ### checkSpacingAfter = (token, pattern) -> checkMethodMap[token.value].after token, pattern or NEXT_TOKEN ###* # Reports a given token if usage of spacing around the token is invalid. # # @param {Token} token - A token to report. # @returns {void} ### checkSpacingAround = (token) -> checkSpacingBefore token checkSpacingAfter token ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken and firstToken.type is 'Keyword' checkSpacingAround firstToken ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing followed by the token is invalid. # # This is used for unary operators (e.g. `typeof`), `function`, and `super`. # Other rules are handling usage of spacing preceded by those keywords. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingBeforeFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken?.type is 'Keyword' checkSpacingBefore firstToken ###* # Reports the previous token of a given node if the token is a keyword and # usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundTokenBefore = (node) -> if node token = sourceCode.getTokenBefore node, astUtils.isKeywordToken checkSpacingAround token ###* # Reports `async` or `function` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForFunction = (node) -> firstToken = node and sourceCode.getFirstToken node if ( firstToken and ((firstToken.type is 'Keyword' and firstToken.value is 'function') or firstToken.value is 'async') ) checkSpacingBefore firstToken ###* # Reports `class` and `extends` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForClass = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.superClass ###* # Reports `if` and `else` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForIfStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.consequent, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.consequent checkSpacingAround token if token?.value is 'then' if node.alternate token = sourceCode.getTokenBefore( node.alternate astUtils.isKeywordToken ) unless token?.value is 'else' token = sourceCode.getFirstToken node.alternate checkSpacingAround token if token?.value is 'else' ###* # Reports `try`, `catch`, and `finally` keywords of a given node if usage # of spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForTryStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundFirstToken node.handler checkSpacingAroundTokenBefore node.finalizer ###* # Reports `do` and `while` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForDoWhileStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.test checkSpacingForWhileStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `for` and `in` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForInStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.right ###* # Reports `for` and `of` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForOfStatement = (node) -> if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.right, astUtils.isNotOpeningParenToken ) checkSpacingForFor = (node) -> if node.postfix # TODO: postfix await, when, by # if node.await # checkSpacingBefore sourceCode.getFirstToken node, 0 # checkSpacingAfter sourceCode.getFirstToken node, 1 # else checkSpacingAround sourceCode.getTokenAfter node.body else if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.source, astUtils.isNotOpeningParenToken ) token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `import`, `export`, `as`, and `from` keywords of a given node if # usage of spacing around those keywords is invalid. # # This rule handles the `*` token in module declarations. # # import*as A from "./a"; /*error Expected space(s) after "import". # error Expected space(s) before "as". # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForModuleDeclaration = (node) -> firstToken = sourceCode.getFirstToken node checkSpacingBefore firstToken, PREV_TOKEN_M checkSpacingAfter firstToken, NEXT_TOKEN_M if node.source fromToken = sourceCode.getTokenBefore node.source checkSpacingBefore fromToken, PREV_TOKEN_M checkSpacingAfter fromToken, NEXT_TOKEN_M ###* # Reports `as` keyword of a given node if usage of spacing around this # keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForImportNamespaceSpecifier = (node) -> asToken = sourceCode.getFirstToken node, 1 checkSpacingBefore asToken, PREV_TOKEN_M ###* # Reports `static`, `get`, and `set` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForProperty = (node) -> if node.static then checkSpacingAroundFirstToken node # if ( # node.kind in ['get', 'set'] or # ((node.method or node.type is 'MethodDefinition') and node.value.async) # ) # token = sourceCode.getTokenBefore node.key, (tok) -> # switch tok.value # when 'get', 'set', 'async' # return yes # else # return no # unless token # throw new Error( # 'Failed to find token get, set, or async beside method name' # ) # checkSpacingAround token ###* # Reports `await` keyword of a given node if usage of spacing before # this keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForAwaitExpression = (node) -> checkSpacingBefore sourceCode.getFirstToken node # Statements DebuggerStatement: checkSpacingAroundFirstToken WithStatement: checkSpacingAroundFirstToken # Statements - Control flow BreakStatement: checkSpacingAroundFirstToken ContinueStatement: checkSpacingAroundFirstToken ReturnStatement: checkSpacingAroundFirstToken ThrowStatement: checkSpacingAroundFirstToken TryStatement: checkSpacingForTryStatement # Statements - Choice IfStatement: checkSpacingForIfStatement ConditionalExpression: checkSpacingForIfStatement SwitchStatement: checkSpacingAroundFirstToken SwitchCase: checkSpacingAroundFirstToken # Statements - Loops DoWhileStatement: checkSpacingForDoWhileStatement ForInStatement: checkSpacingForForInStatement ForOfStatement: checkSpacingForForOfStatement For: checkSpacingForFor ForStatement: checkSpacingAroundFirstToken WhileStatement: checkSpacingForWhileStatement # Statements - Declarations ClassDeclaration: checkSpacingForClass ExportNamedDeclaration: checkSpacingForModuleDeclaration ExportDefaultDeclaration: checkSpacingAroundFirstToken ExportAllDeclaration: checkSpacingForModuleDeclaration FunctionDeclaration: checkSpacingForFunction ImportDeclaration: checkSpacingForModuleDeclaration VariableDeclaration: checkSpacingAroundFirstToken # Expressions ArrowFunctionExpression: checkSpacingForFunction AwaitExpression: checkSpacingForAwaitExpression ClassExpression: checkSpacingForClass FunctionExpression: checkSpacingForFunction NewExpression: checkSpacingBeforeFirstToken Super: checkSpacingBeforeFirstToken ThisExpression: checkSpacingBeforeFirstToken UnaryExpression: checkSpacingAroundFirstToken YieldExpression: checkSpacingBeforeFirstToken # Others ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier MethodDefinition: checkSpacingForProperty Property: checkSpacingForProperty
91774
###* # @fileoverview Rule to enforce spacing before and after keywords. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' keywords = require '../eslint-keywords' #------------------------------------------------------------------------------ # Constants #------------------------------------------------------------------------------ PREV_TOKEN = /// ^ (?: # [-=] > | [ )\]}> ] ) $ /// NEXT_TOKEN = /// ^ (?: [-=] > | [ ([{<~! ] | \+\+? | --? ) $ /// PREV_TOKEN_M = /^[)\]}>*]$/ NEXT_TOKEN_M = /^[{*]$/ TEMPLATE_OPEN_PAREN = /\$\{$/ TEMPLATE_CLOSE_PAREN = /^\}/ CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/ KEYS = keywords.concat [ 'as' 'async' 'await' 'from' 'get' 'let' 'of' 'set' 'yield' 'then' 'when' 'unless' 'until' 'not' ] # check duplications. do -> KEYS.sort() for i in [1...KEYS.length] if KEYS[i] is KEYS[i - 1] throw new Error "Duplication was found in the keyword list: #{KEYS[i]}" #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether or not a given token is a "Template" token ends with "${". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token ends with "${". ### isOpenParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_OPEN_PAREN.test token.value ###* # Checks whether or not a given token is a "Template" token starts with "}". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token starts with "}". ### isCloseParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_CLOSE_PAREN.test token.value #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing before and after keywords' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/keyword-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: before: type: 'boolean' after: type: 'boolean' overrides: type: 'object' properties: KEYS.reduce( (retv, key) -> retv[key] = type: 'object' properties: before: type: 'boolean' after: type: 'boolean' additionalProperties: no retv , {} ) additionalProperties: no additionalProperties: no ] create: (context) -> sourceCode = context.getSourceCode() ###* # Reports a given token if there are not space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### expectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and not sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Expected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.insertTextBefore token, ' ' ###* # Reports a given token if there are space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### unexpectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Unexpected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [prevToken.range[1], token.range[0]] ###* # Reports a given token if there are not space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### expectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and not sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Expected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.insertTextAfter token, ' ' ###* # Reports a given token if there are space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### unexpectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Unexpected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [token.range[1], nextToken.range[0]] ###* # Parses the option object and determines check methods for each keyword. # # @param {Object|undefined} options - The option object to parse. # @returns {Object} - Normalized option object. # Keys are keywords (there are for every keyword). # Values are instances of `{"before": function, "after": function}`. ### parseOptions = (options) -> before = not options or options.before isnt no after = not options or options.after isnt no defaultValue = before: if before then expectSpaceBefore else unexpectSpaceBefore after: if after then expectSpaceAfter else unexpectSpaceAfter overrides = options?.overrides or {} retv = Object.create null for key in KEYS override = overrides[key] if override thisBefore = if 'before' of override then override.before else before thisAfter = if 'after' of override then override.after else after retv[key] = before: if thisBefore expectSpaceBefore else unexpectSpaceBefore after: if thisAfter then expectSpaceAfter else unexpectSpaceAfter else retv[key] = defaultValue retv checkMethodMap = parseOptions context.options[0] ###* # Reports a given token if usage of spacing followed by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the previous # token to check. # @returns {void} ### checkSpacingBefore = (token, pattern) -> checkMethodMap[token.value].before token, pattern or PREV_TOKEN ###* # Reports a given token if usage of spacing preceded by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the next # token to check. # @returns {void} ### checkSpacingAfter = (token, pattern) -> checkMethodMap[token.value].after token, pattern or NEXT_TOKEN ###* # Reports a given token if usage of spacing around the token is invalid. # # @param {Token} token - A token to report. # @returns {void} ### checkSpacingAround = (token) -> checkSpacingBefore token checkSpacingAfter token ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken and firstToken.type is 'Keyword' checkSpacingAround firstToken ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing followed by the token is invalid. # # This is used for unary operators (e.g. `typeof`), `function`, and `super`. # Other rules are handling usage of spacing preceded by those keywords. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingBeforeFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken?.type is 'Keyword' checkSpacingBefore firstToken ###* # Reports the previous token of a given node if the token is a keyword and # usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundTokenBefore = (node) -> if node token = sourceCode.getTokenBefore node, astUtils.isKeywordToken checkSpacingAround token ###* # Reports `async` or `function` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForFunction = (node) -> firstToken = node and sourceCode.getFirstToken node if ( firstToken and ((firstToken.type is 'Keyword' and firstToken.value is 'function') or firstToken.value is 'async') ) checkSpacingBefore firstToken ###* # Reports `class` and `extends` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForClass = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.superClass ###* # Reports `if` and `else` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForIfStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.consequent, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.consequent checkSpacingAround token if token?.value is 'then' if node.alternate token = sourceCode.getTokenBefore( node.alternate astUtils.isKeywordToken ) unless token?.value is 'else' token = sourceCode.getFirstToken node.alternate checkSpacingAround token if token?.value is 'else' ###* # Reports `try`, `catch`, and `finally` keywords of a given node if usage # of spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForTryStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundFirstToken node.handler checkSpacingAroundTokenBefore node.finalizer ###* # Reports `do` and `while` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForDoWhileStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.test checkSpacingForWhileStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `for` and `in` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForInStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.right ###* # Reports `for` and `of` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForOfStatement = (node) -> if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.right, astUtils.isNotOpeningParenToken ) checkSpacingForFor = (node) -> if node.postfix # TODO: postfix await, when, by # if node.await # checkSpacingBefore sourceCode.getFirstToken node, 0 # checkSpacingAfter sourceCode.getFirstToken node, 1 # else checkSpacingAround sourceCode.getTokenAfter node.body else if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.source, astUtils.isNotOpeningParenToken ) token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `import`, `export`, `as`, and `from` keywords of a given node if # usage of spacing around those keywords is invalid. # # This rule handles the `*` token in module declarations. # # import*as A from "./a"; /*error Expected space(s) after "import". # error Expected space(s) before "as". # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForModuleDeclaration = (node) -> firstToken = sourceCode.getFirstToken node checkSpacingBefore firstToken, PREV_TOKEN_M checkSpacingAfter firstToken, NEXT_TOKEN_M if node.source fromToken = sourceCode.getTokenBefore node.source checkSpacingBefore fromToken, PREV_TOKEN_M checkSpacingAfter fromToken, NEXT_TOKEN_M ###* # Reports `as` keyword of a given node if usage of spacing around this # keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForImportNamespaceSpecifier = (node) -> asToken = sourceCode.getFirstToken node, 1 checkSpacingBefore asToken, PREV_TOKEN_M ###* # Reports `static`, `get`, and `set` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForProperty = (node) -> if node.static then checkSpacingAroundFirstToken node # if ( # node.kind in ['get', 'set'] or # ((node.method or node.type is 'MethodDefinition') and node.value.async) # ) # token = sourceCode.getTokenBefore node.key, (tok) -> # switch tok.value # when 'get', 'set', 'async' # return yes # else # return no # unless token # throw new Error( # 'Failed to find token get, set, or async beside method name' # ) # checkSpacingAround token ###* # Reports `await` keyword of a given node if usage of spacing before # this keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForAwaitExpression = (node) -> checkSpacingBefore sourceCode.getFirstToken node # Statements DebuggerStatement: checkSpacingAroundFirstToken WithStatement: checkSpacingAroundFirstToken # Statements - Control flow BreakStatement: checkSpacingAroundFirstToken ContinueStatement: checkSpacingAroundFirstToken ReturnStatement: checkSpacingAroundFirstToken ThrowStatement: checkSpacingAroundFirstToken TryStatement: checkSpacingForTryStatement # Statements - Choice IfStatement: checkSpacingForIfStatement ConditionalExpression: checkSpacingForIfStatement SwitchStatement: checkSpacingAroundFirstToken SwitchCase: checkSpacingAroundFirstToken # Statements - Loops DoWhileStatement: checkSpacingForDoWhileStatement ForInStatement: checkSpacingForForInStatement ForOfStatement: checkSpacingForForOfStatement For: checkSpacingForFor ForStatement: checkSpacingAroundFirstToken WhileStatement: checkSpacingForWhileStatement # Statements - Declarations ClassDeclaration: checkSpacingForClass ExportNamedDeclaration: checkSpacingForModuleDeclaration ExportDefaultDeclaration: checkSpacingAroundFirstToken ExportAllDeclaration: checkSpacingForModuleDeclaration FunctionDeclaration: checkSpacingForFunction ImportDeclaration: checkSpacingForModuleDeclaration VariableDeclaration: checkSpacingAroundFirstToken # Expressions ArrowFunctionExpression: checkSpacingForFunction AwaitExpression: checkSpacingForAwaitExpression ClassExpression: checkSpacingForClass FunctionExpression: checkSpacingForFunction NewExpression: checkSpacingBeforeFirstToken Super: checkSpacingBeforeFirstToken ThisExpression: checkSpacingBeforeFirstToken UnaryExpression: checkSpacingAroundFirstToken YieldExpression: checkSpacingBeforeFirstToken # Others ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier MethodDefinition: checkSpacingForProperty Property: checkSpacingForProperty
true
###* # @fileoverview Rule to enforce spacing before and after keywords. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' keywords = require '../eslint-keywords' #------------------------------------------------------------------------------ # Constants #------------------------------------------------------------------------------ PREV_TOKEN = /// ^ (?: # [-=] > | [ )\]}> ] ) $ /// NEXT_TOKEN = /// ^ (?: [-=] > | [ ([{<~! ] | \+\+? | --? ) $ /// PREV_TOKEN_M = /^[)\]}>*]$/ NEXT_TOKEN_M = /^[{*]$/ TEMPLATE_OPEN_PAREN = /\$\{$/ TEMPLATE_CLOSE_PAREN = /^\}/ CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/ KEYS = keywords.concat [ 'as' 'async' 'await' 'from' 'get' 'let' 'of' 'set' 'yield' 'then' 'when' 'unless' 'until' 'not' ] # check duplications. do -> KEYS.sort() for i in [1...KEYS.length] if KEYS[i] is KEYS[i - 1] throw new Error "Duplication was found in the keyword list: #{KEYS[i]}" #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Checks whether or not a given token is a "Template" token ends with "${". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token ends with "${". ### isOpenParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_OPEN_PAREN.test token.value ###* # Checks whether or not a given token is a "Template" token starts with "}". # # @param {Token} token - A token to check. # @returns {boolean} `true` if the token is a "Template" token starts with "}". ### isCloseParenOfTemplate = (token) -> token.type is 'Template' and TEMPLATE_CLOSE_PAREN.test token.value #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing before and after keywords' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/keyword-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: before: type: 'boolean' after: type: 'boolean' overrides: type: 'object' properties: KEYS.reduce( (retv, key) -> retv[key] = type: 'object' properties: before: type: 'boolean' after: type: 'boolean' additionalProperties: no retv , {} ) additionalProperties: no additionalProperties: no ] create: (context) -> sourceCode = context.getSourceCode() ###* # Reports a given token if there are not space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### expectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and not sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Expected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.insertTextBefore token, ' ' ###* # Reports a given token if there are space(s) before the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the previous token to check. # @returns {void} ### unexpectSpaceBefore = (token, pattern) -> prevToken = sourceCode.getTokenBefore token if ( prevToken and (CHECK_TYPE.test(prevToken.type) or pattern.test(prevToken.value)) and not isOpenParenOfTemplate(prevToken) and astUtils.isTokenOnSameLine(prevToken, token) and sourceCode.isSpaceBetweenTokens prevToken, token ) context.report loc: token.loc.start message: 'Unexpected space(s) before "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [prevToken.range[1], token.range[0]] ###* # Reports a given token if there are not space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### expectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and not sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Expected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.insertTextAfter token, ' ' ###* # Reports a given token if there are space(s) after the token. # # @param {Token} token - A token to report. # @param {RegExp} pattern - A pattern of the next token to check. # @returns {void} ### unexpectSpaceAfter = (token, pattern) -> nextToken = sourceCode.getTokenAfter token if ( nextToken and (CHECK_TYPE.test(nextToken.type) or pattern.test(nextToken.value)) and not isCloseParenOfTemplate(nextToken) and astUtils.isTokenOnSameLine(token, nextToken) and sourceCode.isSpaceBetweenTokens token, nextToken ) context.report loc: token.loc.start message: 'Unexpected space(s) after "{{value}}".' data: token fix: (fixer) -> fixer.removeRange [token.range[1], nextToken.range[0]] ###* # Parses the option object and determines check methods for each keyword. # # @param {Object|undefined} options - The option object to parse. # @returns {Object} - Normalized option object. # Keys are keywords (there are for every keyword). # Values are instances of `{"before": function, "after": function}`. ### parseOptions = (options) -> before = not options or options.before isnt no after = not options or options.after isnt no defaultValue = before: if before then expectSpaceBefore else unexpectSpaceBefore after: if after then expectSpaceAfter else unexpectSpaceAfter overrides = options?.overrides or {} retv = Object.create null for key in KEYS override = overrides[key] if override thisBefore = if 'before' of override then override.before else before thisAfter = if 'after' of override then override.after else after retv[key] = before: if thisBefore expectSpaceBefore else unexpectSpaceBefore after: if thisAfter then expectSpaceAfter else unexpectSpaceAfter else retv[key] = defaultValue retv checkMethodMap = parseOptions context.options[0] ###* # Reports a given token if usage of spacing followed by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the previous # token to check. # @returns {void} ### checkSpacingBefore = (token, pattern) -> checkMethodMap[token.value].before token, pattern or PREV_TOKEN ###* # Reports a given token if usage of spacing preceded by the token is # invalid. # # @param {Token} token - A token to report. # @param {RegExp|undefined} pattern - Optional. A pattern of the next # token to check. # @returns {void} ### checkSpacingAfter = (token, pattern) -> checkMethodMap[token.value].after token, pattern or NEXT_TOKEN ###* # Reports a given token if usage of spacing around the token is invalid. # # @param {Token} token - A token to report. # @returns {void} ### checkSpacingAround = (token) -> checkSpacingBefore token checkSpacingAfter token ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken and firstToken.type is 'Keyword' checkSpacingAround firstToken ###* # Reports the first token of a given node if the first token is a keyword # and usage of spacing followed by the token is invalid. # # This is used for unary operators (e.g. `typeof`), `function`, and `super`. # Other rules are handling usage of spacing preceded by those keywords. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingBeforeFirstToken = (node) -> firstToken = node and sourceCode.getFirstToken node if firstToken?.type is 'Keyword' checkSpacingBefore firstToken ###* # Reports the previous token of a given node if the token is a keyword and # usage of spacing around the token is invalid. # # @param {ASTNode|null} node - A node to report. # @returns {void} ### checkSpacingAroundTokenBefore = (node) -> if node token = sourceCode.getTokenBefore node, astUtils.isKeywordToken checkSpacingAround token ###* # Reports `async` or `function` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForFunction = (node) -> firstToken = node and sourceCode.getFirstToken node if ( firstToken and ((firstToken.type is 'Keyword' and firstToken.value is 'function') or firstToken.value is 'async') ) checkSpacingBefore firstToken ###* # Reports `class` and `extends` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForClass = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.superClass ###* # Reports `if` and `else` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForIfStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.consequent, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.consequent checkSpacingAround token if token?.value is 'then' if node.alternate token = sourceCode.getTokenBefore( node.alternate astUtils.isKeywordToken ) unless token?.value is 'else' token = sourceCode.getFirstToken node.alternate checkSpacingAround token if token?.value is 'else' ###* # Reports `try`, `catch`, and `finally` keywords of a given node if usage # of spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForTryStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundFirstToken node.handler checkSpacingAroundTokenBefore node.finalizer ###* # Reports `do` and `while` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForDoWhileStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.test checkSpacingForWhileStatement = (node) -> if node.postfix checkSpacingAroundTokenBefore node.test else checkSpacingAroundFirstToken node token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `for` and `in` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForInStatement = (node) -> checkSpacingAroundFirstToken node checkSpacingAroundTokenBefore node.right ###* # Reports `for` and `of` keywords of a given node if usage of spacing # around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForForOfStatement = (node) -> if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.right, astUtils.isNotOpeningParenToken ) checkSpacingForFor = (node) -> if node.postfix # TODO: postfix await, when, by # if node.await # checkSpacingBefore sourceCode.getFirstToken node, 0 # checkSpacingAfter sourceCode.getFirstToken node, 1 # else checkSpacingAround sourceCode.getTokenAfter node.body else if node.await checkSpacingBefore sourceCode.getFirstToken node, 0 checkSpacingAfter sourceCode.getFirstToken node, 1 else checkSpacingAroundFirstToken node checkSpacingAround( sourceCode.getTokenBefore node.source, astUtils.isNotOpeningParenToken ) token = sourceCode.getTokenBefore node.body, astUtils.isKeywordToken unless token?.value is 'then' token = sourceCode.getFirstToken node.body checkSpacingAround token if token?.value is 'then' ###* # Reports `import`, `export`, `as`, and `from` keywords of a given node if # usage of spacing around those keywords is invalid. # # This rule handles the `*` token in module declarations. # # import*as A from "./a"; /*error Expected space(s) after "import". # error Expected space(s) before "as". # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForModuleDeclaration = (node) -> firstToken = sourceCode.getFirstToken node checkSpacingBefore firstToken, PREV_TOKEN_M checkSpacingAfter firstToken, NEXT_TOKEN_M if node.source fromToken = sourceCode.getTokenBefore node.source checkSpacingBefore fromToken, PREV_TOKEN_M checkSpacingAfter fromToken, NEXT_TOKEN_M ###* # Reports `as` keyword of a given node if usage of spacing around this # keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForImportNamespaceSpecifier = (node) -> asToken = sourceCode.getFirstToken node, 1 checkSpacingBefore asToken, PREV_TOKEN_M ###* # Reports `static`, `get`, and `set` keywords of a given node if usage of # spacing around those keywords is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForProperty = (node) -> if node.static then checkSpacingAroundFirstToken node # if ( # node.kind in ['get', 'set'] or # ((node.method or node.type is 'MethodDefinition') and node.value.async) # ) # token = sourceCode.getTokenBefore node.key, (tok) -> # switch tok.value # when 'get', 'set', 'async' # return yes # else # return no # unless token # throw new Error( # 'Failed to find token get, set, or async beside method name' # ) # checkSpacingAround token ###* # Reports `await` keyword of a given node if usage of spacing before # this keyword is invalid. # # @param {ASTNode} node - A node to report. # @returns {void} ### checkSpacingForAwaitExpression = (node) -> checkSpacingBefore sourceCode.getFirstToken node # Statements DebuggerStatement: checkSpacingAroundFirstToken WithStatement: checkSpacingAroundFirstToken # Statements - Control flow BreakStatement: checkSpacingAroundFirstToken ContinueStatement: checkSpacingAroundFirstToken ReturnStatement: checkSpacingAroundFirstToken ThrowStatement: checkSpacingAroundFirstToken TryStatement: checkSpacingForTryStatement # Statements - Choice IfStatement: checkSpacingForIfStatement ConditionalExpression: checkSpacingForIfStatement SwitchStatement: checkSpacingAroundFirstToken SwitchCase: checkSpacingAroundFirstToken # Statements - Loops DoWhileStatement: checkSpacingForDoWhileStatement ForInStatement: checkSpacingForForInStatement ForOfStatement: checkSpacingForForOfStatement For: checkSpacingForFor ForStatement: checkSpacingAroundFirstToken WhileStatement: checkSpacingForWhileStatement # Statements - Declarations ClassDeclaration: checkSpacingForClass ExportNamedDeclaration: checkSpacingForModuleDeclaration ExportDefaultDeclaration: checkSpacingAroundFirstToken ExportAllDeclaration: checkSpacingForModuleDeclaration FunctionDeclaration: checkSpacingForFunction ImportDeclaration: checkSpacingForModuleDeclaration VariableDeclaration: checkSpacingAroundFirstToken # Expressions ArrowFunctionExpression: checkSpacingForFunction AwaitExpression: checkSpacingForAwaitExpression ClassExpression: checkSpacingForClass FunctionExpression: checkSpacingForFunction NewExpression: checkSpacingBeforeFirstToken Super: checkSpacingBeforeFirstToken ThisExpression: checkSpacingBeforeFirstToken UnaryExpression: checkSpacingAroundFirstToken YieldExpression: checkSpacingBeforeFirstToken # Others ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier MethodDefinition: checkSpacingForProperty Property: checkSpacingForProperty
[ { "context": "asic\"\n username: options.username\n password: options.password\n\n githubStr = JSON.stringify\n username: optio", "end": 621, "score": 0.9988429546356201, "start": 605, "tag": "PASSWORD", "value": "options.password" }, { "context": ".username\n module.exp...
lib/utils/gitApi.coffee
yezhiming/atom-chameleon
3
Q = require 'q' request = require 'request' GitHubApi = require 'github' {exec} = require 'child_process' {EOL} = require 'os' fse = require 'fs-extra' fs = require 'fs' github = null # api.github.com github_init = -> github = new GitHubApi # required version: '3.0.0' # optional debug: false timeout: 30000 headers: 'user-agent': 'chameleon-ide' # TODO 获取解密的密码重新认证 github_authenticate() github_authenticate = (options) -> console.log "#{options.username}: github is authenticating..." github.authenticate type: "basic" username: options.username password: options.password githubStr = JSON.stringify username: options.username safe: true localStorage.github = githubStr # 可以存储加密的密码 # gogs模拟登入获取cookies gogs_login = (options) -> if options.username and options.password module.exports.gogsClient.username = options.username module.exports.gogsClient.password = options.password else options.username = module.exports.gogsClient.username options.password = module.exports.gogsClient.password Q.Promise (resolve, reject, notify) -> console.log "gogs authenticate: POST #{module.exports.gogsApi}/user/login" request.post url: "#{module.exports.gogsApi}/user/login" form: uname: options.username password: options.password , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 502 e = new Error 'The server is upgrading, please wait...' e.code = 502 reject(e) else if httpResponse.statusCode is 200 and body.contains('Need an account? Sign up now.') e = new Error 'Account and password is wrong, please enter it correctly...' e.code = 401 reject(e) else localStorage.gogs = JSON.stringify username: options.username resolve(httpResponse.headers['set-cookie']) # gogs模拟登入获取csrf gogs_csrf = (cookies) -> Q.Promise (resolve, reject, notify) -> console.log "gogs fetch csrf: GET #{module.exports.gogsApi}/" request.get headers: Cookie: cookies url: "#{module.exports.gogsApi}/" , (err, httpResponse, body) -> reject(err) if err try uname = httpResponse.toJSON().body uname = uname.substr uname.indexOf '<li class=\"right\" id=\"header-nav-user\">' uname = uname.substring uname.indexOf('<a href=\"\/') + '<a href=\"\/'.length, uname.indexOf('\" class=\"text-bold\">') console.log "截取html用户名:#{uname}" # _csrf=VWBBF6oKsv33n5xGtW6sxUmrh5g6MTQyMjM0Njk5NTAzNzEzNTcwNA==; Path=/ csrf = httpResponse.toJSON().headers['set-cookie'][0].split(';')[0].split('=')[1] if csrf.length >= 60 or csrf.contains '%3D' csrf = csrf.replace(/%3D/g, '=') else csrf = "#{csrf}==" console.log "_csrf: #{csrf}" resolve login: uname cookies: cookies csrf: csrf catch e reject e # gogs生成accessToken gogs_authenticate = (msg) -> Q.Promise (resolve, reject, notify) -> gogs = JSON.parse localStorage.getItem 'gogs' if gogs.token resolve(gogs.token) else console.log "gogs create token: POST #{module.exports.gogsApi}/user/settings/applications" # console.log msg request.post url: "#{module.exports.gogsApi}/user/settings/applications" headers: Cookie: msg.cookies form: type: 'token' name: 'chameloenIDE(Mistaken delete!)' _csrf: msg.csrf , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 400 e = new Error 'system will be fix, please wailt...' e.code = 401 reject(e) else if httpResponse.statusCode is 302 # decodeURIComponent 解码url macaron_flash = decodeURIComponent httpResponse.toJSON().headers['set-cookie'][1] token = macaron_flash.split('&success')[0].replace 'macaron_flash=info=', '' console.log "token: #{token}" # 缓存token,不必每次都去获取 gogs['token'] = token gogs['login'] = msg.login localStorage.setItem('gogs', JSON.stringify gogs) resolve(token) module.exports = gogsClient: {}, # https://bsl.foreveross.com/gogs(8001) # gogsApi: 'http://172.16.1.27:3000', gogsProtocol: "http://", gogsApi: "#{module.exports.gogsProtocol}115.28.1.109:8001", # 生成默认的公、密钥到userhome/.ssh generateKeyPair: (options) -> Q.Promise (resolve, reject, notify) -> # 遵循ssh-kengen规范 fse.ensureDirSync "#{options.home}/.ssh" # 关闭确认公钥设置 if (!fs.existsSync "#{options.home}/.ssh/config") or (!fs.readFileSync "#{options.home}/.ssh/config", encoding: 'utf8'.contains 'StrictHostKeyChecking no') fs.appendFileSync "#{options.home}/.ssh/config", "#{EOL}StrictHostKeyChecking no#{EOL}UserKnownHostsFile /dev/null#{EOL}" msg = {} if fs.existsSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub" console.log 'reset rsa KeyPair...' pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg return resolve(pubKey) # 生成默认的公、密钥到userhome/.ssh console.log 'generating rsa KeyPair...' # 根据github规则,公钥名称暂时写死id_rsa cp = exec "ssh-keygen -t rsa -C #{options.username}@github.com -f #{options.home}/.ssh/id_rsa_#{options.username} -N ''", options.option, (error, stdout, stderr) -> if error reject(error) else console.log stdout.toString() console.log stderr.toString() pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg resolve(pubKey) github: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> console.log "github fetch user..." github.user.get msg, (err, data) -> if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 return reject(err) resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.key or msg.title reject new Error 'params: title (String): Required and key (String): Required.' console.log "github creates ssh key..." github.user.createKey msg, (err, data) -> if (err and err.message.indexOf 'key is already in use' != -1) or !err keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_gitHubFlag"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj resolve result: true message: data type: 'github' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@github.com", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'github' # else # resolve # result: true # message: stdout.toString() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 reject(err) else github_authenticate msg.options callMyself(msg) # 如果仓库已经存在,则返回错误 createRepos: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.name reject new Error 'params: name (String): Required.' console.log "github creates repos..." github.repos.create msg, (err, data) -> if err and err.toJSON().code is 422 and (err.toJSON().message.indexOf 'name already exists on this account') != -1 reject err # resolve # result: false # message: err.toJSON() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem 'github' reject(err) else resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) gogs: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' if gogs Q.Promise (resolve, reject, notify) -> resolve result: true message: gogs.login type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and msg.cookies console.log "gogs creates ssh key: POST #{module.exports.gogsApi}/user/settings/ssh" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/user/settings/ssh" headers: Cookie: msg.cookies form: title: msg.title content: msg.content _csrf: msg.csrf , (err, httpResponse, body) -> return reject(err) if err # 不管服务器是否存在key则只要用户不删除本地的公钥密钥对即可 keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_gogsFlag"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj if httpResponse.statusCode is 302 resolve result: true message: body type: 'gogs' else if httpResponse.statusCode is 200 or body.contains 'SSH 密钥已经被使用。' resolve result: false message: body type: 'gogs' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@#{module.exports.gogsApi.replace('https://', '')}", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'gogs' # else # resolve # result: true # message: stdout.toString() # type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> msg.cookies = obj.cookies msg.csrf = obj.csrf callMyself msg # 如果仓库已经存在,则api自动提示 createRepos: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and gogs.token console.log "gogs creates repos: POST #{module.exports.gogsApi}/api/v1/user/repos" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/api/v1/user/repos" headers: Authorization: "token #{gogs.token}" 'Content-Type': 'application/json; charset=utf8' json: true body: msg , (err, httpResponse, body) -> reject(err) if err if httpResponse.statusCode is 403 localStorage.removeItem('gogs') # localStorage 仅限制再atom上可以使用,因为是window属性 reject new Error 'code: 422 , message: Invalid token.' else if httpResponse.statusCode is 422 resolve result: false message: body type: 'gogs' else if httpResponse.statusCode is 200 resolve result: true message: body type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg)
133236
Q = require 'q' request = require 'request' GitHubApi = require 'github' {exec} = require 'child_process' {EOL} = require 'os' fse = require 'fs-extra' fs = require 'fs' github = null # api.github.com github_init = -> github = new GitHubApi # required version: '3.0.0' # optional debug: false timeout: 30000 headers: 'user-agent': 'chameleon-ide' # TODO 获取解密的密码重新认证 github_authenticate() github_authenticate = (options) -> console.log "#{options.username}: github is authenticating..." github.authenticate type: "basic" username: options.username password: <PASSWORD> githubStr = JSON.stringify username: options.username safe: true localStorage.github = githubStr # 可以存储加密的密码 # gogs模拟登入获取cookies gogs_login = (options) -> if options.username and options.password module.exports.gogsClient.username = options.username module.exports.gogsClient.password = <PASSWORD> else options.username = module.exports.gogsClient.username options.password = <PASSWORD> Q.Promise (resolve, reject, notify) -> console.log "gogs authenticate: POST #{module.exports.gogsApi}/user/login" request.post url: "#{module.exports.gogsApi}/user/login" form: uname: options.username password: <PASSWORD> , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 502 e = new Error 'The server is upgrading, please wait...' e.code = 502 reject(e) else if httpResponse.statusCode is 200 and body.contains('Need an account? Sign up now.') e = new Error 'Account and password is wrong, please enter it correctly...' e.code = 401 reject(e) else localStorage.gogs = JSON.stringify username: options.username resolve(httpResponse.headers['set-cookie']) # gogs模拟登入获取csrf gogs_csrf = (cookies) -> Q.Promise (resolve, reject, notify) -> console.log "gogs fetch csrf: GET #{module.exports.gogsApi}/" request.get headers: Cookie: cookies url: "#{module.exports.gogsApi}/" , (err, httpResponse, body) -> reject(err) if err try uname = httpResponse.toJSON().body uname = uname.substr uname.indexOf '<li class=\"right\" id=\"header-nav-user\">' uname = uname.substring uname.indexOf('<a href=\"\/') + '<a href=\"\/'.length, uname.indexOf('\" class=\"text-bold\">') console.log "截取html用户名:#{uname}" # _csrf=VWBBF6oKsv33n5xGtW6sxUmrh5g6MTQyMjM0Njk5NTAzNzEzNTcwNA==; Path=/ csrf = httpResponse.toJSON().headers['set-cookie'][0].split(';')[0].split('=')[1] if csrf.length >= 60 or csrf.contains '%3D' csrf = csrf.replace(/%3D/g, '=') else csrf = "#{csrf}==" console.log "_csrf: #{csrf}" resolve login: uname cookies: cookies csrf: csrf catch e reject e # gogs生成accessToken gogs_authenticate = (msg) -> Q.Promise (resolve, reject, notify) -> gogs = JSON.parse localStorage.getItem 'gogs' if gogs.token resolve(gogs.token) else console.log "gogs create token: POST #{module.exports.gogsApi}/user/settings/applications" # console.log msg request.post url: "#{module.exports.gogsApi}/user/settings/applications" headers: Cookie: msg.cookies form: type: 'token' name: 'chameloenIDE(Mistaken delete!)' _csrf: msg.csrf , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 400 e = new Error 'system will be fix, please wailt...' e.code = 401 reject(e) else if httpResponse.statusCode is 302 # decodeURIComponent 解码url macaron_flash = decodeURIComponent httpResponse.toJSON().headers['set-cookie'][1] token = macaron_flash.split('&success')[0].replace 'macaron_flash=info=', '' console.log "token: #{token}" # 缓存token,不必每次都去获取 gogs['token'] = token gogs['login'] = msg.login localStorage.setItem('gogs', JSON.stringify gogs) resolve(token) module.exports = gogsClient: {}, # https://bsl.foreveross.com/gogs(8001) # gogsApi: 'http://172.16.1.27:3000', gogsProtocol: "http://", gogsApi: "#{module.exports.gogsProtocol}192.168.127.12:8001", # 生成默认的公、密钥到userhome/.ssh generateKeyPair: (options) -> Q.Promise (resolve, reject, notify) -> # 遵循ssh-kengen规范 fse.ensureDirSync "#{options.home}/.ssh" # 关闭确认公钥设置 if (!fs.existsSync "#{options.home}/.ssh/config") or (!fs.readFileSync "#{options.home}/.ssh/config", encoding: 'utf8'.contains 'StrictHostKeyChecking no') fs.appendFileSync "#{options.home}/.ssh/config", "#{EOL}StrictHostKeyChecking no#{EOL}UserKnownHostsFile /dev/null#{EOL}" msg = {} if fs.existsSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub" console.log 'reset rsa KeyPair...' pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg return resolve(pubKey) # 生成默认的公、密钥到userhome/.ssh console.log 'generating rsa KeyPair...' # 根据github规则,公钥名称暂时写死id_rsa cp = exec "ssh-keygen -t rsa -C #{options.username}@github.com -f #{options.home}/.ssh/id_rsa_#{options.username} -N ''", options.option, (error, stdout, stderr) -> if error reject(error) else console.log stdout.toString() console.log stderr.toString() pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg resolve(pubKey) github: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> console.log "github fetch user..." github.user.get msg, (err, data) -> if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 return reject(err) resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.key or msg.title reject new Error 'params: title (String): Required and key (String): Required.' console.log "github creates ssh key..." github.user.createKey msg, (err, data) -> if (err and err.message.indexOf 'key is already in use' != -1) or !err keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_gitHubFlag"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj resolve result: true message: data type: 'github' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@github.com", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'github' # else # resolve # result: true # message: stdout.toString() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 reject(err) else github_authenticate msg.options callMyself(msg) # 如果仓库已经存在,则返回错误 createRepos: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.name reject new Error 'params: name (String): Required.' console.log "github creates repos..." github.repos.create msg, (err, data) -> if err and err.toJSON().code is 422 and (err.toJSON().message.indexOf 'name already exists on this account') != -1 reject err # resolve # result: false # message: err.toJSON() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem 'github' reject(err) else resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) gogs: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' if gogs Q.Promise (resolve, reject, notify) -> resolve result: true message: gogs.login type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and msg.cookies console.log "gogs creates ssh key: POST #{module.exports.gogsApi}/user/settings/ssh" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/user/settings/ssh" headers: Cookie: msg.cookies form: title: msg.title content: msg.content _csrf: msg.csrf , (err, httpResponse, body) -> return reject(err) if err # 不管服务器是否存在key则只要用户不删除本地的公钥密钥对即可 keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_g<KEY>"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj if httpResponse.statusCode is 302 resolve result: true message: body type: 'gogs' else if httpResponse.statusCode is 200 or body.contains 'SSH 密钥已经被使用。' resolve result: false message: body type: 'gogs' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@#{module.exports.gogsApi.replace('https://', '')}", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'gogs' # else # resolve # result: true # message: stdout.toString() # type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> msg.cookies = obj.cookies msg.csrf = obj.csrf callMyself msg # 如果仓库已经存在,则api自动提示 createRepos: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and gogs.token console.log "gogs creates repos: POST #{module.exports.gogsApi}/api/v1/user/repos" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/api/v1/user/repos" headers: Authorization: "token #{gogs.token}" 'Content-Type': 'application/json; charset=utf8' json: true body: msg , (err, httpResponse, body) -> reject(err) if err if httpResponse.statusCode is 403 localStorage.removeItem('gogs') # localStorage 仅限制再atom上可以使用,因为是window属性 reject new Error 'code: 422 , message: Invalid token.' else if httpResponse.statusCode is 422 resolve result: false message: body type: 'gogs' else if httpResponse.statusCode is 200 resolve result: true message: body type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg)
true
Q = require 'q' request = require 'request' GitHubApi = require 'github' {exec} = require 'child_process' {EOL} = require 'os' fse = require 'fs-extra' fs = require 'fs' github = null # api.github.com github_init = -> github = new GitHubApi # required version: '3.0.0' # optional debug: false timeout: 30000 headers: 'user-agent': 'chameleon-ide' # TODO 获取解密的密码重新认证 github_authenticate() github_authenticate = (options) -> console.log "#{options.username}: github is authenticating..." github.authenticate type: "basic" username: options.username password: PI:PASSWORD:<PASSWORD>END_PI githubStr = JSON.stringify username: options.username safe: true localStorage.github = githubStr # 可以存储加密的密码 # gogs模拟登入获取cookies gogs_login = (options) -> if options.username and options.password module.exports.gogsClient.username = options.username module.exports.gogsClient.password = PI:PASSWORD:<PASSWORD>END_PI else options.username = module.exports.gogsClient.username options.password = PI:PASSWORD:<PASSWORD>END_PI Q.Promise (resolve, reject, notify) -> console.log "gogs authenticate: POST #{module.exports.gogsApi}/user/login" request.post url: "#{module.exports.gogsApi}/user/login" form: uname: options.username password: PI:PASSWORD:<PASSWORD>END_PI , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 502 e = new Error 'The server is upgrading, please wait...' e.code = 502 reject(e) else if httpResponse.statusCode is 200 and body.contains('Need an account? Sign up now.') e = new Error 'Account and password is wrong, please enter it correctly...' e.code = 401 reject(e) else localStorage.gogs = JSON.stringify username: options.username resolve(httpResponse.headers['set-cookie']) # gogs模拟登入获取csrf gogs_csrf = (cookies) -> Q.Promise (resolve, reject, notify) -> console.log "gogs fetch csrf: GET #{module.exports.gogsApi}/" request.get headers: Cookie: cookies url: "#{module.exports.gogsApi}/" , (err, httpResponse, body) -> reject(err) if err try uname = httpResponse.toJSON().body uname = uname.substr uname.indexOf '<li class=\"right\" id=\"header-nav-user\">' uname = uname.substring uname.indexOf('<a href=\"\/') + '<a href=\"\/'.length, uname.indexOf('\" class=\"text-bold\">') console.log "截取html用户名:#{uname}" # _csrf=VWBBF6oKsv33n5xGtW6sxUmrh5g6MTQyMjM0Njk5NTAzNzEzNTcwNA==; Path=/ csrf = httpResponse.toJSON().headers['set-cookie'][0].split(';')[0].split('=')[1] if csrf.length >= 60 or csrf.contains '%3D' csrf = csrf.replace(/%3D/g, '=') else csrf = "#{csrf}==" console.log "_csrf: #{csrf}" resolve login: uname cookies: cookies csrf: csrf catch e reject e # gogs生成accessToken gogs_authenticate = (msg) -> Q.Promise (resolve, reject, notify) -> gogs = JSON.parse localStorage.getItem 'gogs' if gogs.token resolve(gogs.token) else console.log "gogs create token: POST #{module.exports.gogsApi}/user/settings/applications" # console.log msg request.post url: "#{module.exports.gogsApi}/user/settings/applications" headers: Cookie: msg.cookies form: type: 'token' name: 'chameloenIDE(Mistaken delete!)' _csrf: msg.csrf , (err, httpResponse, body) -> if err reject(err) else if httpResponse.statusCode is 400 e = new Error 'system will be fix, please wailt...' e.code = 401 reject(e) else if httpResponse.statusCode is 302 # decodeURIComponent 解码url macaron_flash = decodeURIComponent httpResponse.toJSON().headers['set-cookie'][1] token = macaron_flash.split('&success')[0].replace 'macaron_flash=info=', '' console.log "token: #{token}" # 缓存token,不必每次都去获取 gogs['token'] = token gogs['login'] = msg.login localStorage.setItem('gogs', JSON.stringify gogs) resolve(token) module.exports = gogsClient: {}, # https://bsl.foreveross.com/gogs(8001) # gogsApi: 'http://172.16.1.27:3000', gogsProtocol: "http://", gogsApi: "#{module.exports.gogsProtocol}PI:IP_ADDRESS:192.168.127.12END_PI:8001", # 生成默认的公、密钥到userhome/.ssh generateKeyPair: (options) -> Q.Promise (resolve, reject, notify) -> # 遵循ssh-kengen规范 fse.ensureDirSync "#{options.home}/.ssh" # 关闭确认公钥设置 if (!fs.existsSync "#{options.home}/.ssh/config") or (!fs.readFileSync "#{options.home}/.ssh/config", encoding: 'utf8'.contains 'StrictHostKeyChecking no') fs.appendFileSync "#{options.home}/.ssh/config", "#{EOL}StrictHostKeyChecking no#{EOL}UserKnownHostsFile /dev/null#{EOL}" msg = {} if fs.existsSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub" console.log 'reset rsa KeyPair...' pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg return resolve(pubKey) # 生成默认的公、密钥到userhome/.ssh console.log 'generating rsa KeyPair...' # 根据github规则,公钥名称暂时写死id_rsa cp = exec "ssh-keygen -t rsa -C #{options.username}@github.com -f #{options.home}/.ssh/id_rsa_#{options.username} -N ''", options.option, (error, stdout, stderr) -> if error reject(error) else console.log stdout.toString() console.log stderr.toString() pubKey = fs.readFileSync "#{options.home}/.ssh/id_rsa_#{options.username}.pub", encoding:'utf8' msg.public = pubKey localStorage["#{options.username}_installedSshKey"] = JSON.stringify msg resolve(pubKey) github: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> console.log "github fetch user..." github.user.get msg, (err, data) -> if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 return reject(err) resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.key or msg.title reject new Error 'params: title (String): Required and key (String): Required.' console.log "github creates ssh key..." github.user.createKey msg, (err, data) -> if (err and err.message.indexOf 'key is already in use' != -1) or !err keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_gitHubFlag"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj resolve result: true message: data type: 'github' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@github.com", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'github' # else # resolve # result: true # message: stdout.toString() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem('github') # localStorage 仅限制再atom上可以使用,因为是window属性 reject(err) else github_authenticate msg.options callMyself(msg) # 如果仓库已经存在,则返回错误 createRepos: (msg) -> callMyself = arguments.callee github_init() unless github githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库 if githubObj and githubObj.safe Q.Promise (resolve, reject, notify) -> unless msg.name reject new Error 'params: name (String): Required.' console.log "github creates repos..." github.repos.create msg, (err, data) -> if err and err.toJSON().code is 422 and (err.toJSON().message.indexOf 'name already exists on this account') != -1 reject err # resolve # result: false # message: err.toJSON() # type: 'github' else if err # eg:用户输错帐号密码重新验证 Etc. localStorage.removeItem 'github' reject(err) else resolve result: true message: data type: 'github' else github_authenticate msg.options callMyself(msg) gogs: -> # 获取用户信息 getUser: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' if gogs Q.Promise (resolve, reject, notify) -> resolve result: true message: gogs.login type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg) # 上传公钥到服务器 createSshKey: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and msg.cookies console.log "gogs creates ssh key: POST #{module.exports.gogsApi}/user/settings/ssh" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/user/settings/ssh" headers: Cookie: msg.cookies form: title: msg.title content: msg.content _csrf: msg.csrf , (err, httpResponse, body) -> return reject(err) if err # 不管服务器是否存在key则只要用户不删除本地的公钥密钥对即可 keyObj = JSON.parse localStorage.getItem "#{msg.options.username}_installedSshKey" keyObj["#{msg.options.username}_gPI:KEY:<KEY>END_PI"] = true localStorage["#{msg.options.username}_installedSshKey"] = JSON.stringify keyObj if httpResponse.statusCode is 302 resolve result: true message: body type: 'gogs' else if httpResponse.statusCode is 200 or body.contains 'SSH 密钥已经被使用。' resolve result: false message: body type: 'gogs' # 校验keypair # home = process.env.USERPROFILE || process.env.HOME || process.env.HOMEPATH # option = # maxBuffer: 1024*1024*1 # option.env = path: atom.config.get('atom-chameleon.gitCloneEnvironmentPath') if atom.config.get('atom-chameleon.gitCloneEnvironmentPath') # 一般mac不需要配置 # exec "eval \"$(ssh-agent -s)\" && ssh-add #{home}/.ssh/id_rsa_#{msg.options.username} && ssh -T git@#{module.exports.gogsApi.replace('https://', '')}", option, (error, stdout, stderr) -> # console.log('Program stdout: %s', stdout.toString()) # console.log('Program stderr: %s', stderr.toString()) # if error # resolve # result: false # message: stderr.toString() # type: 'gogs' # else # resolve # result: true # message: stdout.toString() # type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> msg.cookies = obj.cookies msg.csrf = obj.csrf callMyself msg # 如果仓库已经存在,则api自动提示 createRepos: (msg) -> callMyself = arguments.callee gogs = JSON.parse localStorage.getItem 'gogs' # 匹配是否同一个用户的token后开始创建仓库 if gogs and gogs.token console.log "gogs creates repos: POST #{module.exports.gogsApi}/api/v1/user/repos" Q.Promise (resolve, reject, notify) -> request method: 'POST' url: "#{module.exports.gogsApi}/api/v1/user/repos" headers: Authorization: "token #{gogs.token}" 'Content-Type': 'application/json; charset=utf8' json: true body: msg , (err, httpResponse, body) -> reject(err) if err if httpResponse.statusCode is 403 localStorage.removeItem('gogs') # localStorage 仅限制再atom上可以使用,因为是window属性 reject new Error 'code: 422 , message: Invalid token.' else if httpResponse.statusCode is 422 resolve result: false message: body type: 'gogs' else if httpResponse.statusCode is 200 resolve result: true message: body type: 'gogs' else gogs_login(msg.options) .then (cookies) -> gogs_csrf cookies .then (obj) -> gogs_authenticate obj .then (token) -> callMyself(msg)
[ { "context": "ew.$el.html '<input>'\n @view.$('input').val 'Lemuria'\n @view.once 'location:update', (location) -", "end": 2433, "score": 0.9751976132392883, "start": 2426, "tag": "NAME", "value": "Lemuria" }, { "context": " (location) ->\n location.should.eql name: ...
src/desktop/components/location_search/test/location_search.coffee
kanaabe/force
1
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' LocationSearchView = benv.requireWithJadeify(resolve(__dirname, '../index'), ['template']) describe 'Location Search', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' google: sinon.stub() Backbone.$ = $ LocationSearchView.__set__ 'geo', loadGoogleMaps: (cb) -> cb() @google = maps: places: Autocomplete: sinon.stub() event: addListener: sinon.stub() addDomListener: sinon.stub() LocationSearchView.__set__ 'google', @google @view = new LocationSearchView done() afterEach -> benv.teardown() it 'should render the template', -> @view.render().$el.html().should.containEql 'Enter your city' it 'should render with a current value', -> value = "New York, NY, United States" @view.render(value).$el.html().should.containEql value it 'attach Google Maps specific event listeners', -> @view.render() @google.maps.event.addListener.args[0][1].should.equal 'place_changed' @google.maps.event.addDomListener.args[0][1].should.equal 'keydown' it 'should announce it\'s location', (done) -> @view.once 'location:update', -> done() @view.announce {} describe '#determineAutofocus', -> it 'should set the appropriate autofocus attribute', -> LocationSearchView.__set__ 'isTouchDevice', -> false new LocationSearchView().determineAutofocus().should.be.true() it 'should accept options', -> LocationSearchView.__set__ 'isTouchDevice', -> false _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() new LocationSearchView(autofocus: true).determineAutofocus().should.be.true() it 'should handle touch devices', -> LocationSearchView.__set__ 'isTouchDevice', -> true _.isUndefined(new LocationSearchView().determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: true).determineAutofocus()).should.be.true() describe '#preAnnounce', -> it 'should announce a named location string when the input is blurred', (done) -> @view.$el.html '<input>' @view.$('input').val 'Lemuria' @view.once 'location:update', (location) -> location.should.eql name: 'Lemuria' done() @view.$('input').trigger 'blur'
189265
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' LocationSearchView = benv.requireWithJadeify(resolve(__dirname, '../index'), ['template']) describe 'Location Search', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' google: sinon.stub() Backbone.$ = $ LocationSearchView.__set__ 'geo', loadGoogleMaps: (cb) -> cb() @google = maps: places: Autocomplete: sinon.stub() event: addListener: sinon.stub() addDomListener: sinon.stub() LocationSearchView.__set__ 'google', @google @view = new LocationSearchView done() afterEach -> benv.teardown() it 'should render the template', -> @view.render().$el.html().should.containEql 'Enter your city' it 'should render with a current value', -> value = "New York, NY, United States" @view.render(value).$el.html().should.containEql value it 'attach Google Maps specific event listeners', -> @view.render() @google.maps.event.addListener.args[0][1].should.equal 'place_changed' @google.maps.event.addDomListener.args[0][1].should.equal 'keydown' it 'should announce it\'s location', (done) -> @view.once 'location:update', -> done() @view.announce {} describe '#determineAutofocus', -> it 'should set the appropriate autofocus attribute', -> LocationSearchView.__set__ 'isTouchDevice', -> false new LocationSearchView().determineAutofocus().should.be.true() it 'should accept options', -> LocationSearchView.__set__ 'isTouchDevice', -> false _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() new LocationSearchView(autofocus: true).determineAutofocus().should.be.true() it 'should handle touch devices', -> LocationSearchView.__set__ 'isTouchDevice', -> true _.isUndefined(new LocationSearchView().determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: true).determineAutofocus()).should.be.true() describe '#preAnnounce', -> it 'should announce a named location string when the input is blurred', (done) -> @view.$el.html '<input>' @view.$('input').val '<NAME>' @view.once 'location:update', (location) -> location.should.eql name: '<NAME>' done() @view.$('input').trigger 'blur'
true
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' LocationSearchView = benv.requireWithJadeify(resolve(__dirname, '../index'), ['template']) describe 'Location Search', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' google: sinon.stub() Backbone.$ = $ LocationSearchView.__set__ 'geo', loadGoogleMaps: (cb) -> cb() @google = maps: places: Autocomplete: sinon.stub() event: addListener: sinon.stub() addDomListener: sinon.stub() LocationSearchView.__set__ 'google', @google @view = new LocationSearchView done() afterEach -> benv.teardown() it 'should render the template', -> @view.render().$el.html().should.containEql 'Enter your city' it 'should render with a current value', -> value = "New York, NY, United States" @view.render(value).$el.html().should.containEql value it 'attach Google Maps specific event listeners', -> @view.render() @google.maps.event.addListener.args[0][1].should.equal 'place_changed' @google.maps.event.addDomListener.args[0][1].should.equal 'keydown' it 'should announce it\'s location', (done) -> @view.once 'location:update', -> done() @view.announce {} describe '#determineAutofocus', -> it 'should set the appropriate autofocus attribute', -> LocationSearchView.__set__ 'isTouchDevice', -> false new LocationSearchView().determineAutofocus().should.be.true() it 'should accept options', -> LocationSearchView.__set__ 'isTouchDevice', -> false _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() new LocationSearchView(autofocus: true).determineAutofocus().should.be.true() it 'should handle touch devices', -> LocationSearchView.__set__ 'isTouchDevice', -> true _.isUndefined(new LocationSearchView().determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: false).determineAutofocus()).should.be.true() _.isUndefined(new LocationSearchView(autofocus: true).determineAutofocus()).should.be.true() describe '#preAnnounce', -> it 'should announce a named location string when the input is blurred', (done) -> @view.$el.html '<input>' @view.$('input').val 'PI:NAME:<NAME>END_PI' @view.once 'location:update', (location) -> location.should.eql name: 'PI:NAME:<NAME>END_PI' done() @view.$('input').trigger 'blur'
[ { "context": "l 3\n Users.identify [{user_id: 3, username: 'my_username'}], (err, userId) ->\n should.not.exist err", "end": 986, "score": 0.9995508193969727, "start": 975, "tag": "USERNAME", "value": "my_username" }, { "context": "ame', (next) ->\n Users.create\n ...
test/identify.coffee
wdavidw/node-ron
14
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'id', -> it 'Test id # number', (next) -> Users.identify 3, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [3], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.user_id', (next) -> Users.identify {user_id: 3}, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [{user_id: 3, username: 'my_username'}], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.username', (next) -> Users.create username: 'my_username', email: 'my@email.com', password: 'my_password' , (err, user) -> # Pass an object Users.identify {username: 'my_username'}, (err, userId) -> should.not.exist err userId.should.eql user.user_id # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], (err, userId) -> should.not.exist err userId.should.eql [1, user.user_id, 2] Users.clear next it 'Test id # invalid object empty', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.identify [1, {}, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.identify {}, (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.clear next it 'Test id # missing unique', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: 'my1@mail.com' } { username: 'my_username_2', email: 'my2@mail.com' } ], (err, users) -> # Test return id Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], (err, result) -> result[0].should.eql users[1].user_id result[1].should.eql users[0].user_id should.not.exist result[2] Users.clear next it 'Test id # missing unique + option object', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: 'my1@mail.com' } { username: 'my_username_2', email: 'my2@mail.com' } ], (err, users) -> Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], {object: true}, (err, result) -> # Test return object result[0].user_id.should.eql users[1].user_id result[1].user_id.should.eql users[0].user_id should.not.exist result[2].user_id Users.clear next it 'Test id # invalid type id', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, true, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid id, got true' Users.identify false, (err, user) -> err.message.should.eql 'Invalid id, got false' Users.clear next it 'Test id # invalid type null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], (err, users) -> err.message.should.eql 'Null record' Users.identify null, (err, user) -> err.message.should.eql 'Null record' Users.clear next it 'Test id # accept null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], {accept_null: true}, (err, users) -> should.not.exist err users.length.should.eql 3 should.exist users[0] should.not.exist users[1] should.exist users[2] # Test null Users.identify null, {accept_null: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # accept null return object', (next) -> # Same test than 'Test id # accept null' with the 'object' option Users.identify [1, null, {user_id: 2}], {accept_null: true, object: true}, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].user_id.should.eql 1 should.not.exist users[1] users[2].user_id.should.eql 2 # Test null Users.identify null, {accept_null: true, object: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # id return object', (next) -> Users.create { username: 'my_username' email: 'my@email.com' password: 'my_password' }, (err, orgUser) -> # Pass an id Users.identify orgUser.user_id, {object: true}, (err, user) -> should.not.exist err user.should.eql {user_id: orgUser.user_id} # Pass an array of ids Users.identify [orgUser.user_id, orgUser.user_id], {object: true}, (err, user) -> user.should.eql [{user_id: orgUser.user_id}, {user_id: orgUser.user_id}] Users.clear next it 'Test id # unique + option object', (next) -> Users.create { username: 'my_username' email: 'my@email.com' password: 'my_password' }, (err, orgUser) -> # Pass an object Users.identify {username: 'my_username'}, {object: true}, (err, user) -> should.not.exist err user.should.eql {username: 'my_username', user_id: orgUser.user_id} # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], {object: true}, (err, user) -> should.not.exist err user.should.eql [{user_id: 1}, {username: 'my_username', user_id: orgUser.user_id}, {user_id: 2}] Users.clear next
222734
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'id', -> it 'Test id # number', (next) -> Users.identify 3, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [3], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.user_id', (next) -> Users.identify {user_id: 3}, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [{user_id: 3, username: 'my_username'}], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.username', (next) -> Users.create username: 'my_username', email: '<EMAIL>', password: '<PASSWORD>' , (err, user) -> # Pass an object Users.identify {username: 'my_username'}, (err, userId) -> should.not.exist err userId.should.eql user.user_id # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], (err, userId) -> should.not.exist err userId.should.eql [1, user.user_id, 2] Users.clear next it 'Test id # invalid object empty', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.identify [1, {}, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.identify {}, (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.clear next it 'Test id # missing unique', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: '<EMAIL>' } { username: 'my_username_2', email: '<EMAIL>' } ], (err, users) -> # Test return id Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], (err, result) -> result[0].should.eql users[1].user_id result[1].should.eql users[0].user_id should.not.exist result[2] Users.clear next it 'Test id # missing unique + option object', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: '<EMAIL>' } { username: 'my_username_2', email: '<EMAIL>' } ], (err, users) -> Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], {object: true}, (err, result) -> # Test return object result[0].user_id.should.eql users[1].user_id result[1].user_id.should.eql users[0].user_id should.not.exist result[2].user_id Users.clear next it 'Test id # invalid type id', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, true, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid id, got true' Users.identify false, (err, user) -> err.message.should.eql 'Invalid id, got false' Users.clear next it 'Test id # invalid type null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], (err, users) -> err.message.should.eql 'Null record' Users.identify null, (err, user) -> err.message.should.eql 'Null record' Users.clear next it 'Test id # accept null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], {accept_null: true}, (err, users) -> should.not.exist err users.length.should.eql 3 should.exist users[0] should.not.exist users[1] should.exist users[2] # Test null Users.identify null, {accept_null: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # accept null return object', (next) -> # Same test than 'Test id # accept null' with the 'object' option Users.identify [1, null, {user_id: 2}], {accept_null: true, object: true}, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].user_id.should.eql 1 should.not.exist users[1] users[2].user_id.should.eql 2 # Test null Users.identify null, {accept_null: true, object: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # id return object', (next) -> Users.create { username: 'my_username' email: '<EMAIL>' password: '<PASSWORD>' }, (err, orgUser) -> # Pass an id Users.identify orgUser.user_id, {object: true}, (err, user) -> should.not.exist err user.should.eql {user_id: orgUser.user_id} # Pass an array of ids Users.identify [orgUser.user_id, orgUser.user_id], {object: true}, (err, user) -> user.should.eql [{user_id: orgUser.user_id}, {user_id: orgUser.user_id}] Users.clear next it 'Test id # unique + option object', (next) -> Users.create { username: 'my_username' email: '<EMAIL>' password: '<PASSWORD>' }, (err, orgUser) -> # Pass an object Users.identify {username: 'my_username'}, {object: true}, (err, user) -> should.not.exist err user.should.eql {username: 'my_username', user_id: orgUser.user_id} # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], {object: true}, (err, user) -> should.not.exist err user.should.eql [{user_id: 1}, {username: 'my_username', user_id: orgUser.user_id}, {user_id: 2}] Users.clear next
true
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'id', -> it 'Test id # number', (next) -> Users.identify 3, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [3], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.user_id', (next) -> Users.identify {user_id: 3}, (err, userId) -> should.not.exist err userId.should.eql 3 Users.identify [{user_id: 3, username: 'my_username'}], (err, userId) -> should.not.exist err userId.should.eql [3] Users.clear next it 'Test id # user.username', (next) -> Users.create username: 'my_username', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' , (err, user) -> # Pass an object Users.identify {username: 'my_username'}, (err, userId) -> should.not.exist err userId.should.eql user.user_id # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], (err, userId) -> should.not.exist err userId.should.eql [1, user.user_id, 2] Users.clear next it 'Test id # invalid object empty', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.identify [1, {}, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.identify {}, (err, user) -> err.message.should.eql 'Invalid record, got {}' Users.clear next it 'Test id # missing unique', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: 'PI:EMAIL:<EMAIL>END_PI' } { username: 'my_username_2', email: 'PI:EMAIL:<EMAIL>END_PI' } ], (err, users) -> # Test return id Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], (err, result) -> result[0].should.eql users[1].user_id result[1].should.eql users[0].user_id should.not.exist result[2] Users.clear next it 'Test id # missing unique + option object', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's an empty object Users.create [ { username: 'my_username_1', email: 'PI:EMAIL:<EMAIL>END_PI' } { username: 'my_username_2', email: 'PI:EMAIL:<EMAIL>END_PI' } ], (err, users) -> Users.identify [ { username: users[1].username } # By unique { user_id: users[0].user_id } # By identifier { username: 'who are you' } # Alien ], {object: true}, (err, result) -> # Test return object result[0].user_id.should.eql users[1].user_id result[1].user_id.should.eql users[0].user_id should.not.exist result[2].user_id Users.clear next it 'Test id # invalid type id', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, true, {user_id: 2}], (err, user) -> err.message.should.eql 'Invalid id, got true' Users.identify false, (err, user) -> err.message.should.eql 'Invalid id, got false' Users.clear next it 'Test id # invalid type null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], (err, users) -> err.message.should.eql 'Null record' Users.identify null, (err, user) -> err.message.should.eql 'Null record' Users.clear next it 'Test id # accept null', (next) -> # Test an array of 3 arguments, # but the second is invalid since it's a boolean Users.identify [1, null, {user_id: 2}], {accept_null: true}, (err, users) -> should.not.exist err users.length.should.eql 3 should.exist users[0] should.not.exist users[1] should.exist users[2] # Test null Users.identify null, {accept_null: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # accept null return object', (next) -> # Same test than 'Test id # accept null' with the 'object' option Users.identify [1, null, {user_id: 2}], {accept_null: true, object: true}, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].user_id.should.eql 1 should.not.exist users[1] users[2].user_id.should.eql 2 # Test null Users.identify null, {accept_null: true, object: true}, (err, user) -> should.not.exist err should.not.exist user Users.clear next it 'Test id # id return object', (next) -> Users.create { username: 'my_username' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err, orgUser) -> # Pass an id Users.identify orgUser.user_id, {object: true}, (err, user) -> should.not.exist err user.should.eql {user_id: orgUser.user_id} # Pass an array of ids Users.identify [orgUser.user_id, orgUser.user_id], {object: true}, (err, user) -> user.should.eql [{user_id: orgUser.user_id}, {user_id: orgUser.user_id}] Users.clear next it 'Test id # unique + option object', (next) -> Users.create { username: 'my_username' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err, orgUser) -> # Pass an object Users.identify {username: 'my_username'}, {object: true}, (err, user) -> should.not.exist err user.should.eql {username: 'my_username', user_id: orgUser.user_id} # Pass an array of ids and objects Users.identify [1, {username: 'my_username'}, 2], {object: true}, (err, user) -> should.not.exist err user.should.eql [{user_id: 1}, {username: 'my_username', user_id: orgUser.user_id}, {user_id: 2}] Users.clear next
[ { "context": " enums (regression)', ->\n # https://github.com/atom/language-java/issues/103\n # This test 'fails' ", "end": 13878, "score": 0.9961035251617432, "start": 13874, "tag": "USERNAME", "value": "atom" }, { "context": " String someString;\n String assigned = ...
spec/java-spec.coffee
ndneighbor/cafecito-atom
0
describe 'Java grammar', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-java') runs -> grammar = atom.grammars.grammarForScopeName('source.java') it 'parses the grammar', -> expect(grammar).toBeTruthy() expect(grammar.scopeName).toBe 'source.java' it 'tokenizes this with `.this` class', -> {tokens} = grammar.tokenizeLine 'this.x' expect(tokens[0]).toEqual value: 'this', scopes: ['source.java', 'variable.language.this.java'] it 'tokenizes braces', -> {tokens} = grammar.tokenizeLine '(3 + 5) + a[b]' expect(tokens[0]).toEqual value: '(', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[6]).toEqual value: ')', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[10]).toEqual value: '[', scopes: ['source.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: ']', scopes: ['source.java', 'punctuation.bracket.square.java'] {tokens} = grammar.tokenizeLine 'a(b)' expect(tokens[1]).toEqual value: '(', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[3]).toEqual value: ')', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' class A<String> { public int[][] something(String[][] hello) { } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][5]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.begin.bracket.curly.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java'] expect(lines[2][10]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][12]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][13]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][14]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][15]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][18]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] expect(lines[5][0]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.end.bracket.curly.java'] it 'tokenizes punctuation', -> {tokens} = grammar.tokenizeLine 'int a, b, c;' expect(tokens[3]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[6]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[9]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a.b(1, 2, c);' expect(tokens[1]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[5]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[8]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[11]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a . b' expect(tokens[2]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine 'class A implements B, C' expect(tokens[7]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.definition.class.implemented.interfaces.java', 'punctuation.separator.delimiter.java'] it 'tokenizes the `package` keyword', -> {tokens} = grammar.tokenizeLine 'package java.util.example;' expect(tokens[0]).toEqual value: 'package', scopes: ['source.java', 'meta.package.java', 'keyword.other.package.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.package.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.package.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'package java.Hi;' expect(tokens[4]).toEqual value: 'H', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes the `import` keyword', -> {tokens} = grammar.tokenizeLine 'import java.util.Example;' expect(tokens[0]).toEqual value: 'import', scopes: ['source.java', 'meta.import.java', 'keyword.other.import.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.import.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.import.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'import java.util.*;' expect(tokens[6]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'variable.language.wildcard.java'] {tokens} = grammar.tokenizeLine 'import static java.lang.Math.PI;' expect(tokens[2]).toEqual value: 'static', scopes: ['source.java', 'meta.import.java', 'storage.modifier.java'] {tokens} = grammar.tokenizeLine 'import java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java.**;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.a*;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes classes', -> lines = grammar.tokenizeLines ''' class Thing { int x; } ''' expect(lines[0][0]).toEqual value: 'class', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Thing', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'entity.name.type.class.java'] it 'tokenizes enums', -> lines = grammar.tokenizeLines ''' enum Letters { /* Comment about A */ A, // Comment about B B } ''' comment = ['source.java', 'meta.enum.java', 'comment.block.java'] commentDefinition = comment.concat('punctuation.definition.comment.java') expect(lines[0][0]).toEqual value: 'enum', scopes: ['source.java', 'meta.enum.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Letters', scopes: ['source.java', 'meta.enum.java', 'entity.name.type.enum.java'] expect(lines[0][4]).toEqual value: '{', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.begin.bracket.curly.java'] expect(lines[1][1]).toEqual value: '/*', scopes: commentDefinition expect(lines[1][2]).toEqual value: ' Comment about A ', scopes: comment expect(lines[1][3]).toEqual value: '*/', scopes: commentDefinition expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.enum.java', 'constant.other.enum.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.end.bracket.curly.java'] it 'does not catastrophically backtrack when tokenizing large enums (regression)', -> # https://github.com/atom/language-java/issues/103 # This test 'fails' if it runs for an absurdly long time without completing. # It should pass almost immediately just like all the other tests. enumContents = 'AAAAAAAAAAA, BBBBBBBBBB, CCCCCCCCCC, DDDDDDDDDD, EEEEEEEEEE, FFFFFFFFFF, '.repeat(50) lines = grammar.tokenizeLines """ public enum test { #{enumContents} } """ expect(lines[0][2]).toEqual value: 'enum', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] it 'tokenizes methods', -> lines = grammar.tokenizeLines ''' class A { A(int a, int b) { } } ''' expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][5]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][11]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] it 'tokenizes `final` in class method', -> lines = grammar.tokenizeLines ''' class A { public int doSomething(final int finalScore, final int scorefinal) { return finalScore; } } ''' expect(lines[2][7]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][11]).toEqual value: 'finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][14]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][18]).toEqual value: 'scorefinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: ' finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] describe 'numbers', -> describe 'integers', -> it 'tokenizes hexadecimal integers', -> {tokens} = grammar.tokenizeLine '0x0' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0X0' expect(tokens[0]).toEqual value: '0X0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567ABCDEF' expect(tokens[0]).toEqual value: '0x1234567ABCDEF', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567aBcDEf' expect(tokens[0]).toEqual value: '0x1234567aBcDEf', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x3746A4l' expect(tokens[0]).toEqual value: '0x3746A4l', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xC3L' expect(tokens[0]).toEqual value: '0xC3L', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0_1B' expect(tokens[0]).toEqual value: '0x0_1B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_B' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_BL' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_BL', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x_0' expect(tokens[0]).toEqual value: '0x_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x_' expect(tokens[0]).toEqual value: '0x_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCQ' expect(tokens[0]).toEqual value: '0x123ABCQ', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC$' expect(tokens[0]).toEqual value: '0x123ABC$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC_L' expect(tokens[0]).toEqual value: '0x123ABC_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCLl' expect(tokens[0]).toEqual value: '0x123ABCLl', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0x123ABC' expect(tokens[0]).toEqual value: 'a0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0x123ABC' expect(tokens[0]).toEqual value: '$0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1x0' expect(tokens[0]).toEqual value: '1x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0x1' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes binary literals', -> {tokens} = grammar.tokenizeLine '0b0' expect(tokens[0]).toEqual value: '0b0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0B0' expect(tokens[0]).toEqual value: '0B0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10101010010101' expect(tokens[0]).toEqual value: '0b10101010010101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10_101__010______01_0_101' expect(tokens[0]).toEqual value: '0b10_101__010______01_0_101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111l' expect(tokens[0]).toEqual value: '0b1111l', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111L' expect(tokens[0]).toEqual value: '0b1111L', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b11__01l' expect(tokens[0]).toEqual value: '0b11__01l', scopes: ['source.java', 'constant.numeric.binary.java'] # Invalid {tokens} = grammar.tokenizeLine '0b_0' expect(tokens[0]).toEqual value: '0b_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b_' expect(tokens[0]).toEqual value: '0b_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b0_' expect(tokens[0]).toEqual value: '0b0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b1001010102' expect(tokens[0]).toEqual value: '0b1001010102', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Q' expect(tokens[0]).toEqual value: '0b100101010Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010$' expect(tokens[0]).toEqual value: '0b100101010$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0b100101010' expect(tokens[0]).toEqual value: 'a0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0b100101010' expect(tokens[0]).toEqual value: '$0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Ll' expect(tokens[0]).toEqual value: '0b100101010Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010_L' expect(tokens[0]).toEqual value: '0b100101010_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1b0' expect(tokens[0]).toEqual value: '1b0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0b100101010' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes octal literals', -> {tokens} = grammar.tokenizeLine '00' expect(tokens[0]).toEqual value: '00', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '01234567' expect(tokens[0]).toEqual value: '01234567', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263_3251___3625_1_4' expect(tokens[0]).toEqual value: '07263_3251___3625_1_4', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263l' expect(tokens[0]).toEqual value: '07263l', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263L' expect(tokens[0]).toEqual value: '07263L', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '011__24l' expect(tokens[0]).toEqual value: '011__24l', scopes: ['source.java', 'constant.numeric.octal.java'] # Invalid {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '0_' expect(tokens[0]).toEqual value: '0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0_0' expect(tokens[0]).toEqual value: '0_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '01_' expect(tokens[0]).toEqual value: '01_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '02637242638' expect(tokens[0]).toEqual value: '02637242638', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Q' expect(tokens[0]).toEqual value: '0263724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263$' expect(tokens[0]).toEqual value: '0263724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0263724263' expect(tokens[0]).toEqual value: 'a0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0263724263' expect(tokens[0]).toEqual value: '$0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Ll' expect(tokens[0]).toEqual value: '0263724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263_L' expect(tokens[0]).toEqual value: '0263724263_L', scopes: ['source.java'] it 'tokenizes numeric integers', -> {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '123456789' expect(tokens[0]).toEqual value: '123456789', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '362__2643_0_7' expect(tokens[0]).toEqual value: '362__2643_0_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738L' expect(tokens[0]).toEqual value: '29473923603492738L', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738l' expect(tokens[0]).toEqual value: '29473923603492738l', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '2947_39___23__60_3_4______92738l' expect(tokens[0]).toEqual value: '2947_39___23__60_3_4______92738l', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '01' expect(tokens[0]).toEqual value: '01', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '1_' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Q' expect(tokens[0]).toEqual value: '2639724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263$' expect(tokens[0]).toEqual value: '2639724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a2639724263' expect(tokens[0]).toEqual value: 'a2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$2639724263' expect(tokens[0]).toEqual value: '$2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Ll' expect(tokens[0]).toEqual value: '2639724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263_L' expect(tokens[0]).toEqual value: '2639724263_L', scopes: ['source.java'] describe 'floats', -> it 'tokenizes hexadecimal floats', -> {tokens} = grammar.tokenizeLine '0x0P0' expect(tokens[0]).toEqual value: '0x0P0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0p0' expect(tokens[0]).toEqual value: '0x0p0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xDp3746' expect(tokens[0]).toEqual value: '0xDp3746', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD__3p3_7_46' expect(tokens[0]).toEqual value: '0xD__3p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.p3_7_46' expect(tokens[0]).toEqual value: '0xD3.p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp+3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp+3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46F' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46F', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46D' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46D', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46d' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46d', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-0f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-0f', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pA' expect(tokens[0]).toEqual value: '0x0pA', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pF' expect(tokens[0]).toEqual value: '0x0pF', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p_' expect(tokens[0]).toEqual value: '0x0p_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_p1' expect(tokens[0]).toEqual value: '0x0_p1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p1_' expect(tokens[0]).toEqual value: '0x0p1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+-2' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+2Ff' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0._p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_.p2' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0..p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0Pp2' expect(tokens[0]).toEqual value: '0x0Pp2', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0xp2' expect(tokens[0]).toEqual value: '0xp2', scopes: ['source.java'] it 'tokenizes numeric floats', -> {tokens} = grammar.tokenizeLine '1.' expect(tokens[0]).toEqual value: '1.', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0' expect(tokens[0]).toEqual value: '1.0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1273.47363' expect(tokens[0]).toEqual value: '1273.47363', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1_2.4_7__89_5' expect(tokens[0]).toEqual value: '1_2.4_7__89_5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.F' expect(tokens[0]).toEqual value: '1.F', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.f' expect(tokens[0]).toEqual value: '1.f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.D' expect(tokens[0]).toEqual value: '1.D', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.d' expect(tokens[0]).toEqual value: '1.d', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0f' expect(tokens[0]).toEqual value: '1.0f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0_7f' expect(tokens[0]).toEqual value: '1.0_7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.E5' expect(tokens[0]).toEqual value: '1.E5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5' expect(tokens[0]).toEqual value: '1.e5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5_7' expect(tokens[0]).toEqual value: '1.e5_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e58_26' expect(tokens[0]).toEqual value: '1.6e58_26', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e8f' expect(tokens[0]).toEqual value: '1.6e8f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7' expect(tokens[0]).toEqual value: '1.78e+7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e-7' expect(tokens[0]).toEqual value: '1.78e-7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7f' expect(tokens[0]).toEqual value: '1.78e+7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.7' expect(tokens[0]).toEqual value: '.7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.726' expect(tokens[0]).toEqual value: '.726', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.72__6e97_5632f' expect(tokens[0]).toEqual value: '.72__6e97_5632f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3' expect(tokens[0]).toEqual value: '7_26e+52_3', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3f' expect(tokens[0]).toEqual value: '7_26e+52_3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '3f' expect(tokens[0]).toEqual value: '3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26f' expect(tokens[0]).toEqual value: '7_26f', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '1e' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.e' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine '1_.' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_.' expect(tokens[0]).toEqual value: '_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1.1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '1.1_' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1e++7' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.ee5' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.Ff' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1..1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a1' expect(tokens[0]).toEqual value: 'a1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1a' expect(tokens[0]).toEqual value: '1a', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.q' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.3fa' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_f' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_e3' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$1' expect(tokens[0]).toEqual value: '$1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1$' expect(tokens[0]).toEqual value: '1$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$.1' expect(tokens[0]).toEqual value: '$', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '.1$' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes `final` in class fields', -> lines = grammar.tokenizeLines ''' class A { private final int finala = 0; final private int bfinal = 1; } ''' expect(lines[2][3]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][7]).toEqual value: 'finala', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[3][1]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][7]).toEqual value: 'bfinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes method-local variables', -> lines = grammar.tokenizeLines ''' class A { public void fn() { String someString; String assigned = "Rand al'Thor"; int primitive = 5; } } ''' expect(lines[4][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'someString', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[5][3]).toEqual value: 'assigned', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][8]).toEqual value: "Rand al'Thor", scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(lines[6][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][3]).toEqual value: 'primitive', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][7]).toEqual value: '5', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] it 'tokenizes function and method calls', -> lines = grammar.tokenizeLines ''' class A { A() { hello(); hello(a, 1, "hello"); $hello(); this.hello(); this . hello(a, b); } } ''' expect(lines[4][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[4][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][3]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java'] expect(lines[5][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.separator.delimiter.java'] expect(lines[5][6]).toEqual value: '1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'constant.numeric.decimal.java'] expect(lines[5][9]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(lines[5][11]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(lines[5][13]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[6][1]).toEqual value: '$hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: 'this', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.language.this.java'] expect(lines[7][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[7][3]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[7][5]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[8][3]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[8][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][5]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[8][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(lines[8][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes objects and properties', -> lines = grammar.tokenizeLines ''' class A { A() { object.property; object.Property; Object.property; object . property; $object.$property; object.property1.property2; object.method().property; object.property.method(); object.123illegal; } } ''' expect(lines[4][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[4][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[4][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'Property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[6][1]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][5]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[8][1]).toEqual value: '$object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[8][3]).toEqual value: '$property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[9][3]).toEqual value: 'property1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[9][5]).toEqual value: 'property2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[10][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[10][3]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[10][7]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[11][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[11][5]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[12][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[12][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[12][3]).toEqual value: '123illegal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'invalid.illegal.identifier.java'] expect(lines[12][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes generics', -> lines = grammar.tokenizeLines ''' class A<T extends A & B, String, Integer> { HashMap<Integer, String> map = new HashMap<>(); CodeMap<String, ? extends ArrayList> codemap; C(Map<?, ? extends List<?>> m) {} Map<Integer, String> method() {} private Object otherMethod() { return null; } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][4]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][5]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][6]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'storage.modifier.extends.java'] expect(lines[0][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][8]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][9]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][10]).toEqual value: '&', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.types.java'] expect(lines[0][11]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][12]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][13]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][14]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][15]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][16]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][17]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][18]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][19]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[2][1]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[2][6]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][9]).toEqual value: 'map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][15]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][16]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][17]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][1]).toEqual value: 'CodeMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[3][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][3]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[3][6]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.wildcard.java'] expect(lines[3][8]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.modifier.extends.java'] expect(lines[3][10]).toEqual value: 'ArrayList', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][11]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][13]).toEqual value: 'codemap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][1]).toEqual value: 'C', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[4][3]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][5]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[4][8]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][10]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.extends.java'] expect(lines[4][12]).toEqual value: 'List', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][13]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][14]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][15]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][16]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][18]).toEqual value: 'm', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[5][1]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[5][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.generic.java'] expect(lines[5][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][9]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[6][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[6][5]).toEqual value: 'otherMethod', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] it 'tokenizes generics and primitive arrays declarations', -> lines = grammar.tokenizeLines ''' class A<T> { private B<T>[] arr; private int[][] two = null; } ''' expect(lines[1][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[1][3]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][5]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[1][6]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][7]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][8]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][10]).toEqual value: 'arr', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[1][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][9]).toEqual value: 'two', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][11]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[2][13]).toEqual value: 'null', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.language.java'] expect(lines[2][14]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] it 'tokenizes lambda expressions', -> {tokens} = grammar.tokenizeLine '(String s1) -> s1.length() - outer.length();' expect(tokens[1]).toEqual value: 'String', scopes: ['source.java', 'storage.type.java'] expect(tokens[5]).toEqual value: '->', scopes: ['source.java', 'storage.type.function.arrow.java'] expect(tokens[8]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[10]).toEqual value: '(', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[11]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: '-', scopes: ['source.java', 'keyword.operator.arithmetic.java'] it 'tokenizes `new` statements', -> {tokens} = grammar.tokenizeLine 'int[] list = new int[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[9]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[10]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'boolean[] list = new boolean[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[]{"hi", "abc", "etc"};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[15]).toEqual value: 'hi', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[16]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(tokens[17]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[18]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[27]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[28]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = new A[]{new A(), new A()};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[16]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[23]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[24]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[25]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[26]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[27]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = {new A(), new A()};' expect(tokens[8]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(tokens[9]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[11]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[12]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[13]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[16]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[18]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[19]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[20]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.end.bracket.curly.java'] expect(tokens[22]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String a = (valid ? new Date().toString() + " : " : "");' expect(tokens[16]).toEqual value: 'toString', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: '+', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.operator.arithmetic.java'] expect(tokens[23]).toEqual value: ' : ', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[26]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[28]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[29]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'Point point = new Point(1, 4);' expect(tokens[6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[9]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[14]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[15]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'Point point = true ? new Point(1, 4) : new Point(0, 0);' expect(tokens[8]).toEqual value: '?', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[10]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[12]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[13]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[22]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[31]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'map.put(key, new Value(value), "extra");' expect(tokens[12]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[15]).toEqual value: '"', scopes: ['source.java', 'meta.method-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' map.put(key, new Value(value) ); ''' expect(lines[2][0]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' Point point = new Point() { public void something(x) { int y = x; } }; ''' expect(lines[0][6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(lines[0][8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.begin.bracket.curly.java'] expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.end.bracket.curly.java'] expect(lines[6][1]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] it 'tokenizes the `instanceof` operator', -> {tokens} = grammar.tokenizeLine 'instanceof' expect(tokens[0]).toEqual value: 'instanceof', scopes: ['source.java', 'keyword.operator.instanceof.java'] it 'tokenizes class fields', -> lines = grammar.tokenizeLines ''' class Test { private int variable; public Object[] variable; private int variable = 3; private int variable1, variable2, variable3; private int variable1, variable2 = variable; private int variable;// = 3; public String CAPITALVARIABLE; private int[][] somevar = new int[10][12]; private int 1invalid; private Integer $tar_war$; double a,b,c;double d; String[] primitiveArray; } ''' expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][2]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[2][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[2][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[3][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[3][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[3][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[4][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][6]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][7]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[4][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][9]).toEqual value: '3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[4][10]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[5][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[5][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[5][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][11]).toEqual value: 'variable3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[6][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][10]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[6][11]).toEqual value: ' variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[6][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][7]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[8][5]).toEqual value: 'CAPITALVARIABLE', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[8][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[9][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][9]).toEqual value: 'somevar', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[9][15]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][16]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][17]).toEqual value: '10', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][18]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][19]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][20]).toEqual value: '12', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][21]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[10][2]).toEqual value: ' int 1invalid', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[11][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[11][5]).toEqual value: '$tar_war$', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][1]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][5]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][7]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][8]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[12][9]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][11]).toEqual value: 'd', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[13][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[13][2]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][3]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][5]).toEqual value: 'primitiveArray', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes qualified storage types', -> lines = grammar.tokenizeLines ''' class Test { private Test.Double something; } ''' expect(lines[1][3]).toEqual value: 'Test', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java', 'punctuation.separator.period.java'] expect(lines[1][5]).toEqual value: 'Double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][7]).toEqual value: 'something', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { errorProneMethod(); } catch (RuntimeException re) { handleRuntimeException(re); } catch (Exception e) { String variable = "assigning for some reason"; } finally { // Relax, it's over new Thingie().call(); } } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[3][1]).toEqual value: 'errorProneMethod', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[4][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.catch.java' expect(lines[4][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[4][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[4][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[4][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[4][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[5][1]).toEqual value: 'handleRuntimeException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[6][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] expect(lines[6][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[6][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[6][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[6][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[6][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[7][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[7][3]).toEqual value: 'variable', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.finally.java' expect(lines[8][3]).toEqual value: 'finally', scopes: scopeStack.concat ['keyword.control.finally.java'] expect(lines[8][5]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.finally.begin.bracket.curly.java'] scopeStack.push 'meta.finally.body.java' expect(lines[9][1]).toEqual value: '//', scopes: scopeStack.concat ['comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[10][1]).toEqual value: 'new', scopes: scopeStack.concat ['keyword.control.new.java'] scopeStack.pop() expect(lines[11][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.finally.end.bracket.curly.java'] it 'tokenizes nested try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { try { String nested; } catch (Exception e) { handleNestedException(); } } catch (RuntimeException re) {} } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopeStack expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java', 'meta.try.java' expect(lines[3][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[3][2]).toEqual value: ' ', scopes: scopeStack expect(lines[3][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[4][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'nested', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[5][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[5][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[5][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[5][4]).toEqual value: ' ', scopes: scopeStack expect(lines[5][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[5][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[5][7]).toEqual value: ' ', scopes: scopeStack expect(lines[5][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[5][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[5][10]).toEqual value: ' ', scopes: scopeStack expect(lines[5][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[6][1]).toEqual value: 'handleNestedException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[7][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[8][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[8][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[8][4]).toEqual value: ' ', scopes: scopeStack expect(lines[8][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[8][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[8][7]).toEqual value: ' ', scopes: scopeStack expect(lines[8][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[8][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][10]).toEqual value: ' ', scopes: scopeStack expect(lines[8][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] expect(lines[8][12]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] it 'tokenizes try-catch blocks with resources', -> lines = grammar.tokenizeLines ''' class Test { private void fn() { try ( BufferedReader in = new BufferedReader(); ) { // stuff } } } ''' scopes = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.try.java'] expect(lines[2][1]).toEqual value: 'try', scopes: scopes.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopes expect(lines[2][3]).toEqual value: '(', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.begin.bracket.round.java'] expect(lines[3][1]).toEqual value: 'BufferedReader', scopes: scopes.concat ['meta.try.resources.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][1]).toEqual value: ')', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.end.bracket.round.java'] expect(lines[4][2]).toEqual value: ' ', scopes: scopes expect(lines[4][3]).toEqual value: '{', scopes: scopes.concat ['punctuation.section.try.begin.bracket.curly.java'] it 'tokenizes comment inside method body', -> lines = grammar.tokenizeLines ''' class Test { private void method() { /** invalid javadoc comment */ /* inline comment */ // single-line comment } } ''' expect(lines[3][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[3][2]).toEqual value: '* invalid javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[3][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][2]).toEqual value: ' inline comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[4][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[5][2]).toEqual value: ' single-line comment', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java'] it 'tokenizes single-line javadoc comment', -> lines = grammar.tokenizeLines ''' /** single-line javadoc comment */ class Test { private int variable; } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[0][1]).toEqual value: ' single-line javadoc comment ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[0][2]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes javadoc comment inside class body', -> # this checks single line javadoc comment, but the same rules apply for multi-line one lines = grammar.tokenizeLines ''' enum Test { /** javadoc comment */ } class Test { /** javadoc comment */ } ''' expect(lines[1][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java'] expect(lines[1][2]).toEqual value: '*/', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][2]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes inline comment inside method signature', -> # this checks usage of inline /*...*/ comments mixing with parameters lines = grammar.tokenizeLines ''' class A { public A(int a, /* String b,*/ boolean c) { } public void methodA(int a /*, String b */) { } private void methodB(/* int a, */String b) { } protected void methodC(/* comment */) { } } ''' expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][5]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][10]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][11]).toEqual value: ' String b,', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[2][12]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][14]).toEqual value: 'booleano', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][16]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][17]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][7]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[4][9]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][11]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][12]).toEqual value: ', String b ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[4][13]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][14]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[6][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][8]).toEqual value: ' int a, ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[6][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][10]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[6][12]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[6][13]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[8][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][8]).toEqual value: ' comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[8][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][10]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] it 'tokenizes multi-line basic javadoc comment', -> lines = grammar.tokenizeLines ''' /** * @author John Smith * @deprecated description * @see reference * @since version * @version version */ class Test { } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: '@author', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[1][2]).toEqual value: ' John Smith', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[2][1]).toEqual value: '@deprecated', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[2][2]).toEqual value: ' description', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[3][1]).toEqual value: '@see', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][2]).toEqual value: ' reference', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@since', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[5][1]).toEqual value: '@version', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][0]).toEqual value: ' ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][1]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes `param` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Increment number. * @param num value to increment. */ public void inc(int num) { num += 1; } } ''' expect(lines[4][1]).toEqual value: '@param', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'num', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][4]).toEqual value: ' value to increment.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `exception`/`throws` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * @throws IllegalStateException reason * @exception IllegalStateException reason */ public void fail() { throw new IllegalStateException(); } } ''' expect(lines[3][1]).toEqual value: '@throws', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[3][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@exception', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[4][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `link` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Use {@link #method()} * Use {@link #method(int a)} * Use {@link Class#method(int a)} * Use {@link Class#method (int a, int b)} * @link #method() * Use {@link Class#method$(int a) label {@link Class#method()}} */ public int test() { return -1; } } ''' expect(lines[3][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[3][4]).toEqual value: 'method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][4]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[5][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[5][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][6]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[6][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[6][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[6][6]).toEqual value: 'method (int a, int b)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[7][0]).toEqual value: ' * @link #method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[8][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[8][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][6]).toEqual value: 'method$(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[8][7]).toEqual value: ' label {@link Class#method()}}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes class-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes method-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public int func() { List<Integer> list = new ArrayList<Integer>(); { int a = 1; list.add(a); } return 1; } } ''' expect(lines[4][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[5][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][1]).toEqual value: 'list', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[6][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes static initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); static { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: 'static', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java']
67545
describe 'Java grammar', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-java') runs -> grammar = atom.grammars.grammarForScopeName('source.java') it 'parses the grammar', -> expect(grammar).toBeTruthy() expect(grammar.scopeName).toBe 'source.java' it 'tokenizes this with `.this` class', -> {tokens} = grammar.tokenizeLine 'this.x' expect(tokens[0]).toEqual value: 'this', scopes: ['source.java', 'variable.language.this.java'] it 'tokenizes braces', -> {tokens} = grammar.tokenizeLine '(3 + 5) + a[b]' expect(tokens[0]).toEqual value: '(', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[6]).toEqual value: ')', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[10]).toEqual value: '[', scopes: ['source.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: ']', scopes: ['source.java', 'punctuation.bracket.square.java'] {tokens} = grammar.tokenizeLine 'a(b)' expect(tokens[1]).toEqual value: '(', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[3]).toEqual value: ')', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' class A<String> { public int[][] something(String[][] hello) { } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][5]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.begin.bracket.curly.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java'] expect(lines[2][10]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][12]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][13]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][14]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][15]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][18]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] expect(lines[5][0]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.end.bracket.curly.java'] it 'tokenizes punctuation', -> {tokens} = grammar.tokenizeLine 'int a, b, c;' expect(tokens[3]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[6]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[9]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a.b(1, 2, c);' expect(tokens[1]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[5]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[8]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[11]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a . b' expect(tokens[2]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine 'class A implements B, C' expect(tokens[7]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.definition.class.implemented.interfaces.java', 'punctuation.separator.delimiter.java'] it 'tokenizes the `package` keyword', -> {tokens} = grammar.tokenizeLine 'package java.util.example;' expect(tokens[0]).toEqual value: 'package', scopes: ['source.java', 'meta.package.java', 'keyword.other.package.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.package.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.package.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'package java.Hi;' expect(tokens[4]).toEqual value: 'H', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes the `import` keyword', -> {tokens} = grammar.tokenizeLine 'import java.util.Example;' expect(tokens[0]).toEqual value: 'import', scopes: ['source.java', 'meta.import.java', 'keyword.other.import.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.import.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.import.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'import java.util.*;' expect(tokens[6]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'variable.language.wildcard.java'] {tokens} = grammar.tokenizeLine 'import static java.lang.Math.PI;' expect(tokens[2]).toEqual value: 'static', scopes: ['source.java', 'meta.import.java', 'storage.modifier.java'] {tokens} = grammar.tokenizeLine 'import java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java.**;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.a*;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes classes', -> lines = grammar.tokenizeLines ''' class Thing { int x; } ''' expect(lines[0][0]).toEqual value: 'class', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Thing', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'entity.name.type.class.java'] it 'tokenizes enums', -> lines = grammar.tokenizeLines ''' enum Letters { /* Comment about A */ A, // Comment about B B } ''' comment = ['source.java', 'meta.enum.java', 'comment.block.java'] commentDefinition = comment.concat('punctuation.definition.comment.java') expect(lines[0][0]).toEqual value: 'enum', scopes: ['source.java', 'meta.enum.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Letters', scopes: ['source.java', 'meta.enum.java', 'entity.name.type.enum.java'] expect(lines[0][4]).toEqual value: '{', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.begin.bracket.curly.java'] expect(lines[1][1]).toEqual value: '/*', scopes: commentDefinition expect(lines[1][2]).toEqual value: ' Comment about A ', scopes: comment expect(lines[1][3]).toEqual value: '*/', scopes: commentDefinition expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.enum.java', 'constant.other.enum.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.end.bracket.curly.java'] it 'does not catastrophically backtrack when tokenizing large enums (regression)', -> # https://github.com/atom/language-java/issues/103 # This test 'fails' if it runs for an absurdly long time without completing. # It should pass almost immediately just like all the other tests. enumContents = 'AAAAAAAAAAA, BBBBBBBBBB, CCCCCCCCCC, DDDDDDDDDD, EEEEEEEEEE, FFFFFFFFFF, '.repeat(50) lines = grammar.tokenizeLines """ public enum test { #{enumContents} } """ expect(lines[0][2]).toEqual value: 'enum', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] it 'tokenizes methods', -> lines = grammar.tokenizeLines ''' class A { A(int a, int b) { } } ''' expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][5]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][11]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] it 'tokenizes `final` in class method', -> lines = grammar.tokenizeLines ''' class A { public int doSomething(final int finalScore, final int scorefinal) { return finalScore; } } ''' expect(lines[2][7]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][11]).toEqual value: 'finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][14]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][18]).toEqual value: 'scorefinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: ' finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] describe 'numbers', -> describe 'integers', -> it 'tokenizes hexadecimal integers', -> {tokens} = grammar.tokenizeLine '0x0' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0X0' expect(tokens[0]).toEqual value: '0X0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567ABCDEF' expect(tokens[0]).toEqual value: '0x1234567ABCDEF', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567aBcDEf' expect(tokens[0]).toEqual value: '0x1234567aBcDEf', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x3746A4l' expect(tokens[0]).toEqual value: '0x3746A4l', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xC3L' expect(tokens[0]).toEqual value: '0xC3L', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0_1B' expect(tokens[0]).toEqual value: '0x0_1B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_B' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_BL' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_BL', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x_0' expect(tokens[0]).toEqual value: '0x_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x_' expect(tokens[0]).toEqual value: '0x_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCQ' expect(tokens[0]).toEqual value: '0x123ABCQ', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC$' expect(tokens[0]).toEqual value: '0x123ABC$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC_L' expect(tokens[0]).toEqual value: '0x123ABC_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCLl' expect(tokens[0]).toEqual value: '0x123ABCLl', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0x123ABC' expect(tokens[0]).toEqual value: 'a0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0x123ABC' expect(tokens[0]).toEqual value: '$0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1x0' expect(tokens[0]).toEqual value: '1x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0x1' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes binary literals', -> {tokens} = grammar.tokenizeLine '0b0' expect(tokens[0]).toEqual value: '0b0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0B0' expect(tokens[0]).toEqual value: '0B0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10101010010101' expect(tokens[0]).toEqual value: '0b10101010010101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10_101__010______01_0_101' expect(tokens[0]).toEqual value: '0b10_101__010______01_0_101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111l' expect(tokens[0]).toEqual value: '0b1111l', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111L' expect(tokens[0]).toEqual value: '0b1111L', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b11__01l' expect(tokens[0]).toEqual value: '0b11__01l', scopes: ['source.java', 'constant.numeric.binary.java'] # Invalid {tokens} = grammar.tokenizeLine '0b_0' expect(tokens[0]).toEqual value: '0b_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b_' expect(tokens[0]).toEqual value: '0b_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b0_' expect(tokens[0]).toEqual value: '0b0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b1001010102' expect(tokens[0]).toEqual value: '0b1001010102', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Q' expect(tokens[0]).toEqual value: '0b100101010Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010$' expect(tokens[0]).toEqual value: '0b100101010$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0b100101010' expect(tokens[0]).toEqual value: 'a0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0b100101010' expect(tokens[0]).toEqual value: '$0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Ll' expect(tokens[0]).toEqual value: '0b100101010Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010_L' expect(tokens[0]).toEqual value: '0b100101010_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1b0' expect(tokens[0]).toEqual value: '1b0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0b100101010' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes octal literals', -> {tokens} = grammar.tokenizeLine '00' expect(tokens[0]).toEqual value: '00', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '01234567' expect(tokens[0]).toEqual value: '01234567', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263_3251___3625_1_4' expect(tokens[0]).toEqual value: '07263_3251___3625_1_4', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263l' expect(tokens[0]).toEqual value: '07263l', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263L' expect(tokens[0]).toEqual value: '07263L', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '011__24l' expect(tokens[0]).toEqual value: '011__24l', scopes: ['source.java', 'constant.numeric.octal.java'] # Invalid {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '0_' expect(tokens[0]).toEqual value: '0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0_0' expect(tokens[0]).toEqual value: '0_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '01_' expect(tokens[0]).toEqual value: '01_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '02637242638' expect(tokens[0]).toEqual value: '02637242638', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Q' expect(tokens[0]).toEqual value: '0263724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263$' expect(tokens[0]).toEqual value: '0263724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0263724263' expect(tokens[0]).toEqual value: 'a0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0263724263' expect(tokens[0]).toEqual value: '$0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Ll' expect(tokens[0]).toEqual value: '0263724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263_L' expect(tokens[0]).toEqual value: '0263724263_L', scopes: ['source.java'] it 'tokenizes numeric integers', -> {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '123456789' expect(tokens[0]).toEqual value: '123456789', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '362__2643_0_7' expect(tokens[0]).toEqual value: '362__2643_0_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738L' expect(tokens[0]).toEqual value: '29473923603492738L', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738l' expect(tokens[0]).toEqual value: '29473923603492738l', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '2947_39___23__60_3_4______92738l' expect(tokens[0]).toEqual value: '2947_39___23__60_3_4______92738l', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '01' expect(tokens[0]).toEqual value: '01', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '1_' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Q' expect(tokens[0]).toEqual value: '2639724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263$' expect(tokens[0]).toEqual value: '2639724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a2639724263' expect(tokens[0]).toEqual value: 'a2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$2639724263' expect(tokens[0]).toEqual value: '$2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Ll' expect(tokens[0]).toEqual value: '2639724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263_L' expect(tokens[0]).toEqual value: '2639724263_L', scopes: ['source.java'] describe 'floats', -> it 'tokenizes hexadecimal floats', -> {tokens} = grammar.tokenizeLine '0x0P0' expect(tokens[0]).toEqual value: '0x0P0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0p0' expect(tokens[0]).toEqual value: '0x0p0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xDp3746' expect(tokens[0]).toEqual value: '0xDp3746', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD__3p3_7_46' expect(tokens[0]).toEqual value: '0xD__3p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.p3_7_46' expect(tokens[0]).toEqual value: '0xD3.p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp+3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp+3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46F' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46F', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46D' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46D', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46d' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46d', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-0f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-0f', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pA' expect(tokens[0]).toEqual value: '0x0pA', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pF' expect(tokens[0]).toEqual value: '0x0pF', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p_' expect(tokens[0]).toEqual value: '0x0p_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_p1' expect(tokens[0]).toEqual value: '0x0_p1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p1_' expect(tokens[0]).toEqual value: '0x0p1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+-2' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+2Ff' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0._p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_.p2' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0..p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0Pp2' expect(tokens[0]).toEqual value: '0x0Pp2', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0xp2' expect(tokens[0]).toEqual value: '0xp2', scopes: ['source.java'] it 'tokenizes numeric floats', -> {tokens} = grammar.tokenizeLine '1.' expect(tokens[0]).toEqual value: '1.', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0' expect(tokens[0]).toEqual value: '1.0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1273.47363' expect(tokens[0]).toEqual value: '1273.47363', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1_2.4_7__89_5' expect(tokens[0]).toEqual value: '1_2.4_7__89_5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.F' expect(tokens[0]).toEqual value: '1.F', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.f' expect(tokens[0]).toEqual value: '1.f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.D' expect(tokens[0]).toEqual value: '1.D', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.d' expect(tokens[0]).toEqual value: '1.d', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0f' expect(tokens[0]).toEqual value: '1.0f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0_7f' expect(tokens[0]).toEqual value: '1.0_7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.E5' expect(tokens[0]).toEqual value: '1.E5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5' expect(tokens[0]).toEqual value: '1.e5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5_7' expect(tokens[0]).toEqual value: '1.e5_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e58_26' expect(tokens[0]).toEqual value: '1.6e58_26', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e8f' expect(tokens[0]).toEqual value: '1.6e8f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7' expect(tokens[0]).toEqual value: '1.78e+7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e-7' expect(tokens[0]).toEqual value: '1.78e-7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7f' expect(tokens[0]).toEqual value: '1.78e+7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.7' expect(tokens[0]).toEqual value: '.7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.726' expect(tokens[0]).toEqual value: '.726', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.72__6e97_5632f' expect(tokens[0]).toEqual value: '.72__6e97_5632f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3' expect(tokens[0]).toEqual value: '7_26e+52_3', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3f' expect(tokens[0]).toEqual value: '7_26e+52_3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '3f' expect(tokens[0]).toEqual value: '3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26f' expect(tokens[0]).toEqual value: '7_26f', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '1e' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.e' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine '1_.' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_.' expect(tokens[0]).toEqual value: '_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1.1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '1.1_' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1e++7' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.ee5' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.Ff' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1..1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a1' expect(tokens[0]).toEqual value: 'a1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1a' expect(tokens[0]).toEqual value: '1a', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.q' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.3fa' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_f' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_e3' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$1' expect(tokens[0]).toEqual value: '$1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1$' expect(tokens[0]).toEqual value: '1$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$.1' expect(tokens[0]).toEqual value: '$', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '.1$' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes `final` in class fields', -> lines = grammar.tokenizeLines ''' class A { private final int finala = 0; final private int bfinal = 1; } ''' expect(lines[2][3]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][7]).toEqual value: 'finala', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[3][1]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][7]).toEqual value: 'bfinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes method-local variables', -> lines = grammar.tokenizeLines ''' class A { public void fn() { String someString; String assigned = "<NAME>"; int primitive = 5; } } ''' expect(lines[4][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'someString', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[5][3]).toEqual value: 'assigned', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][8]).toEqual value: "<NAME>", scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(lines[6][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][3]).toEqual value: 'primitive', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][7]).toEqual value: '5', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] it 'tokenizes function and method calls', -> lines = grammar.tokenizeLines ''' class A { A() { hello(); hello(a, 1, "hello"); $hello(); this.hello(); this . hello(a, b); } } ''' expect(lines[4][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[4][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][3]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java'] expect(lines[5][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.separator.delimiter.java'] expect(lines[5][6]).toEqual value: '1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'constant.numeric.decimal.java'] expect(lines[5][9]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(lines[5][11]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(lines[5][13]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[6][1]).toEqual value: '$hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: 'this', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.language.this.java'] expect(lines[7][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[7][3]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[7][5]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[8][3]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[8][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][5]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[8][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(lines[8][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes objects and properties', -> lines = grammar.tokenizeLines ''' class A { A() { object.property; object.Property; Object.property; object . property; $object.$property; object.property1.property2; object.method().property; object.property.method(); object.123illegal; } } ''' expect(lines[4][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[4][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[4][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'Property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[6][1]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][5]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[8][1]).toEqual value: '$object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[8][3]).toEqual value: '$property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[9][3]).toEqual value: 'property1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[9][5]).toEqual value: 'property2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[10][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[10][3]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[10][7]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[11][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[11][5]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[12][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[12][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[12][3]).toEqual value: '123illegal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'invalid.illegal.identifier.java'] expect(lines[12][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes generics', -> lines = grammar.tokenizeLines ''' class A<T extends A & B, String, Integer> { HashMap<Integer, String> map = new HashMap<>(); CodeMap<String, ? extends ArrayList> codemap; C(Map<?, ? extends List<?>> m) {} Map<Integer, String> method() {} private Object otherMethod() { return null; } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][4]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][5]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][6]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'storage.modifier.extends.java'] expect(lines[0][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][8]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][9]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][10]).toEqual value: '&', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.types.java'] expect(lines[0][11]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][12]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][13]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][14]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][15]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][16]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][17]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][18]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][19]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[2][1]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[2][6]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][9]).toEqual value: 'map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][15]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][16]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][17]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][1]).toEqual value: 'CodeMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[3][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][3]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[3][6]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.wildcard.java'] expect(lines[3][8]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.modifier.extends.java'] expect(lines[3][10]).toEqual value: 'ArrayList', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][11]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][13]).toEqual value: 'codemap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][1]).toEqual value: 'C', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[4][3]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][5]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[4][8]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][10]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.extends.java'] expect(lines[4][12]).toEqual value: 'List', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][13]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][14]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][15]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][16]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][18]).toEqual value: 'm', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[5][1]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[5][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.generic.java'] expect(lines[5][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][9]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[6][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[6][5]).toEqual value: 'otherMethod', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] it 'tokenizes generics and primitive arrays declarations', -> lines = grammar.tokenizeLines ''' class A<T> { private B<T>[] arr; private int[][] two = null; } ''' expect(lines[1][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[1][3]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][5]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[1][6]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][7]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][8]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][10]).toEqual value: 'arr', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[1][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][9]).toEqual value: 'two', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][11]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[2][13]).toEqual value: 'null', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.language.java'] expect(lines[2][14]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] it 'tokenizes lambda expressions', -> {tokens} = grammar.tokenizeLine '(String s1) -> s1.length() - outer.length();' expect(tokens[1]).toEqual value: 'String', scopes: ['source.java', 'storage.type.java'] expect(tokens[5]).toEqual value: '->', scopes: ['source.java', 'storage.type.function.arrow.java'] expect(tokens[8]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[10]).toEqual value: '(', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[11]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: '-', scopes: ['source.java', 'keyword.operator.arithmetic.java'] it 'tokenizes `new` statements', -> {tokens} = grammar.tokenizeLine 'int[] list = new int[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[9]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[10]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'boolean[] list = new boolean[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[]{"hi", "abc", "etc"};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[15]).toEqual value: 'hi', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[16]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(tokens[17]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[18]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[27]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[28]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = new A[]{new A(), new A()};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[16]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[23]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[24]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[25]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[26]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[27]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = {new A(), new A()};' expect(tokens[8]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(tokens[9]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[11]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[12]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[13]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[16]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[18]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[19]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[20]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.end.bracket.curly.java'] expect(tokens[22]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String a = (valid ? new Date().toString() + " : " : "");' expect(tokens[16]).toEqual value: 'toString', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: '+', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.operator.arithmetic.java'] expect(tokens[23]).toEqual value: ' : ', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[26]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[28]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[29]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'Point point = new Point(1, 4);' expect(tokens[6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[9]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[14]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[15]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'Point point = true ? new Point(1, 4) : new Point(0, 0);' expect(tokens[8]).toEqual value: '?', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[10]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[12]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[13]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[22]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[31]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'map.put(key, new Value(value), "extra");' expect(tokens[12]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[15]).toEqual value: '"', scopes: ['source.java', 'meta.method-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' map.put(key, new Value(value) ); ''' expect(lines[2][0]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' Point point = new Point() { public void something(x) { int y = x; } }; ''' expect(lines[0][6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(lines[0][8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.begin.bracket.curly.java'] expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.end.bracket.curly.java'] expect(lines[6][1]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] it 'tokenizes the `instanceof` operator', -> {tokens} = grammar.tokenizeLine 'instanceof' expect(tokens[0]).toEqual value: 'instanceof', scopes: ['source.java', 'keyword.operator.instanceof.java'] it 'tokenizes class fields', -> lines = grammar.tokenizeLines ''' class Test { private int variable; public Object[] variable; private int variable = 3; private int variable1, variable2, variable3; private int variable1, variable2 = variable; private int variable;// = 3; public String CAPITALVARIABLE; private int[][] somevar = new int[10][12]; private int 1invalid; private Integer $tar_war$; double a,b,c;double d; String[] primitiveArray; } ''' expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][2]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[2][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[2][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[3][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[3][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[3][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[4][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][6]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][7]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[4][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][9]).toEqual value: '3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[4][10]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[5][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[5][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[5][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][11]).toEqual value: 'variable3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[6][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][10]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[6][11]).toEqual value: ' variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[6][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][7]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[8][5]).toEqual value: 'CAPITALVARIABLE', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[8][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[9][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][9]).toEqual value: 'somevar', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[9][15]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][16]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][17]).toEqual value: '10', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][18]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][19]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][20]).toEqual value: '12', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][21]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[10][2]).toEqual value: ' int 1invalid', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[11][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[11][5]).toEqual value: '$tar_war$', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][1]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][5]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][7]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][8]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[12][9]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][11]).toEqual value: 'd', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[13][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[13][2]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][3]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][5]).toEqual value: 'primitiveArray', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes qualified storage types', -> lines = grammar.tokenizeLines ''' class Test { private Test.Double something; } ''' expect(lines[1][3]).toEqual value: 'Test', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java', 'punctuation.separator.period.java'] expect(lines[1][5]).toEqual value: 'Double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][7]).toEqual value: 'something', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { errorProneMethod(); } catch (RuntimeException re) { handleRuntimeException(re); } catch (Exception e) { String variable = "assigning for some reason"; } finally { // Relax, it's over new Thingie().call(); } } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[3][1]).toEqual value: 'errorProneMethod', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[4][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.catch.java' expect(lines[4][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[4][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[4][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[4][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[4][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[5][1]).toEqual value: 'handleRuntimeException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[6][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] expect(lines[6][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[6][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[6][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[6][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[6][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[7][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[7][3]).toEqual value: 'variable', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.finally.java' expect(lines[8][3]).toEqual value: 'finally', scopes: scopeStack.concat ['keyword.control.finally.java'] expect(lines[8][5]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.finally.begin.bracket.curly.java'] scopeStack.push 'meta.finally.body.java' expect(lines[9][1]).toEqual value: '//', scopes: scopeStack.concat ['comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[10][1]).toEqual value: 'new', scopes: scopeStack.concat ['keyword.control.new.java'] scopeStack.pop() expect(lines[11][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.finally.end.bracket.curly.java'] it 'tokenizes nested try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { try { String nested; } catch (Exception e) { handleNestedException(); } } catch (RuntimeException re) {} } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopeStack expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java', 'meta.try.java' expect(lines[3][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[3][2]).toEqual value: ' ', scopes: scopeStack expect(lines[3][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[4][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'nested', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[5][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[5][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[5][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[5][4]).toEqual value: ' ', scopes: scopeStack expect(lines[5][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[5][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[5][7]).toEqual value: ' ', scopes: scopeStack expect(lines[5][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[5][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[5][10]).toEqual value: ' ', scopes: scopeStack expect(lines[5][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[6][1]).toEqual value: 'handleNestedException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[7][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[8][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[8][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[8][4]).toEqual value: ' ', scopes: scopeStack expect(lines[8][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[8][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[8][7]).toEqual value: ' ', scopes: scopeStack expect(lines[8][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[8][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][10]).toEqual value: ' ', scopes: scopeStack expect(lines[8][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] expect(lines[8][12]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] it 'tokenizes try-catch blocks with resources', -> lines = grammar.tokenizeLines ''' class Test { private void fn() { try ( BufferedReader in = new BufferedReader(); ) { // stuff } } } ''' scopes = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.try.java'] expect(lines[2][1]).toEqual value: 'try', scopes: scopes.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopes expect(lines[2][3]).toEqual value: '(', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.begin.bracket.round.java'] expect(lines[3][1]).toEqual value: 'BufferedReader', scopes: scopes.concat ['meta.try.resources.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][1]).toEqual value: ')', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.end.bracket.round.java'] expect(lines[4][2]).toEqual value: ' ', scopes: scopes expect(lines[4][3]).toEqual value: '{', scopes: scopes.concat ['punctuation.section.try.begin.bracket.curly.java'] it 'tokenizes comment inside method body', -> lines = grammar.tokenizeLines ''' class Test { private void method() { /** invalid javadoc comment */ /* inline comment */ // single-line comment } } ''' expect(lines[3][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[3][2]).toEqual value: '* invalid javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[3][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][2]).toEqual value: ' inline comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[4][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[5][2]).toEqual value: ' single-line comment', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java'] it 'tokenizes single-line javadoc comment', -> lines = grammar.tokenizeLines ''' /** single-line javadoc comment */ class Test { private int variable; } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[0][1]).toEqual value: ' single-line javadoc comment ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[0][2]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes javadoc comment inside class body', -> # this checks single line javadoc comment, but the same rules apply for multi-line one lines = grammar.tokenizeLines ''' enum Test { /** javadoc comment */ } class Test { /** javadoc comment */ } ''' expect(lines[1][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java'] expect(lines[1][2]).toEqual value: '*/', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][2]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes inline comment inside method signature', -> # this checks usage of inline /*...*/ comments mixing with parameters lines = grammar.tokenizeLines ''' class A { public A(int a, /* String b,*/ boolean c) { } public void methodA(int a /*, String b */) { } private void methodB(/* int a, */String b) { } protected void methodC(/* comment */) { } } ''' expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][5]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][10]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][11]).toEqual value: ' String b,', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[2][12]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][14]).toEqual value: 'booleano', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][16]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][17]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][7]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[4][9]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][11]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][12]).toEqual value: ', String b ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[4][13]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][14]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[6][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][8]).toEqual value: ' int a, ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[6][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][10]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[6][12]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[6][13]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[8][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][8]).toEqual value: ' comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[8][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][10]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] it 'tokenizes multi-line basic javadoc comment', -> lines = grammar.tokenizeLines ''' /** * @author <NAME> * @deprecated description * @see reference * @since version * @version version */ class Test { } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: '@author', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[1][2]).toEqual value: ' <NAME>', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[2][1]).toEqual value: '@deprecated', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[2][2]).toEqual value: ' description', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[3][1]).toEqual value: '@see', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][2]).toEqual value: ' reference', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@since', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[5][1]).toEqual value: '@version', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][0]).toEqual value: ' ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][1]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes `param` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Increment number. * @param num value to increment. */ public void inc(int num) { num += 1; } } ''' expect(lines[4][1]).toEqual value: '@param', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'num', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][4]).toEqual value: ' value to increment.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `exception`/`throws` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * @throws IllegalStateException reason * @exception IllegalStateException reason */ public void fail() { throw new IllegalStateException(); } } ''' expect(lines[3][1]).toEqual value: '@throws', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[3][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@exception', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[4][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `link` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Use {@link #method()} * Use {@link #method(int a)} * Use {@link Class#method(int a)} * Use {@link Class#method (int a, int b)} * @link #method() * Use {@link Class#method$(int a) label {@link Class#method()}} */ public int test() { return -1; } } ''' expect(lines[3][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[3][4]).toEqual value: 'method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][4]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[5][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[5][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][6]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[6][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[6][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[6][6]).toEqual value: 'method (int a, int b)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[7][0]).toEqual value: ' * @link #method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[8][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[8][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][6]).toEqual value: 'method$(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[8][7]).toEqual value: ' label {@link Class#method()}}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes class-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes method-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public int func() { List<Integer> list = new ArrayList<Integer>(); { int a = 1; list.add(a); } return 1; } } ''' expect(lines[4][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[5][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][1]).toEqual value: 'list', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[6][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes static initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); static { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: 'static', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java']
true
describe 'Java grammar', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage('language-java') runs -> grammar = atom.grammars.grammarForScopeName('source.java') it 'parses the grammar', -> expect(grammar).toBeTruthy() expect(grammar.scopeName).toBe 'source.java' it 'tokenizes this with `.this` class', -> {tokens} = grammar.tokenizeLine 'this.x' expect(tokens[0]).toEqual value: 'this', scopes: ['source.java', 'variable.language.this.java'] it 'tokenizes braces', -> {tokens} = grammar.tokenizeLine '(3 + 5) + a[b]' expect(tokens[0]).toEqual value: '(', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[6]).toEqual value: ')', scopes: ['source.java', 'punctuation.bracket.round.java'] expect(tokens[10]).toEqual value: '[', scopes: ['source.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: ']', scopes: ['source.java', 'punctuation.bracket.square.java'] {tokens} = grammar.tokenizeLine 'a(b)' expect(tokens[1]).toEqual value: '(', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[3]).toEqual value: ')', scopes: ['source.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' class A<String> { public int[][] something(String[][] hello) { } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][5]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.begin.bracket.curly.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.square.java'] expect(lines[2][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java'] expect(lines[2][10]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][12]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][13]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][14]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][15]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.square.java'] expect(lines[2][18]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] expect(lines[5][0]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'punctuation.section.class.end.bracket.curly.java'] it 'tokenizes punctuation', -> {tokens} = grammar.tokenizeLine 'int a, b, c;' expect(tokens[3]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[6]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[9]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a.b(1, 2, c);' expect(tokens[1]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[5]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[8]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[11]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'a . b' expect(tokens[2]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine 'class A implements B, C' expect(tokens[7]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.definition.class.implemented.interfaces.java', 'punctuation.separator.delimiter.java'] it 'tokenizes the `package` keyword', -> {tokens} = grammar.tokenizeLine 'package java.util.example;' expect(tokens[0]).toEqual value: 'package', scopes: ['source.java', 'meta.package.java', 'keyword.other.package.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.package.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.package.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'package java.Hi;' expect(tokens[4]).toEqual value: 'H', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java'] {tokens} = grammar.tokenizeLine 'package java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'package java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.package.java', 'storage.modifier.package.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes the `import` keyword', -> {tokens} = grammar.tokenizeLine 'import java.util.Example;' expect(tokens[0]).toEqual value: 'import', scopes: ['source.java', 'meta.import.java', 'keyword.other.import.java'] expect(tokens[1]).toEqual value: ' ', scopes: ['source.java', 'meta.import.java'] expect(tokens[2]).toEqual value: 'java', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'punctuation.separator.java'] expect(tokens[4]).toEqual value: 'util', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] expect(tokens[7]).toEqual value: ';', scopes: ['source.java', 'meta.import.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'import java.util.*;' expect(tokens[6]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'variable.language.wildcard.java'] {tokens} = grammar.tokenizeLine 'import static java.lang.Math.PI;' expect(tokens[2]).toEqual value: 'static', scopes: ['source.java', 'meta.import.java', 'storage.modifier.java'] {tokens} = grammar.tokenizeLine 'import java.3a;' expect(tokens[4]).toEqual value: '3', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.-hi;' expect(tokens[4]).toEqual value: '-', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java._;' expect(tokens[4]).toEqual value: '_', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.__;' expect(tokens[4]).toEqual value: '__', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java.**;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.a*;' expect(tokens[5]).toEqual value: '*', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.int;' expect(tokens[4]).toEqual value: 'int', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.interesting;' expect(tokens[4]).toEqual value: 'interesting', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java'] {tokens} = grammar.tokenizeLine 'import java..hi;' expect(tokens[4]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] {tokens} = grammar.tokenizeLine 'import java.;' expect(tokens[3]).toEqual value: '.', scopes: ['source.java', 'meta.import.java', 'storage.modifier.import.java', 'invalid.illegal.character_not_allowed_here.java'] it 'tokenizes classes', -> lines = grammar.tokenizeLines ''' class Thing { int x; } ''' expect(lines[0][0]).toEqual value: 'class', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Thing', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'entity.name.type.class.java'] it 'tokenizes enums', -> lines = grammar.tokenizeLines ''' enum Letters { /* Comment about A */ A, // Comment about B B } ''' comment = ['source.java', 'meta.enum.java', 'comment.block.java'] commentDefinition = comment.concat('punctuation.definition.comment.java') expect(lines[0][0]).toEqual value: 'enum', scopes: ['source.java', 'meta.enum.java', 'storage.modifier.java'] expect(lines[0][2]).toEqual value: 'Letters', scopes: ['source.java', 'meta.enum.java', 'entity.name.type.enum.java'] expect(lines[0][4]).toEqual value: '{', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.begin.bracket.curly.java'] expect(lines[1][1]).toEqual value: '/*', scopes: commentDefinition expect(lines[1][2]).toEqual value: ' Comment about A ', scopes: comment expect(lines[1][3]).toEqual value: '*/', scopes: commentDefinition expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.enum.java', 'constant.other.enum.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.enum.java', 'punctuation.section.enum.end.bracket.curly.java'] it 'does not catastrophically backtrack when tokenizing large enums (regression)', -> # https://github.com/atom/language-java/issues/103 # This test 'fails' if it runs for an absurdly long time without completing. # It should pass almost immediately just like all the other tests. enumContents = 'AAAAAAAAAAA, BBBBBBBBBB, CCCCCCCCCC, DDDDDDDDDD, EEEEEEEEEE, FFFFFFFFFF, '.repeat(50) lines = grammar.tokenizeLines """ public enum test { #{enumContents} } """ expect(lines[0][2]).toEqual value: 'enum', scopes: ['source.java', 'meta.class.java', 'meta.class.identifier.java', 'storage.modifier.java'] it 'tokenizes methods', -> lines = grammar.tokenizeLines ''' class A { A(int a, int b) { } } ''' expect(lines[2][1]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][5]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][11]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'punctuation.section.method.end.bracket.curly.java'] it 'tokenizes `final` in class method', -> lines = grammar.tokenizeLines ''' class A { public int doSomething(final int finalScore, final int scorefinal) { return finalScore; } } ''' expect(lines[2][7]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][11]).toEqual value: 'finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][14]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.java'] expect(lines[2][18]).toEqual value: 'scorefinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: ' finalScore', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] describe 'numbers', -> describe 'integers', -> it 'tokenizes hexadecimal integers', -> {tokens} = grammar.tokenizeLine '0x0' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0X0' expect(tokens[0]).toEqual value: '0X0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567ABCDEF' expect(tokens[0]).toEqual value: '0x1234567ABCDEF', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x1234567aBcDEf' expect(tokens[0]).toEqual value: '0x1234567aBcDEf', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x3746A4l' expect(tokens[0]).toEqual value: '0x3746A4l', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xC3L' expect(tokens[0]).toEqual value: '0xC3L', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0_1B' expect(tokens[0]).toEqual value: '0x0_1B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_B' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_B', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xCF______3_2_A_73_BL' expect(tokens[0]).toEqual value: '0xCF______3_2_A_73_BL', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x_0' expect(tokens[0]).toEqual value: '0x_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x_' expect(tokens[0]).toEqual value: '0x_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCQ' expect(tokens[0]).toEqual value: '0x123ABCQ', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC$' expect(tokens[0]).toEqual value: '0x123ABC$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABC_L' expect(tokens[0]).toEqual value: '0x123ABC_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x123ABCLl' expect(tokens[0]).toEqual value: '0x123ABCLl', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0x123ABC' expect(tokens[0]).toEqual value: 'a0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0x123ABC' expect(tokens[0]).toEqual value: '$0x123ABC', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1x0' expect(tokens[0]).toEqual value: '1x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0x1' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes binary literals', -> {tokens} = grammar.tokenizeLine '0b0' expect(tokens[0]).toEqual value: '0b0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0B0' expect(tokens[0]).toEqual value: '0B0', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10101010010101' expect(tokens[0]).toEqual value: '0b10101010010101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b10_101__010______01_0_101' expect(tokens[0]).toEqual value: '0b10_101__010______01_0_101', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111l' expect(tokens[0]).toEqual value: '0b1111l', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b1111L' expect(tokens[0]).toEqual value: '0b1111L', scopes: ['source.java', 'constant.numeric.binary.java'] {tokens} = grammar.tokenizeLine '0b11__01l' expect(tokens[0]).toEqual value: '0b11__01l', scopes: ['source.java', 'constant.numeric.binary.java'] # Invalid {tokens} = grammar.tokenizeLine '0b_0' expect(tokens[0]).toEqual value: '0b_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b_' expect(tokens[0]).toEqual value: '0b_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b0_' expect(tokens[0]).toEqual value: '0b0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b1001010102' expect(tokens[0]).toEqual value: '0b1001010102', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Q' expect(tokens[0]).toEqual value: '0b100101010Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010$' expect(tokens[0]).toEqual value: '0b100101010$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0b100101010' expect(tokens[0]).toEqual value: 'a0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0b100101010' expect(tokens[0]).toEqual value: '$0b100101010', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010Ll' expect(tokens[0]).toEqual value: '0b100101010Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0b100101010_L' expect(tokens[0]).toEqual value: '0b100101010_L', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1b0' expect(tokens[0]).toEqual value: '1b0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.0b100101010' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes octal literals', -> {tokens} = grammar.tokenizeLine '00' expect(tokens[0]).toEqual value: '00', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '01234567' expect(tokens[0]).toEqual value: '01234567', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263_3251___3625_1_4' expect(tokens[0]).toEqual value: '07263_3251___3625_1_4', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263l' expect(tokens[0]).toEqual value: '07263l', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '07263L' expect(tokens[0]).toEqual value: '07263L', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '011__24l' expect(tokens[0]).toEqual value: '011__24l', scopes: ['source.java', 'constant.numeric.octal.java'] # Invalid {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '0_' expect(tokens[0]).toEqual value: '0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0_0' expect(tokens[0]).toEqual value: '0_0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '01_' expect(tokens[0]).toEqual value: '01_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '02637242638' expect(tokens[0]).toEqual value: '02637242638', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Q' expect(tokens[0]).toEqual value: '0263724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263$' expect(tokens[0]).toEqual value: '0263724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a0263724263' expect(tokens[0]).toEqual value: 'a0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$0263724263' expect(tokens[0]).toEqual value: '$0263724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263Ll' expect(tokens[0]).toEqual value: '0263724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0263724263_L' expect(tokens[0]).toEqual value: '0263724263_L', scopes: ['source.java'] it 'tokenizes numeric integers', -> {tokens} = grammar.tokenizeLine '0' expect(tokens[0]).toEqual value: '0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '123456789' expect(tokens[0]).toEqual value: '123456789', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '362__2643_0_7' expect(tokens[0]).toEqual value: '362__2643_0_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738L' expect(tokens[0]).toEqual value: '29473923603492738L', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '29473923603492738l' expect(tokens[0]).toEqual value: '29473923603492738l', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '2947_39___23__60_3_4______92738l' expect(tokens[0]).toEqual value: '2947_39___23__60_3_4______92738l', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '01' expect(tokens[0]).toEqual value: '01', scopes: ['source.java', 'constant.numeric.octal.java'] {tokens} = grammar.tokenizeLine '1_' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Q' expect(tokens[0]).toEqual value: '2639724263Q', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263$' expect(tokens[0]).toEqual value: '2639724263$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a2639724263' expect(tokens[0]).toEqual value: 'a2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$2639724263' expect(tokens[0]).toEqual value: '$2639724263', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263Ll' expect(tokens[0]).toEqual value: '2639724263Ll', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '2639724263_L' expect(tokens[0]).toEqual value: '2639724263_L', scopes: ['source.java'] describe 'floats', -> it 'tokenizes hexadecimal floats', -> {tokens} = grammar.tokenizeLine '0x0P0' expect(tokens[0]).toEqual value: '0x0P0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0x0p0' expect(tokens[0]).toEqual value: '0x0p0', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xDp3746' expect(tokens[0]).toEqual value: '0xDp3746', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD__3p3_7_46' expect(tokens[0]).toEqual value: '0xD__3p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.p3_7_46' expect(tokens[0]).toEqual value: '0xD3.p3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp+3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp+3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46F' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46F', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46D' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46D', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp3_7_46d' expect(tokens[0]).toEqual value: '0xD3.17_Fp3_7_46d', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-3_7_46f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-3_7_46f', scopes: ['source.java', 'constant.numeric.hex.java'] {tokens} = grammar.tokenizeLine '0xD3.17_Fp-0f' expect(tokens[0]).toEqual value: '0xD3.17_Fp-0f', scopes: ['source.java', 'constant.numeric.hex.java'] # Invalid {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pA' expect(tokens[0]).toEqual value: '0x0pA', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0pF' expect(tokens[0]).toEqual value: '0x0pF', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p_' expect(tokens[0]).toEqual value: '0x0p_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_p1' expect(tokens[0]).toEqual value: '0x0_p1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p1_' expect(tokens[0]).toEqual value: '0x0p1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+-2' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0p+2Ff' expect(tokens[0]).toEqual value: '0x0p', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0._p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0_.p2' expect(tokens[0]).toEqual value: '0x0_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0..p2' expect(tokens[0]).toEqual value: '0x0', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0x0Pp2' expect(tokens[0]).toEqual value: '0x0Pp2', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '0xp2' expect(tokens[0]).toEqual value: '0xp2', scopes: ['source.java'] it 'tokenizes numeric floats', -> {tokens} = grammar.tokenizeLine '1.' expect(tokens[0]).toEqual value: '1.', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0' expect(tokens[0]).toEqual value: '1.0', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1273.47363' expect(tokens[0]).toEqual value: '1273.47363', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1_2.4_7__89_5' expect(tokens[0]).toEqual value: '1_2.4_7__89_5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.F' expect(tokens[0]).toEqual value: '1.F', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.f' expect(tokens[0]).toEqual value: '1.f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.D' expect(tokens[0]).toEqual value: '1.D', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.d' expect(tokens[0]).toEqual value: '1.d', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0f' expect(tokens[0]).toEqual value: '1.0f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.0_7f' expect(tokens[0]).toEqual value: '1.0_7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.E5' expect(tokens[0]).toEqual value: '1.E5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5' expect(tokens[0]).toEqual value: '1.e5', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.e5_7' expect(tokens[0]).toEqual value: '1.e5_7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e58_26' expect(tokens[0]).toEqual value: '1.6e58_26', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.6e8f' expect(tokens[0]).toEqual value: '1.6e8f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7' expect(tokens[0]).toEqual value: '1.78e+7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e-7' expect(tokens[0]).toEqual value: '1.78e-7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '1.78e+7f' expect(tokens[0]).toEqual value: '1.78e+7f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.7' expect(tokens[0]).toEqual value: '.7', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.726' expect(tokens[0]).toEqual value: '.726', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '.72__6e97_5632f' expect(tokens[0]).toEqual value: '.72__6e97_5632f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3' expect(tokens[0]).toEqual value: '7_26e+52_3', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26e+52_3f' expect(tokens[0]).toEqual value: '7_26e+52_3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '3f' expect(tokens[0]).toEqual value: '3f', scopes: ['source.java', 'constant.numeric.decimal.java'] {tokens} = grammar.tokenizeLine '7_26f' expect(tokens[0]).toEqual value: '7_26f', scopes: ['source.java', 'constant.numeric.decimal.java'] # Invalid {tokens} = grammar.tokenizeLine '1e' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '.e' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] {tokens} = grammar.tokenizeLine '1_.' expect(tokens[0]).toEqual value: '1_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_.' expect(tokens[0]).toEqual value: '_', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1._1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '_1.1' expect(tokens[0]).toEqual value: '_1', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '1.1_' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1e++7' expect(tokens[0]).toEqual value: '1e', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.ee5' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.Ff' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.e' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1..1' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine 'a1' expect(tokens[0]).toEqual value: 'a1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1a' expect(tokens[0]).toEqual value: '1a', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.q' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.3fa' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_f' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1.1_e3' expect(tokens[0]).toEqual value: '1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$1' expect(tokens[0]).toEqual value: '$1', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '1$' expect(tokens[0]).toEqual value: '1$', scopes: ['source.java'] {tokens} = grammar.tokenizeLine '$.1' expect(tokens[0]).toEqual value: '$', scopes: ['source.java', 'variable.other.object.java'] {tokens} = grammar.tokenizeLine '.1$' expect(tokens[0]).toEqual value: '.', scopes: ['source.java', 'punctuation.separator.period.java'] it 'tokenizes `final` in class fields', -> lines = grammar.tokenizeLines ''' class A { private final int finala = 0; final private int bfinal = 1; } ''' expect(lines[2][3]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][7]).toEqual value: 'finala', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[3][1]).toEqual value: 'final', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][7]).toEqual value: 'bfinal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes method-local variables', -> lines = grammar.tokenizeLines ''' class A { public void fn() { String someString; String assigned = "PI:NAME:<NAME>END_PI"; int primitive = 5; } } ''' expect(lines[4][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'someString', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[5][3]).toEqual value: 'assigned', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][8]).toEqual value: "PI:NAME:<NAME>END_PI", scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(lines[6][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][3]).toEqual value: 'primitive', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][7]).toEqual value: '5', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] it 'tokenizes function and method calls', -> lines = grammar.tokenizeLines ''' class A { A() { hello(); hello(a, 1, "hello"); $hello(); this.hello(); this . hello(a, b); } } ''' expect(lines[4][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[4][2]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][3]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java'] expect(lines[5][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'punctuation.separator.delimiter.java'] expect(lines[5][6]).toEqual value: '1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'constant.numeric.decimal.java'] expect(lines[5][9]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(lines[5][11]).toEqual value: '"', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(lines[5][13]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[6][1]).toEqual value: '$hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: 'this', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.language.this.java'] expect(lines[7][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[7][3]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[7][5]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[8][3]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(lines[8][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][5]).toEqual value: 'hello', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[8][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java'] expect(lines[8][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(lines[8][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes objects and properties', -> lines = grammar.tokenizeLines ''' class A { A() { object.property; object.Property; Object.property; object . property; $object.$property; object.property1.property2; object.method().property; object.property.method(); object.123illegal; } } ''' expect(lines[4][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[4][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[4][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[4][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] expect(lines[5][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'Property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[6][1]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[7][5]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[8][1]).toEqual value: '$object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[8][3]).toEqual value: '$property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[9][3]).toEqual value: 'property1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[9][5]).toEqual value: 'property2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[10][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[10][3]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[10][7]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.property.java'] expect(lines[11][3]).toEqual value: 'property', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.property.java'] expect(lines[11][5]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[12][1]).toEqual value: 'object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[12][2]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.separator.period.java'] expect(lines[12][3]).toEqual value: '123illegal', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'invalid.illegal.identifier.java'] expect(lines[12][4]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.terminator.java'] it 'tokenizes generics', -> lines = grammar.tokenizeLines ''' class A<T extends A & B, String, Integer> { HashMap<Integer, String> map = new HashMap<>(); CodeMap<String, ? extends ArrayList> codemap; C(Map<?, ? extends List<?>> m) {} Map<Integer, String> method() {} private Object otherMethod() { return null; } } ''' expect(lines[0][3]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[0][4]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][5]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][6]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'storage.modifier.extends.java'] expect(lines[0][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][8]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][9]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][10]).toEqual value: '&', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.types.java'] expect(lines[0][11]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][12]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][13]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][14]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][15]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][16]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'punctuation.separator.delimiter.java'] expect(lines[0][17]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java'] expect(lines[0][18]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'storage.type.generic.java'] expect(lines[0][19]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'punctuation.bracket.angle.java'] expect(lines[2][1]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[2][6]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[2][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][9]).toEqual value: 'map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][15]).toEqual value: 'HashMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[2][16]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[2][17]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][1]).toEqual value: 'CodeMap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[3][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][3]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[3][6]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.wildcard.java'] expect(lines[3][8]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.modifier.extends.java'] expect(lines[3][10]).toEqual value: 'ArrayList', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[3][11]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[3][13]).toEqual value: 'codemap', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][1]).toEqual value: 'C', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[4][3]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][5]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[4][8]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][10]).toEqual value: 'extends', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.modifier.extends.java'] expect(lines[4][12]).toEqual value: 'List', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[4][13]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][14]).toEqual value: '?', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.generic.wildcard.java'] expect(lines[4][15]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][16]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.bracket.angle.java'] expect(lines[4][18]).toEqual value: 'm', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[5][1]).toEqual value: 'Map', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[5][2]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.generic.java'] expect(lines[5][7]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'punctuation.bracket.angle.java'] expect(lines[5][9]).toEqual value: 'method', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[6][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.return-type.java', 'storage.type.java'] expect(lines[6][5]).toEqual value: 'otherMethod', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] it 'tokenizes generics and primitive arrays declarations', -> lines = grammar.tokenizeLines ''' class A<T> { private B<T>[] arr; private int[][] two = null; } ''' expect(lines[1][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[1][3]).toEqual value: 'B', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '<', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][5]).toEqual value: 'T', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.generic.java'] expect(lines[1][6]).toEqual value: '>', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.angle.java'] expect(lines[1][7]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][8]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[1][10]).toEqual value: 'arr', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[1][11]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[2][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[2][9]).toEqual value: 'two', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][11]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[2][13]).toEqual value: 'null', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.language.java'] expect(lines[2][14]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] it 'tokenizes lambda expressions', -> {tokens} = grammar.tokenizeLine '(String s1) -> s1.length() - outer.length();' expect(tokens[1]).toEqual value: 'String', scopes: ['source.java', 'storage.type.java'] expect(tokens[5]).toEqual value: '->', scopes: ['source.java', 'storage.type.function.arrow.java'] expect(tokens[8]).toEqual value: '.', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.period.java'] expect(tokens[10]).toEqual value: '(', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[11]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: '-', scopes: ['source.java', 'keyword.operator.arithmetic.java'] it 'tokenizes `new` statements', -> {tokens} = grammar.tokenizeLine 'int[] list = new int[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[9]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[10]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'boolean[] list = new boolean[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[10];' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[11]).toEqual value: '[', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[12]).toEqual value: '10', scopes: ['source.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(tokens[13]).toEqual value: ']', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(tokens[14]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[]{"hi", "abc", "etc"};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'String', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[15]).toEqual value: 'hi', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[16]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] expect(tokens[17]).toEqual value: ',', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(tokens[18]).toEqual value: ' ', scopes: ['source.java', 'meta.definition.variable.java'] expect(tokens[27]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[28]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = new A[]{new A(), new A()};' expect(tokens[8]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[10]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(tokens[13]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[14]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[16]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[23]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[24]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[25]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[26]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.bracket.curly.java'] expect(tokens[27]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'A[] arr = {new A(), new A()};' expect(tokens[8]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(tokens[9]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[11]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[12]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[13]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[16]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[18]).toEqual value: 'A', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[19]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[20]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[21]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'punctuation.section.block.end.bracket.curly.java'] expect(tokens[22]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'String a = (valid ? new Date().toString() + " : " : "");' expect(tokens[16]).toEqual value: 'toString', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[17]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: '+', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.operator.arithmetic.java'] expect(tokens[23]).toEqual value: ' : ', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java'] expect(tokens[26]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[28]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[29]).toEqual value: '"', scopes: ['source.java', 'meta.definition.variable.java', 'string.quoted.double.java', 'punctuation.definition.string.end.java'] {tokens} = grammar.tokenizeLine 'String[] list = new String[variable];' expect(tokens[12]).toEqual value: 'variable', scopes: ['source.java', 'meta.definition.variable.java'] {tokens} = grammar.tokenizeLine 'Point point = new Point(1, 4);' expect(tokens[6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[9]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[14]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[15]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'Point point = true ? new Point(1, 4) : new Point(0, 0);' expect(tokens[8]).toEqual value: '?', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[10]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[12]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(tokens[13]).toEqual value: '(', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[20]).toEqual value: ':', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.ternary.java'] expect(tokens[22]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(tokens[31]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] {tokens} = grammar.tokenizeLine 'map.put(key, new Value(value), "extra");' expect(tokens[12]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'meta.function-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(tokens[13]).toEqual value: ',', scopes: ['source.java', 'meta.method-call.java', 'punctuation.separator.delimiter.java'] expect(tokens[15]).toEqual value: '"', scopes: ['source.java', 'meta.method-call.java', 'string.quoted.double.java', 'punctuation.definition.string.begin.java'] expect(tokens[18]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' map.put(key, new Value(value) ); ''' expect(lines[2][0]).toEqual value: ')', scopes: ['source.java', 'meta.method-call.java', 'punctuation.definition.parameters.end.bracket.round.java'] lines = grammar.tokenizeLines ''' Point point = new Point() { public void something(x) { int y = x; } }; ''' expect(lines[0][6]).toEqual value: 'new', scopes: ['source.java', 'meta.definition.variable.java', 'keyword.control.new.java'] expect(lines[0][8]).toEqual value: 'Point', scopes: ['source.java', 'meta.definition.variable.java', 'meta.function-call.java', 'entity.name.function.java'] expect(lines[1][0]).toEqual value: '{', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.begin.bracket.curly.java'] expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[6][0]).toEqual value: '}', scopes: ['source.java', 'meta.definition.variable.java', 'meta.inner-class.java', 'punctuation.section.inner-class.end.bracket.curly.java'] expect(lines[6][1]).toEqual value: ';', scopes: ['source.java', 'punctuation.terminator.java'] it 'tokenizes the `instanceof` operator', -> {tokens} = grammar.tokenizeLine 'instanceof' expect(tokens[0]).toEqual value: 'instanceof', scopes: ['source.java', 'keyword.operator.instanceof.java'] it 'tokenizes class fields', -> lines = grammar.tokenizeLines ''' class Test { private int variable; public Object[] variable; private int variable = 3; private int variable1, variable2, variable3; private int variable1, variable2 = variable; private int variable;// = 3; public String CAPITALVARIABLE; private int[][] somevar = new int[10][12]; private int 1invalid; private Integer $tar_war$; double a,b,c;double d; String[] primitiveArray; } ''' expect(lines[2][1]).toEqual value: 'private', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[2][2]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[2][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[2][4]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[2][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[2][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[3][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: 'Object', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[3][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[3][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[4][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[4][6]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][7]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[4][8]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[4][9]).toEqual value: '3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[4][10]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[5][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[5][7]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[5][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][11]).toEqual value: 'variable3', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[6][5]).toEqual value: 'variable1', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][8]).toEqual value: 'variable2', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][10]).toEqual value: '=', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'keyword.operator.assignment.java'] expect(lines[6][11]).toEqual value: ' variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java'] expect(lines[6][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][5]).toEqual value: 'variable', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[7][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[7][7]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[8][5]).toEqual value: 'CAPITALVARIABLE', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[8][6]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[9][3]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][4]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][5]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][6]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][7]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][9]).toEqual value: 'somevar', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[9][15]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.array.java'] expect(lines[9][16]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][17]).toEqual value: '10', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][18]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][19]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[9][20]).toEqual value: '12', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'constant.numeric.decimal.java'] expect(lines[9][21]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[10][2]).toEqual value: ' int 1invalid', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java'] expect(lines[11][3]).toEqual value: 'Integer', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[11][5]).toEqual value: '$tar_war$', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][1]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][4]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][5]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][6]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.separator.delimiter.java'] expect(lines[12][7]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][8]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[12][9]).toEqual value: 'double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[12][11]).toEqual value: 'd', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[12][12]).toEqual value: ';', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.terminator.java'] expect(lines[13][1]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.object.array.java'] expect(lines[13][2]).toEqual value: '[', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][3]).toEqual value: ']', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'punctuation.bracket.square.java'] expect(lines[13][5]).toEqual value: 'primitiveArray', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes qualified storage types', -> lines = grammar.tokenizeLines ''' class Test { private Test.Double something; } ''' expect(lines[1][3]).toEqual value: 'Test', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][4]).toEqual value: '.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java', 'punctuation.separator.period.java'] expect(lines[1][5]).toEqual value: 'Double', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[1][7]).toEqual value: 'something', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] it 'tokenizes try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { errorProneMethod(); } catch (RuntimeException re) { handleRuntimeException(re); } catch (Exception e) { String variable = "assigning for some reason"; } finally { // Relax, it's over new Thingie().call(); } } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[3][1]).toEqual value: 'errorProneMethod', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[4][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.catch.java' expect(lines[4][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[4][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[4][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[4][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[4][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[5][1]).toEqual value: 'handleRuntimeException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[6][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] expect(lines[6][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[6][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[6][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[6][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[6][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[7][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[7][3]).toEqual value: 'variable', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.push 'meta.finally.java' expect(lines[8][3]).toEqual value: 'finally', scopes: scopeStack.concat ['keyword.control.finally.java'] expect(lines[8][5]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.finally.begin.bracket.curly.java'] scopeStack.push 'meta.finally.body.java' expect(lines[9][1]).toEqual value: '//', scopes: scopeStack.concat ['comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[10][1]).toEqual value: 'new', scopes: scopeStack.concat ['keyword.control.new.java'] scopeStack.pop() expect(lines[11][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.finally.end.bracket.curly.java'] it 'tokenizes nested try-catch-finally blocks', -> lines = grammar.tokenizeLines ''' class Test { public void fn() { try { try { String nested; } catch (Exception e) { handleNestedException(); } } catch (RuntimeException re) {} } } ''' scopeStack = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java'] scopeStack.push 'meta.try.java' expect(lines[2][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopeStack expect(lines[2][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java', 'meta.try.java' expect(lines[3][1]).toEqual value: 'try', scopes: scopeStack.concat ['keyword.control.try.java'] expect(lines[3][2]).toEqual value: ' ', scopes: scopeStack expect(lines[3][3]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.try.begin.bracket.curly.java'] scopeStack.push 'meta.try.body.java' expect(lines[4][1]).toEqual value: 'String', scopes: scopeStack.concat ['meta.definition.variable.java', 'storage.type.java'] expect(lines[4][3]).toEqual value: 'nested', scopes: scopeStack.concat ['meta.definition.variable.java', 'variable.other.definition.java'] scopeStack.pop() expect(lines[5][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[5][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[5][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[5][4]).toEqual value: ' ', scopes: scopeStack expect(lines[5][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[5][6]).toEqual value: 'Exception', scopes: scopeStack.concat ['storage.type.java'] expect(lines[5][7]).toEqual value: ' ', scopes: scopeStack expect(lines[5][8]).toEqual value: 'e', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[5][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[5][10]).toEqual value: ' ', scopes: scopeStack expect(lines[5][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] scopeStack.push 'meta.catch.body.java' expect(lines[6][1]).toEqual value: 'handleNestedException', scopes: scopeStack.concat ['meta.function-call.java', 'entity.name.function.java'] scopeStack.pop() expect(lines[7][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] scopeStack.pop() scopeStack.pop() expect(lines[8][1]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.try.end.bracket.curly.java'] scopeStack.pop() expect(lines[8][2]).toEqual value: ' ', scopes: scopeStack scopeStack.push 'meta.catch.java' expect(lines[8][3]).toEqual value: 'catch', scopes: scopeStack.concat ['keyword.control.catch.java'] expect(lines[8][4]).toEqual value: ' ', scopes: scopeStack expect(lines[8][5]).toEqual value: '(', scopes: scopeStack.concat ['punctuation.definition.parameters.begin.bracket.round.java'] scopeStack.push 'meta.catch.parameters.java' expect(lines[8][6]).toEqual value: 'RuntimeException', scopes: scopeStack.concat ['storage.type.java'] expect(lines[8][7]).toEqual value: ' ', scopes: scopeStack expect(lines[8][8]).toEqual value: 're', scopes: scopeStack.concat ['variable.parameter.java'] scopeStack.pop() expect(lines[8][9]).toEqual value: ')', scopes: scopeStack.concat ['punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][10]).toEqual value: ' ', scopes: scopeStack expect(lines[8][11]).toEqual value: '{', scopes: scopeStack.concat ['punctuation.section.catch.begin.bracket.curly.java'] expect(lines[8][12]).toEqual value: '}', scopes: scopeStack.concat ['punctuation.section.catch.end.bracket.curly.java'] it 'tokenizes try-catch blocks with resources', -> lines = grammar.tokenizeLines ''' class Test { private void fn() { try ( BufferedReader in = new BufferedReader(); ) { // stuff } } } ''' scopes = ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.try.java'] expect(lines[2][1]).toEqual value: 'try', scopes: scopes.concat ['keyword.control.try.java'] expect(lines[2][2]).toEqual value: ' ', scopes: scopes expect(lines[2][3]).toEqual value: '(', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.begin.bracket.round.java'] expect(lines[3][1]).toEqual value: 'BufferedReader', scopes: scopes.concat ['meta.try.resources.java', 'meta.definition.variable.java', 'storage.type.java'] expect(lines[4][1]).toEqual value: ')', scopes: scopes.concat ['meta.try.resources.java', 'punctuation.section.try.resources.end.bracket.round.java'] expect(lines[4][2]).toEqual value: ' ', scopes: scopes expect(lines[4][3]).toEqual value: '{', scopes: scopes.concat ['punctuation.section.try.begin.bracket.curly.java'] it 'tokenizes comment inside method body', -> lines = grammar.tokenizeLines ''' class Test { private void method() { /** invalid javadoc comment */ /* inline comment */ // single-line comment } } ''' expect(lines[3][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[3][2]).toEqual value: '* invalid javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[3][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][1]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][2]).toEqual value: ' inline comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java'] expect(lines[4][3]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: '//', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java', 'punctuation.definition.comment.java'] expect(lines[5][2]).toEqual value: ' single-line comment', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'comment.line.double-slash.java'] it 'tokenizes single-line javadoc comment', -> lines = grammar.tokenizeLines ''' /** single-line javadoc comment */ class Test { private int variable; } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[0][1]).toEqual value: ' single-line javadoc comment ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[0][2]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes javadoc comment inside class body', -> # this checks single line javadoc comment, but the same rules apply for multi-line one lines = grammar.tokenizeLines ''' enum Test { /** javadoc comment */ } class Test { /** javadoc comment */ } ''' expect(lines[1][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java'] expect(lines[1][2]).toEqual value: '*/', scopes: ['source.java', 'meta.enum.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][0]).toEqual value: ' /**', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[5][1]).toEqual value: ' javadoc comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][2]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes inline comment inside method signature', -> # this checks usage of inline /*...*/ comments mixing with parameters lines = grammar.tokenizeLines ''' class A { public A(int a, /* String b,*/ boolean c) { } public void methodA(int a /*, String b */) { } private void methodB(/* int a, */String b) { } protected void methodC(/* comment */) { } } ''' expect(lines[2][1]).toEqual value: 'public', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'storage.modifier.java'] expect(lines[2][3]).toEqual value: 'A', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'entity.name.function.java'] expect(lines[2][4]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[2][5]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][7]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][8]).toEqual value: ',', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.separator.delimiter.java'] expect(lines[2][10]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][11]).toEqual value: ' String b,', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[2][12]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[2][14]).toEqual value: 'booleano', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[2][16]).toEqual value: 'c', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[2][17]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[4][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[4][7]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.primitive.java'] expect(lines[4][9]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[4][11]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][12]).toEqual value: ', String b ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[4][13]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[4][14]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[6][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[6][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][8]).toEqual value: ' int a, ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[6][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[6][10]).toEqual value: 'String', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'storage.type.java'] expect(lines[6][12]).toEqual value: 'b', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'variable.parameter.java'] expect(lines[6][13]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] expect(lines[8][6]).toEqual value: '(', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.begin.bracket.round.java'] expect(lines[8][7]).toEqual value: '/*', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][8]).toEqual value: ' comment ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java'] expect(lines[8][9]).toEqual value: '*/', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'comment.block.java', 'punctuation.definition.comment.java'] expect(lines[8][10]).toEqual value: ')', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.identifier.java', 'punctuation.definition.parameters.end.bracket.round.java'] it 'tokenizes multi-line basic javadoc comment', -> lines = grammar.tokenizeLines ''' /** * @author PI:NAME:<NAME>END_PI * @deprecated description * @see reference * @since version * @version version */ class Test { } ''' expect(lines[0][0]).toEqual value: '/**', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] expect(lines[1][1]).toEqual value: '@author', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[1][2]).toEqual value: ' PI:NAME:<NAME>END_PI', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[2][1]).toEqual value: '@deprecated', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[2][2]).toEqual value: ' description', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[3][1]).toEqual value: '@see', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][2]).toEqual value: ' reference', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@since', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[5][1]).toEqual value: '@version', scopes: ['source.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][2]).toEqual value: ' version', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][0]).toEqual value: ' ', scopes: ['source.java', 'comment.block.javadoc.java'] expect(lines[6][1]).toEqual value: '*/', scopes: ['source.java', 'comment.block.javadoc.java', 'punctuation.definition.comment.java'] it 'tokenizes `param` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Increment number. * @param num value to increment. */ public void inc(int num) { num += 1; } } ''' expect(lines[4][1]).toEqual value: '@param', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'num', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][4]).toEqual value: ' value to increment.', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `exception`/`throws` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * @throws IllegalStateException reason * @exception IllegalStateException reason */ public void fail() { throw new IllegalStateException(); } } ''' expect(lines[3][1]).toEqual value: '@throws', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[3][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][1]).toEqual value: '@exception', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: 'IllegalStateException', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[4][4]).toEqual value: ' reason', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes `link` javadoc comment', -> lines = grammar.tokenizeLines ''' class Test { /** * Use {@link #method()} * Use {@link #method(int a)} * Use {@link Class#method(int a)} * Use {@link Class#method (int a, int b)} * @link #method() * Use {@link Class#method$(int a) label {@link Class#method()}} */ public int test() { return -1; } } ''' expect(lines[3][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[3][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[3][4]).toEqual value: 'method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[4][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[4][3]).toEqual value: ' #', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[4][4]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[5][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[5][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[5][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[5][6]).toEqual value: 'method(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[6][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[6][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[6][6]).toEqual value: 'method (int a, int b)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[7][0]).toEqual value: ' * @link #method()', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][2]).toEqual value: '@link', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'keyword.other.documentation.javadoc.java'] expect(lines[8][3]).toEqual value: ' ', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][4]).toEqual value: 'Class', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'entity.name.type.class.java'] expect(lines[8][5]).toEqual value: '#', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] expect(lines[8][6]).toEqual value: 'method$(int a)', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java', 'variable.parameter.java'] expect(lines[8][7]).toEqual value: ' label {@link Class#method()}}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'comment.block.javadoc.java'] it 'tokenizes class-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes method-body block initializer', -> lines = grammar.tokenizeLines ''' class Test { public int func() { List<Integer> list = new ArrayList<Integer>(); { int a = 1; list.add(a); } return 1; } } ''' expect(lines[4][1]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[5][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[5][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[6][1]).toEqual value: 'list', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'variable.other.object.java'] expect(lines[6][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[7][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method.java', 'meta.method.body.java', 'punctuation.section.block.end.bracket.curly.java'] it 'tokenizes static initializer', -> lines = grammar.tokenizeLines ''' class Test { public static HashSet<Integer> set = new HashSet<Integer>(); static { int a = 1; set.add(a); } } ''' expect(lines[3][1]).toEqual value: 'static', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'storage.modifier.java'] expect(lines[3][3]).toEqual value: '{', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.begin.bracket.curly.java'] expect(lines[4][1]).toEqual value: 'int', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'storage.type.primitive.java'] expect(lines[4][3]).toEqual value: 'a', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.definition.variable.java', 'variable.other.definition.java'] expect(lines[5][1]).toEqual value: 'set', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'variable.other.object.java'] expect(lines[5][3]).toEqual value: 'add', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'meta.method-call.java', 'entity.name.function.java'] expect(lines[6][1]).toEqual value: '}', scopes: ['source.java', 'meta.class.java', 'meta.class.body.java', 'punctuation.section.block.end.bracket.curly.java']
[ { "context": "ction_name = rule_queue.shift()\n rule_key = \"#{action_name}_#{separate_url_length}\"\n args = @_prepareArgs rule_queue, rule_key", "end": 722, "score": 0.9847366213798523, "start": 683, "tag": "KEY", "value": "\"#{action_name}_#{separate_url_length}\"" } ]
vendor/assets/javascripts/keybridge/routine_route.js.coffee
eduvo/bootstrap-sass
0
define (require) -> $window = $(window) UrlPath = require 'keybridge/urlpath' class RoutineRoute eventName: "RR:route" path: '' rulesPool: {} _prepareArgs: (rule_queue, rule_key) -> option = {} if option_candidate = @rulesPool[rule_key]?.option_candidate args = [rule_key, option] _.each option_candidate, (value, key) -> option[key] = rule_queue[value] args.push option[key] args go: (rule_queue) -> do @allRouteCallback if @allRouteCallback? rule_queue = @path.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() rule_key = "#{action_name}_#{separate_url_length}" args = @_prepareArgs rule_queue, rule_key $window.trigger "#{@eventName}", args else $window.trigger "#{@eventName}", [@path] @afterCallback?.call @ constructor: -> $window.on "#{@eventName}", (event, route, others...) => if @rulesPool[route]? if @rulesPool[route].callback? @rulesPool[route].callback.apply(@, others) else @rulesPool[route].apply(@, others) else if @default? do @default @rulesPool = {} # Clear rules pool UrlPath.registryAction => @path = UrlPath.getPath() do @go ## Setting route rules get: (rule, callback) -> rule_queue = rule.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() option_candidate = {} _.each rule_queue, (rule, index) -> if (plain_rule = /\:\w+/.exec(rule)[0]?.replace(':','')) isnt '' option_candidate[plain_rule] = index @rulesPool["#{action_name}_#{separate_url_length}"] = callback: callback option_candidate: option_candidate else @rulesPool[rule] = callback this done: -> @path = UrlPath.getPath() do @go if @path isnt '' this after: (@afterCallback) -> this all: (callback) -> @allRouteCallback = callback this trigger: (rule) -> $window.trigger "#{@eventName}", [rule] route: (@rulesPool) -> default: (@default) -> this new RoutineRoute
1358
define (require) -> $window = $(window) UrlPath = require 'keybridge/urlpath' class RoutineRoute eventName: "RR:route" path: '' rulesPool: {} _prepareArgs: (rule_queue, rule_key) -> option = {} if option_candidate = @rulesPool[rule_key]?.option_candidate args = [rule_key, option] _.each option_candidate, (value, key) -> option[key] = rule_queue[value] args.push option[key] args go: (rule_queue) -> do @allRouteCallback if @allRouteCallback? rule_queue = @path.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() rule_key = <KEY> args = @_prepareArgs rule_queue, rule_key $window.trigger "#{@eventName}", args else $window.trigger "#{@eventName}", [@path] @afterCallback?.call @ constructor: -> $window.on "#{@eventName}", (event, route, others...) => if @rulesPool[route]? if @rulesPool[route].callback? @rulesPool[route].callback.apply(@, others) else @rulesPool[route].apply(@, others) else if @default? do @default @rulesPool = {} # Clear rules pool UrlPath.registryAction => @path = UrlPath.getPath() do @go ## Setting route rules get: (rule, callback) -> rule_queue = rule.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() option_candidate = {} _.each rule_queue, (rule, index) -> if (plain_rule = /\:\w+/.exec(rule)[0]?.replace(':','')) isnt '' option_candidate[plain_rule] = index @rulesPool["#{action_name}_#{separate_url_length}"] = callback: callback option_candidate: option_candidate else @rulesPool[rule] = callback this done: -> @path = UrlPath.getPath() do @go if @path isnt '' this after: (@afterCallback) -> this all: (callback) -> @allRouteCallback = callback this trigger: (rule) -> $window.trigger "#{@eventName}", [rule] route: (@rulesPool) -> default: (@default) -> this new RoutineRoute
true
define (require) -> $window = $(window) UrlPath = require 'keybridge/urlpath' class RoutineRoute eventName: "RR:route" path: '' rulesPool: {} _prepareArgs: (rule_queue, rule_key) -> option = {} if option_candidate = @rulesPool[rule_key]?.option_candidate args = [rule_key, option] _.each option_candidate, (value, key) -> option[key] = rule_queue[value] args.push option[key] args go: (rule_queue) -> do @allRouteCallback if @allRouteCallback? rule_queue = @path.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() rule_key = PI:KEY:<KEY>END_PI args = @_prepareArgs rule_queue, rule_key $window.trigger "#{@eventName}", args else $window.trigger "#{@eventName}", [@path] @afterCallback?.call @ constructor: -> $window.on "#{@eventName}", (event, route, others...) => if @rulesPool[route]? if @rulesPool[route].callback? @rulesPool[route].callback.apply(@, others) else @rulesPool[route].apply(@, others) else if @default? do @default @rulesPool = {} # Clear rules pool UrlPath.registryAction => @path = UrlPath.getPath() do @go ## Setting route rules get: (rule, callback) -> rule_queue = rule.split('/') if (separate_url_length = rule_queue.length) > 1 action_name = rule_queue.shift() option_candidate = {} _.each rule_queue, (rule, index) -> if (plain_rule = /\:\w+/.exec(rule)[0]?.replace(':','')) isnt '' option_candidate[plain_rule] = index @rulesPool["#{action_name}_#{separate_url_length}"] = callback: callback option_candidate: option_candidate else @rulesPool[rule] = callback this done: -> @path = UrlPath.getPath() do @go if @path isnt '' this after: (@afterCallback) -> this all: (callback) -> @allRouteCallback = callback this trigger: (rule) -> $window.trigger "#{@eventName}", [rule] route: (@rulesPool) -> default: (@default) -> this new RoutineRoute
[ { "context": "ull\n\nbeforeEach ->\n struct = new Struct name: 'Bob'\n\nit 'key is accessible', ->\n assert.is struct", "end": 100, "score": 0.9976414442062378, "start": 97, "tag": "NAME", "value": "Bob" }, { "context": "ey is accessible', ->\n assert.is struct.name, 'Bob'\n...
packages/core/neft-core/src/struct/index.test.coffee
Neft-io/neftio
23
'use strict' Struct = require './' struct = null beforeEach -> struct = new Struct name: 'Bob' it 'key is accessible', -> assert.is struct.name, 'Bob' it 'key can be changed', -> struct.name = 'Max' assert.is struct.name, 'Max' it 'new key cannot be added', -> error = null try struct.age = 12 catch er error = er assert.ok error assert.is struct.age, undefined it 'old key cannot be deleted', -> error = null try delete struct.name catch er error = er assert.ok error assert.is struct.name, 'Bob' it 'onChange signal is emitted with old value', -> oldValues = [] struct.onNameChange.connect (oldValue) -> oldValues.push(oldValue) struct.name = 'Max' assert.isEqual oldValues, ['Bob'] it 'new value is available in onChange signal', -> newValue = null struct.onNameChange.connect -> newValue = @name struct.name = 'Max' assert.is newValue, 'Max' it 'only keys are enumerable', -> assert.isEqual Object.keys(struct), ['name']
137267
'use strict' Struct = require './' struct = null beforeEach -> struct = new Struct name: '<NAME>' it 'key is accessible', -> assert.is struct.name, '<NAME>' it 'key can be changed', -> struct.name = '<NAME>' assert.is struct.name, '<NAME>' it 'new key cannot be added', -> error = null try struct.age = 12 catch er error = er assert.ok error assert.is struct.age, undefined it 'old key cannot be deleted', -> error = null try delete struct.name catch er error = er assert.ok error assert.is struct.name, '<NAME>' it 'onChange signal is emitted with old value', -> oldValues = [] struct.onNameChange.connect (oldValue) -> oldValues.push(oldValue) struct.name = '<NAME>' assert.isEqual oldValues, ['<NAME>'] it 'new value is available in onChange signal', -> newValue = null struct.onNameChange.connect -> newValue = @name struct.name = '<NAME>' assert.is newValue, '<NAME>' it 'only keys are enumerable', -> assert.isEqual Object.keys(struct), ['name']
true
'use strict' Struct = require './' struct = null beforeEach -> struct = new Struct name: 'PI:NAME:<NAME>END_PI' it 'key is accessible', -> assert.is struct.name, 'PI:NAME:<NAME>END_PI' it 'key can be changed', -> struct.name = 'PI:NAME:<NAME>END_PI' assert.is struct.name, 'PI:NAME:<NAME>END_PI' it 'new key cannot be added', -> error = null try struct.age = 12 catch er error = er assert.ok error assert.is struct.age, undefined it 'old key cannot be deleted', -> error = null try delete struct.name catch er error = er assert.ok error assert.is struct.name, 'PI:NAME:<NAME>END_PI' it 'onChange signal is emitted with old value', -> oldValues = [] struct.onNameChange.connect (oldValue) -> oldValues.push(oldValue) struct.name = 'PI:NAME:<NAME>END_PI' assert.isEqual oldValues, ['PI:NAME:<NAME>END_PI'] it 'new value is available in onChange signal', -> newValue = null struct.onNameChange.connect -> newValue = @name struct.name = 'PI:NAME:<NAME>END_PI' assert.is newValue, 'PI:NAME:<NAME>END_PI' it 'only keys are enumerable', -> assert.isEqual Object.keys(struct), ['name']
[ { "context": "O: when API supports it as per https://github.com/resin-io/hq/pull/949 remove userId\n\t\t\t_.defaults(device, {", "end": 8859, "score": 0.9990300536155701, "start": 8851, "tag": "USERNAME", "value": "resin-io" }, { "context": "stance, it failed to start so far\n\t\t\t\...
src/api-binder.coffee
hippolyt/resin-supervisor
0
Promise = require 'bluebird' _ = require 'lodash' url = require 'url' TypedError = require 'typed-error' PinejsClient = require 'pinejs-client' deviceRegister = require 'resin-register-device' express = require 'express' bodyParser = require 'body-parser' Lock = require 'rwlock' { request, requestOpts } = require './lib/request' { checkTruthy, checkInt } = require './lib/validation' DuplicateUuidError = (err) -> _.startsWith(err.message, '"uuid" must be unique') ExchangeKeyError = class ExchangeKeyError extends TypedError REPORT_SUCCESS_DELAY = 1000 MAX_REPORT_RETRY_DELAY = 60000 INTERNAL_STATE_KEYS = [ 'update_pending', 'update_downloaded', 'update_failed', ] createAPIBinderRouter = (apiBinder) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) router.post '/v1/update', (req, res) -> apiBinder.eventTracker.track('Update notification') if apiBinder.readyForUpdates apiBinder.getAndSetTargetState(req.body.force) .catchReturn() res.sendStatus(204) return router module.exports = class APIBinder constructor: ({ @config, @db, @deviceState, @eventTracker }) -> @resinApi = null @cachedResinApi = null @lastReportedState = { local: {}, dependent: {} } @stateForReport = { local: {}, dependent: {} } @lastTarget = {} @lastTargetStateFetch = process.hrtime() @_targetStateInterval = null @reportPending = false @stateReportErrors = 0 @targetStateFetchErrors = 0 @router = createAPIBinderRouter(this) _lock = new Lock() @_writeLock = Promise.promisify(_lock.async.writeLock) @readyForUpdates = false healthcheck: => @config.getMany([ 'appUpdatePollInterval', 'offlineMode', 'connectivityCheckEnabled' ]) .then (conf) => if conf.offlineMode return true timeSinceLastFetch = process.hrtime(@lastTargetStateFetch) timeSinceLastFetchMs = timeSinceLastFetch[0] * 1000 + timeSinceLastFetch[1] / 1e6 stateFetchHealthy = timeSinceLastFetchMs < 2 * conf.appUpdatePollInterval stateReportHealthy = !conf.connectivityCheckEnabled or !@deviceState.connected or @stateReportErrors < 3 return stateFetchHealthy and stateReportHealthy _lockGetTarget: => @_writeLock('getTarget').disposer (release) -> release() initClient: => @config.getMany([ 'offlineMode', 'apiEndpoint', 'currentApiKey' ]) .then ({ offlineMode, apiEndpoint, currentApiKey }) => if offlineMode console.log('Offline Mode is set, skipping API client initialization') return baseUrl = url.resolve(apiEndpoint, '/v4/') passthrough = _.cloneDeep(requestOpts) passthrough.headers ?= {} passthrough.headers.Authorization = "Bearer #{currentApiKey}" @resinApi = new PinejsClient apiPrefix: baseUrl passthrough: passthrough baseUrlLegacy = url.resolve(apiEndpoint, '/v2/') @resinApiLegacy = new PinejsClient apiPrefix: baseUrlLegacy passthrough: passthrough @cachedResinApi = @resinApi.clone({}, cache: {}) start: => @config.getMany([ 'apiEndpoint', 'offlineMode', 'bootstrapRetryDelay' ]) .then ({ apiEndpoint, offlineMode, bootstrapRetryDelay }) => if offlineMode console.log('Offline Mode is set, skipping API binder initialization') # If we are offline because there is no apiEndpoint, there's a chance # we've went through a deprovision. We need to set the initialConfigReported # value to '', to ensure that when we do re-provision, we'll report # the config and hardward-specific options won't be lost if !Boolean(apiEndpoint) return @config.set({ initialConfigReported: '' }) return console.log('Ensuring device is provisioned') @provisionDevice() .then => @config.getMany([ 'initialConfigReported', 'apiEndpoint' ]) .then ({ initialConfigReported, apiEndpoint }) => # Either we haven't reported our initial config or we've # been re-provisioned if apiEndpoint != initialConfigReported console.log('Reporting initial configuration') @reportInitialConfig(apiEndpoint, bootstrapRetryDelay) .then => console.log('Starting current state report') @startCurrentStateReport() .then => @readyForUpdates = true console.log('Starting target state poll') @startTargetStatePoll() return null fetchDevice: (uuid, apiKey, timeout) => reqOpts = { resource: 'device' options: filter: uuid: uuid passthrough: headers: Authorization: "Bearer #{apiKey}" } @resinApi.get(reqOpts) .get(0) .catchReturn(null) .timeout(timeout) _exchangeKeyAndGetDevice: (opts) -> Promise.try => if !opts? @config.get('provisioningOptions') .then (conf) -> opts = conf .then => # If we have an existing device key we first check if it's valid, because if it is we can just use that if opts.deviceApiKey? @fetchDevice(opts.uuid, opts.deviceApiKey, opts.apiTimeout) .then (device) => if device? return device # If it's not valid/doesn't exist then we try to use the user/provisioning api key for the exchange @fetchDevice(opts.uuid, opts.provisioningApiKey, opts.apiTimeout) .tap (device) -> if not device? throw new ExchangeKeyError("Couldn't fetch device with provisioning key") # We found the device, we can try to register a working device key for it request.postAsync("#{opts.apiEndpoint}/api-key/device/#{device.id}/device-key", { json: true body: apiKey: opts.deviceApiKey headers: Authorization: "Bearer #{opts.provisioningApiKey}" }) .spread (res, body) -> if res.statusCode != 200 throw new ExchangeKeyError("Couldn't register device key with provisioning key") .timeout(opts.apiTimeout) _exchangeKeyAndGetDeviceOrRegenerate: (opts) => @_exchangeKeyAndGetDevice(opts) .tap -> console.log('Key exchange succeeded, all good') .tapCatch ExchangeKeyError, (err) => # If it fails we just have to reregister as a provisioning key doesn't have the ability to change existing devices console.log('Exchanging key failed, having to reregister') @config.regenerateRegistrationFields() _provision: => @config.get('provisioningOptions') .then (opts) => if opts.registered_at? and opts.deviceId? and !opts.provisioningApiKey? return Promise.try => if opts.registered_at? and !opts.deviceId? console.log('Device is registered but no device id available, attempting key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) else if !opts.registered_at? console.log('New device detected. Provisioning...') deviceRegister.register(opts) .timeout(opts.apiTimeout) .catch DuplicateUuidError, => console.log('UUID already registered, trying a key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) .tap -> opts.registered_at = Date.now() else if opts.provisioningApiKey? console.log('Device is registered but we still have an apiKey, attempting key exchange') @_exchangeKeyAndGetDevice(opts) .then ({ id }) => @resinApi.passthrough.headers.Authorization = "Bearer #{opts.deviceApiKey}" configToUpdate = { registered_at: opts.registered_at deviceId: id apiKey: null } @config.set(configToUpdate) .then => @eventTracker.track('Device bootstrap success') # Check if we need to pin the device, regardless of if we provisioned .then => @config.get('pinDevice') .then(JSON.parse) .tapCatch -> console.log('Warning: Malformed pinDevice value in supervisor database') .catchReturn(null) .then (pinValue) => if pinValue? if !pinValue.app? or !pinValue.commit? console.log("Malformed pinDevice fields in supervisor database: #{pinValue}") return console.log('Attempting to pin device to preloaded release...') @pinDevice(pinValue) _provisionOrRetry: (retryDelay) => @eventTracker.track('Device bootstrap') @_provision() .catch (err) => @eventTracker.track('Device bootstrap failed, retrying', { error: err, delay: retryDelay }) Promise.delay(retryDelay).then => @_provisionOrRetry(retryDelay) provisionDevice: => if !@resinApi? throw new Error('Trying to provision device without initializing API client') @config.getMany([ 'provisioned' 'bootstrapRetryDelay' 'apiKey' 'pinDevice' ]) .tap (conf) => if !conf.provisioned or conf.apiKey? or conf.pinDevice? @_provisionOrRetry(conf.bootstrapRetryDelay) provisionDependentDevice: (device) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' 'userId' 'deviceId' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot provision dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to provision a dependent device') # TODO: when API supports it as per https://github.com/resin-io/hq/pull/949 remove userId _.defaults(device, { belongs_to__user: conf.userId is_managed_by__device: conf.deviceId uuid: deviceRegister.generateUniqueKey() registered_at: Math.floor(Date.now() / 1000) }) @resinApi.post resource: 'device' body: device .timeout(conf.apiTimeout) # This uses resin API v2 for now, as the proxyvisor expects to be able to patch the device's commit patchDevice: (id, updatedFields) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot update dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to update a dependent device') @resinApiLegacy.patch resource: 'device' id: id body: updatedFields .timeout(conf.apiTimeout) pinDevice: ({ app, commit }) => @config.get('deviceId') .then (deviceId) => @resinApi.get resource: 'release' options: filter: belongs_to__application: app commit: commit status: 'success' select: 'id' .then (release) => releaseId = _.get(release, '[0].id') if !releaseId? throw new Error('Cannot continue pinning preloaded device! No release found!') @resinApi.patch resource: 'device' id: deviceId body: should_be_running__release: releaseId .then => # Set the config value for pinDevice to null, so that we know the # task has been completed @config.remove('pinDevice') .tapCatch (e) -> console.log('Could not pin device to release!') console.log('Error: ', e) # Creates the necessary config vars in the API to match the current device state, # without overwriting any variables that are already set. _reportInitialEnv: (apiEndpoint) => Promise.join( @deviceState.getCurrentForComparison() @getTargetState() @deviceState.deviceConfig.getDefaults() @config.get('deviceId') (currentState, targetState, defaultConfig, deviceId) => currentConfig = currentState.local.config targetConfig = targetState.local.config Promise.mapSeries _.toPairs(currentConfig), ([ key, value ]) => # We never want to disable VPN if, for instance, it failed to start so far if key == 'RESIN_SUPERVISOR_VPN_CONTROL' value = 'true' if !targetConfig[key]? and value != defaultConfig[key] envVar = { value device: deviceId name: key } @resinApi.post resource: 'device_config_variable' body: envVar ) .then => @config.set({ initialConfigReported: apiEndpoint }) reportInitialConfig: (apiEndpoint, retryDelay) => @_reportInitialEnv(apiEndpoint) .catch (err) => console.error('Error reporting initial configuration, will retry', err) Promise.delay(retryDelay) .then => @reportInitialConfig(apiEndpoint, retryDelay) getTargetState: => @config.getMany([ 'uuid', 'apiEndpoint', 'apiTimeout' ]) .then ({ uuid, apiEndpoint, apiTimeout }) => endpoint = url.resolve(apiEndpoint, "/device/v2/#{uuid}/state") requestParams = _.extend method: 'GET' url: "#{endpoint}" , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) .timeout(apiTimeout) # Get target state from API, set it on @deviceState and trigger a state application getAndSetTargetState: (force) => Promise.using @_lockGetTarget(), => @getTargetState() .then (targetState) => if !_.isEqual(targetState, @lastTarget) @deviceState.setTarget(targetState) .then => @lastTarget = _.cloneDeep(targetState) @deviceState.triggerApplyTarget({ force }) .tapCatch (err) -> console.error("Failed to get target state for device: #{err}") .finally => @lastTargetStateFetch = process.hrtime() _pollTargetState: => @getAndSetTargetState() .then => @targetStateFetchErrors = 0 @config.get('appUpdatePollInterval') .catch => @targetStateFetchErrors += 1 @config.get('appUpdatePollInterval') .then (appUpdatePollInterval) => Math.min(appUpdatePollInterval, 15000 * 2 ** (@targetStateFetchErrors - 1)) .then(checkInt) .then(Promise.delay) .then(@_pollTargetState) startTargetStatePoll: => Promise.try => if !@resinApi? throw new Error('Trying to start poll without initializing API client') @_pollTargetState() return null _getStateDiff: => diff = { local: _(@stateForReport.local) .omitBy((val, key) => _.isEqual(@lastReportedState.local[key], val)) .omit(INTERNAL_STATE_KEYS) .value() dependent: _(@stateForReport.dependent) .omitBy((val, key) => _.isEqual(@lastReportedState.dependent[key], val)) .omit(INTERNAL_STATE_KEYS) .value() } return _.pickBy(diff, _.negate(_.isEmpty)) _sendReportPatch: (stateDiff, conf) => endpoint = url.resolve(conf.apiEndpoint, "/device/v2/#{conf.uuid}/state") requestParams = _.extend method: 'PATCH' url: "#{endpoint}" body: stateDiff , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) _report: => @config.getMany([ 'deviceId', 'apiTimeout', 'apiEndpoint', 'uuid' ]) .then (conf) => stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 return @_sendReportPatch(stateDiff, conf) .timeout(conf.apiTimeout) .then => @stateReportErrors = 0 _.assign(@lastReportedState.local, stateDiff.local) _.assign(@lastReportedState.dependent, stateDiff.dependent) _reportCurrentState: => @reportPending = true @deviceState.getStatus() .then (currentDeviceState) => _.assign(@stateForReport.local, currentDeviceState.local) _.assign(@stateForReport.dependent, currentDeviceState.dependent) stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 @reportPending = false return @_report() .delay(REPORT_SUCCESS_DELAY) .then => @_reportCurrentState() .catch (err) => @stateReportErrors += 1 @eventTracker.track('Device state report failure', { error: err }) delay = Math.min((2 ** @stateReportErrors) * 500, MAX_REPORT_RETRY_DELAY) Promise.delay(delay) .then => @_reportCurrentState() return null startCurrentStateReport: => if !@resinApi? throw new Error('Trying to start state reporting without initializing API client') # patch to the device(id) endpoint @deviceState.on 'change', => if !@reportPending # A latency of 100 ms should be acceptable and # allows avoiding catching docker at weird states @_reportCurrentState() @_reportCurrentState()
201548
Promise = require 'bluebird' _ = require 'lodash' url = require 'url' TypedError = require 'typed-error' PinejsClient = require 'pinejs-client' deviceRegister = require 'resin-register-device' express = require 'express' bodyParser = require 'body-parser' Lock = require 'rwlock' { request, requestOpts } = require './lib/request' { checkTruthy, checkInt } = require './lib/validation' DuplicateUuidError = (err) -> _.startsWith(err.message, '"uuid" must be unique') ExchangeKeyError = class ExchangeKeyError extends TypedError REPORT_SUCCESS_DELAY = 1000 MAX_REPORT_RETRY_DELAY = 60000 INTERNAL_STATE_KEYS = [ 'update_pending', 'update_downloaded', 'update_failed', ] createAPIBinderRouter = (apiBinder) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) router.post '/v1/update', (req, res) -> apiBinder.eventTracker.track('Update notification') if apiBinder.readyForUpdates apiBinder.getAndSetTargetState(req.body.force) .catchReturn() res.sendStatus(204) return router module.exports = class APIBinder constructor: ({ @config, @db, @deviceState, @eventTracker }) -> @resinApi = null @cachedResinApi = null @lastReportedState = { local: {}, dependent: {} } @stateForReport = { local: {}, dependent: {} } @lastTarget = {} @lastTargetStateFetch = process.hrtime() @_targetStateInterval = null @reportPending = false @stateReportErrors = 0 @targetStateFetchErrors = 0 @router = createAPIBinderRouter(this) _lock = new Lock() @_writeLock = Promise.promisify(_lock.async.writeLock) @readyForUpdates = false healthcheck: => @config.getMany([ 'appUpdatePollInterval', 'offlineMode', 'connectivityCheckEnabled' ]) .then (conf) => if conf.offlineMode return true timeSinceLastFetch = process.hrtime(@lastTargetStateFetch) timeSinceLastFetchMs = timeSinceLastFetch[0] * 1000 + timeSinceLastFetch[1] / 1e6 stateFetchHealthy = timeSinceLastFetchMs < 2 * conf.appUpdatePollInterval stateReportHealthy = !conf.connectivityCheckEnabled or !@deviceState.connected or @stateReportErrors < 3 return stateFetchHealthy and stateReportHealthy _lockGetTarget: => @_writeLock('getTarget').disposer (release) -> release() initClient: => @config.getMany([ 'offlineMode', 'apiEndpoint', 'currentApiKey' ]) .then ({ offlineMode, apiEndpoint, currentApiKey }) => if offlineMode console.log('Offline Mode is set, skipping API client initialization') return baseUrl = url.resolve(apiEndpoint, '/v4/') passthrough = _.cloneDeep(requestOpts) passthrough.headers ?= {} passthrough.headers.Authorization = "Bearer #{currentApiKey}" @resinApi = new PinejsClient apiPrefix: baseUrl passthrough: passthrough baseUrlLegacy = url.resolve(apiEndpoint, '/v2/') @resinApiLegacy = new PinejsClient apiPrefix: baseUrlLegacy passthrough: passthrough @cachedResinApi = @resinApi.clone({}, cache: {}) start: => @config.getMany([ 'apiEndpoint', 'offlineMode', 'bootstrapRetryDelay' ]) .then ({ apiEndpoint, offlineMode, bootstrapRetryDelay }) => if offlineMode console.log('Offline Mode is set, skipping API binder initialization') # If we are offline because there is no apiEndpoint, there's a chance # we've went through a deprovision. We need to set the initialConfigReported # value to '', to ensure that when we do re-provision, we'll report # the config and hardward-specific options won't be lost if !Boolean(apiEndpoint) return @config.set({ initialConfigReported: '' }) return console.log('Ensuring device is provisioned') @provisionDevice() .then => @config.getMany([ 'initialConfigReported', 'apiEndpoint' ]) .then ({ initialConfigReported, apiEndpoint }) => # Either we haven't reported our initial config or we've # been re-provisioned if apiEndpoint != initialConfigReported console.log('Reporting initial configuration') @reportInitialConfig(apiEndpoint, bootstrapRetryDelay) .then => console.log('Starting current state report') @startCurrentStateReport() .then => @readyForUpdates = true console.log('Starting target state poll') @startTargetStatePoll() return null fetchDevice: (uuid, apiKey, timeout) => reqOpts = { resource: 'device' options: filter: uuid: uuid passthrough: headers: Authorization: "Bearer #{apiKey}" } @resinApi.get(reqOpts) .get(0) .catchReturn(null) .timeout(timeout) _exchangeKeyAndGetDevice: (opts) -> Promise.try => if !opts? @config.get('provisioningOptions') .then (conf) -> opts = conf .then => # If we have an existing device key we first check if it's valid, because if it is we can just use that if opts.deviceApiKey? @fetchDevice(opts.uuid, opts.deviceApiKey, opts.apiTimeout) .then (device) => if device? return device # If it's not valid/doesn't exist then we try to use the user/provisioning api key for the exchange @fetchDevice(opts.uuid, opts.provisioningApiKey, opts.apiTimeout) .tap (device) -> if not device? throw new ExchangeKeyError("Couldn't fetch device with provisioning key") # We found the device, we can try to register a working device key for it request.postAsync("#{opts.apiEndpoint}/api-key/device/#{device.id}/device-key", { json: true body: apiKey: opts.deviceApiKey headers: Authorization: "Bearer #{opts.provisioningApiKey}" }) .spread (res, body) -> if res.statusCode != 200 throw new ExchangeKeyError("Couldn't register device key with provisioning key") .timeout(opts.apiTimeout) _exchangeKeyAndGetDeviceOrRegenerate: (opts) => @_exchangeKeyAndGetDevice(opts) .tap -> console.log('Key exchange succeeded, all good') .tapCatch ExchangeKeyError, (err) => # If it fails we just have to reregister as a provisioning key doesn't have the ability to change existing devices console.log('Exchanging key failed, having to reregister') @config.regenerateRegistrationFields() _provision: => @config.get('provisioningOptions') .then (opts) => if opts.registered_at? and opts.deviceId? and !opts.provisioningApiKey? return Promise.try => if opts.registered_at? and !opts.deviceId? console.log('Device is registered but no device id available, attempting key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) else if !opts.registered_at? console.log('New device detected. Provisioning...') deviceRegister.register(opts) .timeout(opts.apiTimeout) .catch DuplicateUuidError, => console.log('UUID already registered, trying a key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) .tap -> opts.registered_at = Date.now() else if opts.provisioningApiKey? console.log('Device is registered but we still have an apiKey, attempting key exchange') @_exchangeKeyAndGetDevice(opts) .then ({ id }) => @resinApi.passthrough.headers.Authorization = "Bearer #{opts.deviceApiKey}" configToUpdate = { registered_at: opts.registered_at deviceId: id apiKey: null } @config.set(configToUpdate) .then => @eventTracker.track('Device bootstrap success') # Check if we need to pin the device, regardless of if we provisioned .then => @config.get('pinDevice') .then(JSON.parse) .tapCatch -> console.log('Warning: Malformed pinDevice value in supervisor database') .catchReturn(null) .then (pinValue) => if pinValue? if !pinValue.app? or !pinValue.commit? console.log("Malformed pinDevice fields in supervisor database: #{pinValue}") return console.log('Attempting to pin device to preloaded release...') @pinDevice(pinValue) _provisionOrRetry: (retryDelay) => @eventTracker.track('Device bootstrap') @_provision() .catch (err) => @eventTracker.track('Device bootstrap failed, retrying', { error: err, delay: retryDelay }) Promise.delay(retryDelay).then => @_provisionOrRetry(retryDelay) provisionDevice: => if !@resinApi? throw new Error('Trying to provision device without initializing API client') @config.getMany([ 'provisioned' 'bootstrapRetryDelay' 'apiKey' 'pinDevice' ]) .tap (conf) => if !conf.provisioned or conf.apiKey? or conf.pinDevice? @_provisionOrRetry(conf.bootstrapRetryDelay) provisionDependentDevice: (device) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' 'userId' 'deviceId' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot provision dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to provision a dependent device') # TODO: when API supports it as per https://github.com/resin-io/hq/pull/949 remove userId _.defaults(device, { belongs_to__user: conf.userId is_managed_by__device: conf.deviceId uuid: deviceRegister.generateUniqueKey() registered_at: Math.floor(Date.now() / 1000) }) @resinApi.post resource: 'device' body: device .timeout(conf.apiTimeout) # This uses resin API v2 for now, as the proxyvisor expects to be able to patch the device's commit patchDevice: (id, updatedFields) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot update dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to update a dependent device') @resinApiLegacy.patch resource: 'device' id: id body: updatedFields .timeout(conf.apiTimeout) pinDevice: ({ app, commit }) => @config.get('deviceId') .then (deviceId) => @resinApi.get resource: 'release' options: filter: belongs_to__application: app commit: commit status: 'success' select: 'id' .then (release) => releaseId = _.get(release, '[0].id') if !releaseId? throw new Error('Cannot continue pinning preloaded device! No release found!') @resinApi.patch resource: 'device' id: deviceId body: should_be_running__release: releaseId .then => # Set the config value for pinDevice to null, so that we know the # task has been completed @config.remove('pinDevice') .tapCatch (e) -> console.log('Could not pin device to release!') console.log('Error: ', e) # Creates the necessary config vars in the API to match the current device state, # without overwriting any variables that are already set. _reportInitialEnv: (apiEndpoint) => Promise.join( @deviceState.getCurrentForComparison() @getTargetState() @deviceState.deviceConfig.getDefaults() @config.get('deviceId') (currentState, targetState, defaultConfig, deviceId) => currentConfig = currentState.local.config targetConfig = targetState.local.config Promise.mapSeries _.toPairs(currentConfig), ([ key, value ]) => # We never want to disable VPN if, for instance, it failed to start so far if key == '<KEY>' value = 'true' if !targetConfig[key]? and value != defaultConfig[key] envVar = { value device: deviceId name: key } @resinApi.post resource: 'device_config_variable' body: envVar ) .then => @config.set({ initialConfigReported: apiEndpoint }) reportInitialConfig: (apiEndpoint, retryDelay) => @_reportInitialEnv(apiEndpoint) .catch (err) => console.error('Error reporting initial configuration, will retry', err) Promise.delay(retryDelay) .then => @reportInitialConfig(apiEndpoint, retryDelay) getTargetState: => @config.getMany([ 'uuid', 'apiEndpoint', 'apiTimeout' ]) .then ({ uuid, apiEndpoint, apiTimeout }) => endpoint = url.resolve(apiEndpoint, "/device/v2/#{uuid}/state") requestParams = _.extend method: 'GET' url: "#{endpoint}" , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) .timeout(apiTimeout) # Get target state from API, set it on @deviceState and trigger a state application getAndSetTargetState: (force) => Promise.using @_lockGetTarget(), => @getTargetState() .then (targetState) => if !_.isEqual(targetState, @lastTarget) @deviceState.setTarget(targetState) .then => @lastTarget = _.cloneDeep(targetState) @deviceState.triggerApplyTarget({ force }) .tapCatch (err) -> console.error("Failed to get target state for device: #{err}") .finally => @lastTargetStateFetch = process.hrtime() _pollTargetState: => @getAndSetTargetState() .then => @targetStateFetchErrors = 0 @config.get('appUpdatePollInterval') .catch => @targetStateFetchErrors += 1 @config.get('appUpdatePollInterval') .then (appUpdatePollInterval) => Math.min(appUpdatePollInterval, 15000 * 2 ** (@targetStateFetchErrors - 1)) .then(checkInt) .then(Promise.delay) .then(@_pollTargetState) startTargetStatePoll: => Promise.try => if !@resinApi? throw new Error('Trying to start poll without initializing API client') @_pollTargetState() return null _getStateDiff: => diff = { local: _(@stateForReport.local) .omitBy((val, key) => _.isEqual(@lastReportedState.local[key], val)) .omit(INTERNAL_STATE_KEYS) .value() dependent: _(@stateForReport.dependent) .omitBy((val, key) => _.isEqual(@lastReportedState.dependent[key], val)) .omit(INTERNAL_STATE_KEYS) .value() } return _.pickBy(diff, _.negate(_.isEmpty)) _sendReportPatch: (stateDiff, conf) => endpoint = url.resolve(conf.apiEndpoint, "/device/v2/#{conf.uuid}/state") requestParams = _.extend method: 'PATCH' url: "#{endpoint}" body: stateDiff , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) _report: => @config.getMany([ 'deviceId', 'apiTimeout', 'apiEndpoint', 'uuid' ]) .then (conf) => stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 return @_sendReportPatch(stateDiff, conf) .timeout(conf.apiTimeout) .then => @stateReportErrors = 0 _.assign(@lastReportedState.local, stateDiff.local) _.assign(@lastReportedState.dependent, stateDiff.dependent) _reportCurrentState: => @reportPending = true @deviceState.getStatus() .then (currentDeviceState) => _.assign(@stateForReport.local, currentDeviceState.local) _.assign(@stateForReport.dependent, currentDeviceState.dependent) stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 @reportPending = false return @_report() .delay(REPORT_SUCCESS_DELAY) .then => @_reportCurrentState() .catch (err) => @stateReportErrors += 1 @eventTracker.track('Device state report failure', { error: err }) delay = Math.min((2 ** @stateReportErrors) * 500, MAX_REPORT_RETRY_DELAY) Promise.delay(delay) .then => @_reportCurrentState() return null startCurrentStateReport: => if !@resinApi? throw new Error('Trying to start state reporting without initializing API client') # patch to the device(id) endpoint @deviceState.on 'change', => if !@reportPending # A latency of 100 ms should be acceptable and # allows avoiding catching docker at weird states @_reportCurrentState() @_reportCurrentState()
true
Promise = require 'bluebird' _ = require 'lodash' url = require 'url' TypedError = require 'typed-error' PinejsClient = require 'pinejs-client' deviceRegister = require 'resin-register-device' express = require 'express' bodyParser = require 'body-parser' Lock = require 'rwlock' { request, requestOpts } = require './lib/request' { checkTruthy, checkInt } = require './lib/validation' DuplicateUuidError = (err) -> _.startsWith(err.message, '"uuid" must be unique') ExchangeKeyError = class ExchangeKeyError extends TypedError REPORT_SUCCESS_DELAY = 1000 MAX_REPORT_RETRY_DELAY = 60000 INTERNAL_STATE_KEYS = [ 'update_pending', 'update_downloaded', 'update_failed', ] createAPIBinderRouter = (apiBinder) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) router.post '/v1/update', (req, res) -> apiBinder.eventTracker.track('Update notification') if apiBinder.readyForUpdates apiBinder.getAndSetTargetState(req.body.force) .catchReturn() res.sendStatus(204) return router module.exports = class APIBinder constructor: ({ @config, @db, @deviceState, @eventTracker }) -> @resinApi = null @cachedResinApi = null @lastReportedState = { local: {}, dependent: {} } @stateForReport = { local: {}, dependent: {} } @lastTarget = {} @lastTargetStateFetch = process.hrtime() @_targetStateInterval = null @reportPending = false @stateReportErrors = 0 @targetStateFetchErrors = 0 @router = createAPIBinderRouter(this) _lock = new Lock() @_writeLock = Promise.promisify(_lock.async.writeLock) @readyForUpdates = false healthcheck: => @config.getMany([ 'appUpdatePollInterval', 'offlineMode', 'connectivityCheckEnabled' ]) .then (conf) => if conf.offlineMode return true timeSinceLastFetch = process.hrtime(@lastTargetStateFetch) timeSinceLastFetchMs = timeSinceLastFetch[0] * 1000 + timeSinceLastFetch[1] / 1e6 stateFetchHealthy = timeSinceLastFetchMs < 2 * conf.appUpdatePollInterval stateReportHealthy = !conf.connectivityCheckEnabled or !@deviceState.connected or @stateReportErrors < 3 return stateFetchHealthy and stateReportHealthy _lockGetTarget: => @_writeLock('getTarget').disposer (release) -> release() initClient: => @config.getMany([ 'offlineMode', 'apiEndpoint', 'currentApiKey' ]) .then ({ offlineMode, apiEndpoint, currentApiKey }) => if offlineMode console.log('Offline Mode is set, skipping API client initialization') return baseUrl = url.resolve(apiEndpoint, '/v4/') passthrough = _.cloneDeep(requestOpts) passthrough.headers ?= {} passthrough.headers.Authorization = "Bearer #{currentApiKey}" @resinApi = new PinejsClient apiPrefix: baseUrl passthrough: passthrough baseUrlLegacy = url.resolve(apiEndpoint, '/v2/') @resinApiLegacy = new PinejsClient apiPrefix: baseUrlLegacy passthrough: passthrough @cachedResinApi = @resinApi.clone({}, cache: {}) start: => @config.getMany([ 'apiEndpoint', 'offlineMode', 'bootstrapRetryDelay' ]) .then ({ apiEndpoint, offlineMode, bootstrapRetryDelay }) => if offlineMode console.log('Offline Mode is set, skipping API binder initialization') # If we are offline because there is no apiEndpoint, there's a chance # we've went through a deprovision. We need to set the initialConfigReported # value to '', to ensure that when we do re-provision, we'll report # the config and hardward-specific options won't be lost if !Boolean(apiEndpoint) return @config.set({ initialConfigReported: '' }) return console.log('Ensuring device is provisioned') @provisionDevice() .then => @config.getMany([ 'initialConfigReported', 'apiEndpoint' ]) .then ({ initialConfigReported, apiEndpoint }) => # Either we haven't reported our initial config or we've # been re-provisioned if apiEndpoint != initialConfigReported console.log('Reporting initial configuration') @reportInitialConfig(apiEndpoint, bootstrapRetryDelay) .then => console.log('Starting current state report') @startCurrentStateReport() .then => @readyForUpdates = true console.log('Starting target state poll') @startTargetStatePoll() return null fetchDevice: (uuid, apiKey, timeout) => reqOpts = { resource: 'device' options: filter: uuid: uuid passthrough: headers: Authorization: "Bearer #{apiKey}" } @resinApi.get(reqOpts) .get(0) .catchReturn(null) .timeout(timeout) _exchangeKeyAndGetDevice: (opts) -> Promise.try => if !opts? @config.get('provisioningOptions') .then (conf) -> opts = conf .then => # If we have an existing device key we first check if it's valid, because if it is we can just use that if opts.deviceApiKey? @fetchDevice(opts.uuid, opts.deviceApiKey, opts.apiTimeout) .then (device) => if device? return device # If it's not valid/doesn't exist then we try to use the user/provisioning api key for the exchange @fetchDevice(opts.uuid, opts.provisioningApiKey, opts.apiTimeout) .tap (device) -> if not device? throw new ExchangeKeyError("Couldn't fetch device with provisioning key") # We found the device, we can try to register a working device key for it request.postAsync("#{opts.apiEndpoint}/api-key/device/#{device.id}/device-key", { json: true body: apiKey: opts.deviceApiKey headers: Authorization: "Bearer #{opts.provisioningApiKey}" }) .spread (res, body) -> if res.statusCode != 200 throw new ExchangeKeyError("Couldn't register device key with provisioning key") .timeout(opts.apiTimeout) _exchangeKeyAndGetDeviceOrRegenerate: (opts) => @_exchangeKeyAndGetDevice(opts) .tap -> console.log('Key exchange succeeded, all good') .tapCatch ExchangeKeyError, (err) => # If it fails we just have to reregister as a provisioning key doesn't have the ability to change existing devices console.log('Exchanging key failed, having to reregister') @config.regenerateRegistrationFields() _provision: => @config.get('provisioningOptions') .then (opts) => if opts.registered_at? and opts.deviceId? and !opts.provisioningApiKey? return Promise.try => if opts.registered_at? and !opts.deviceId? console.log('Device is registered but no device id available, attempting key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) else if !opts.registered_at? console.log('New device detected. Provisioning...') deviceRegister.register(opts) .timeout(opts.apiTimeout) .catch DuplicateUuidError, => console.log('UUID already registered, trying a key exchange') @_exchangeKeyAndGetDeviceOrRegenerate(opts) .tap -> opts.registered_at = Date.now() else if opts.provisioningApiKey? console.log('Device is registered but we still have an apiKey, attempting key exchange') @_exchangeKeyAndGetDevice(opts) .then ({ id }) => @resinApi.passthrough.headers.Authorization = "Bearer #{opts.deviceApiKey}" configToUpdate = { registered_at: opts.registered_at deviceId: id apiKey: null } @config.set(configToUpdate) .then => @eventTracker.track('Device bootstrap success') # Check if we need to pin the device, regardless of if we provisioned .then => @config.get('pinDevice') .then(JSON.parse) .tapCatch -> console.log('Warning: Malformed pinDevice value in supervisor database') .catchReturn(null) .then (pinValue) => if pinValue? if !pinValue.app? or !pinValue.commit? console.log("Malformed pinDevice fields in supervisor database: #{pinValue}") return console.log('Attempting to pin device to preloaded release...') @pinDevice(pinValue) _provisionOrRetry: (retryDelay) => @eventTracker.track('Device bootstrap') @_provision() .catch (err) => @eventTracker.track('Device bootstrap failed, retrying', { error: err, delay: retryDelay }) Promise.delay(retryDelay).then => @_provisionOrRetry(retryDelay) provisionDevice: => if !@resinApi? throw new Error('Trying to provision device without initializing API client') @config.getMany([ 'provisioned' 'bootstrapRetryDelay' 'apiKey' 'pinDevice' ]) .tap (conf) => if !conf.provisioned or conf.apiKey? or conf.pinDevice? @_provisionOrRetry(conf.bootstrapRetryDelay) provisionDependentDevice: (device) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' 'userId' 'deviceId' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot provision dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to provision a dependent device') # TODO: when API supports it as per https://github.com/resin-io/hq/pull/949 remove userId _.defaults(device, { belongs_to__user: conf.userId is_managed_by__device: conf.deviceId uuid: deviceRegister.generateUniqueKey() registered_at: Math.floor(Date.now() / 1000) }) @resinApi.post resource: 'device' body: device .timeout(conf.apiTimeout) # This uses resin API v2 for now, as the proxyvisor expects to be able to patch the device's commit patchDevice: (id, updatedFields) => @config.getMany([ 'offlineMode' 'provisioned' 'apiTimeout' ]) .then (conf) => if conf.offlineMode throw new Error('Cannot update dependent device in offline mode') if !conf.provisioned throw new Error('Device must be provisioned to update a dependent device') @resinApiLegacy.patch resource: 'device' id: id body: updatedFields .timeout(conf.apiTimeout) pinDevice: ({ app, commit }) => @config.get('deviceId') .then (deviceId) => @resinApi.get resource: 'release' options: filter: belongs_to__application: app commit: commit status: 'success' select: 'id' .then (release) => releaseId = _.get(release, '[0].id') if !releaseId? throw new Error('Cannot continue pinning preloaded device! No release found!') @resinApi.patch resource: 'device' id: deviceId body: should_be_running__release: releaseId .then => # Set the config value for pinDevice to null, so that we know the # task has been completed @config.remove('pinDevice') .tapCatch (e) -> console.log('Could not pin device to release!') console.log('Error: ', e) # Creates the necessary config vars in the API to match the current device state, # without overwriting any variables that are already set. _reportInitialEnv: (apiEndpoint) => Promise.join( @deviceState.getCurrentForComparison() @getTargetState() @deviceState.deviceConfig.getDefaults() @config.get('deviceId') (currentState, targetState, defaultConfig, deviceId) => currentConfig = currentState.local.config targetConfig = targetState.local.config Promise.mapSeries _.toPairs(currentConfig), ([ key, value ]) => # We never want to disable VPN if, for instance, it failed to start so far if key == 'PI:KEY:<KEY>END_PI' value = 'true' if !targetConfig[key]? and value != defaultConfig[key] envVar = { value device: deviceId name: key } @resinApi.post resource: 'device_config_variable' body: envVar ) .then => @config.set({ initialConfigReported: apiEndpoint }) reportInitialConfig: (apiEndpoint, retryDelay) => @_reportInitialEnv(apiEndpoint) .catch (err) => console.error('Error reporting initial configuration, will retry', err) Promise.delay(retryDelay) .then => @reportInitialConfig(apiEndpoint, retryDelay) getTargetState: => @config.getMany([ 'uuid', 'apiEndpoint', 'apiTimeout' ]) .then ({ uuid, apiEndpoint, apiTimeout }) => endpoint = url.resolve(apiEndpoint, "/device/v2/#{uuid}/state") requestParams = _.extend method: 'GET' url: "#{endpoint}" , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) .timeout(apiTimeout) # Get target state from API, set it on @deviceState and trigger a state application getAndSetTargetState: (force) => Promise.using @_lockGetTarget(), => @getTargetState() .then (targetState) => if !_.isEqual(targetState, @lastTarget) @deviceState.setTarget(targetState) .then => @lastTarget = _.cloneDeep(targetState) @deviceState.triggerApplyTarget({ force }) .tapCatch (err) -> console.error("Failed to get target state for device: #{err}") .finally => @lastTargetStateFetch = process.hrtime() _pollTargetState: => @getAndSetTargetState() .then => @targetStateFetchErrors = 0 @config.get('appUpdatePollInterval') .catch => @targetStateFetchErrors += 1 @config.get('appUpdatePollInterval') .then (appUpdatePollInterval) => Math.min(appUpdatePollInterval, 15000 * 2 ** (@targetStateFetchErrors - 1)) .then(checkInt) .then(Promise.delay) .then(@_pollTargetState) startTargetStatePoll: => Promise.try => if !@resinApi? throw new Error('Trying to start poll without initializing API client') @_pollTargetState() return null _getStateDiff: => diff = { local: _(@stateForReport.local) .omitBy((val, key) => _.isEqual(@lastReportedState.local[key], val)) .omit(INTERNAL_STATE_KEYS) .value() dependent: _(@stateForReport.dependent) .omitBy((val, key) => _.isEqual(@lastReportedState.dependent[key], val)) .omit(INTERNAL_STATE_KEYS) .value() } return _.pickBy(diff, _.negate(_.isEmpty)) _sendReportPatch: (stateDiff, conf) => endpoint = url.resolve(conf.apiEndpoint, "/device/v2/#{conf.uuid}/state") requestParams = _.extend method: 'PATCH' url: "#{endpoint}" body: stateDiff , @cachedResinApi.passthrough @cachedResinApi._request(requestParams) _report: => @config.getMany([ 'deviceId', 'apiTimeout', 'apiEndpoint', 'uuid' ]) .then (conf) => stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 return @_sendReportPatch(stateDiff, conf) .timeout(conf.apiTimeout) .then => @stateReportErrors = 0 _.assign(@lastReportedState.local, stateDiff.local) _.assign(@lastReportedState.dependent, stateDiff.dependent) _reportCurrentState: => @reportPending = true @deviceState.getStatus() .then (currentDeviceState) => _.assign(@stateForReport.local, currentDeviceState.local) _.assign(@stateForReport.dependent, currentDeviceState.dependent) stateDiff = @_getStateDiff() if _.size(stateDiff) is 0 @reportPending = false return @_report() .delay(REPORT_SUCCESS_DELAY) .then => @_reportCurrentState() .catch (err) => @stateReportErrors += 1 @eventTracker.track('Device state report failure', { error: err }) delay = Math.min((2 ** @stateReportErrors) * 500, MAX_REPORT_RETRY_DELAY) Promise.delay(delay) .then => @_reportCurrentState() return null startCurrentStateReport: => if !@resinApi? throw new Error('Trying to start state reporting without initializing API client') # patch to the device(id) endpoint @deviceState.on 'change', => if !@reportPending # A latency of 100 ms should be acceptable and # allows avoiding catching docker at weird states @_reportCurrentState() @_reportCurrentState()
[ { "context": "###*\n# @fileoverview No mixed linebreaks\n# @author Erik Mueller\n###\n'use strict'\n\n#------------------------------", "end": 63, "score": 0.9998123049736023, "start": 51, "tag": "NAME", "value": "Erik Mueller" } ]
src/tests/rules/linebreak-style.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview No mixed linebreaks # @author Erik Mueller ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/linebreak-style' {RuleTester} = require 'eslint' path = require 'path' EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'." EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'." #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'linebreak-style', rule, valid: [ "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" options: ['unix'] , code: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n ### do stuff ### \r\n \r\n" options: ['windows'] , code: "b = 'b'" options: ['unix'] , code: "b = 'b'" options: ['windows'] ] invalid: [ code: "a = 'a'\r\n" output: "a = 'a'\n" errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\n" output: "a = 'a'\n" options: ['unix'] errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\n" output: "a = 'a'\r\n" options: ['windows'] errors: [ line: 1 column: 8 message: EXPECTED_CRLF_MSG ] , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\r\n ### do stuff ### \n \r\n" output: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" errors: [ line: 4 column: 18 message: EXPECTED_LF_MSG , line: 6 column: 3 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\nb = 'b'\r\n\nfoo = (params) ->\r\n \n ### do stuff ### \n \r\n" output: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n \r\n ### do stuff ### \r\n \r\n" options: ['windows'] errors: [ line: 3 column: 1 message: EXPECTED_CRLF_MSG , line: 5 column: 3 message: EXPECTED_CRLF_MSG , line: 6 column: 20 message: EXPECTED_CRLF_MSG ] ]
209781
###* # @fileoverview No mixed linebreaks # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/linebreak-style' {RuleTester} = require 'eslint' path = require 'path' EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'." EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'." #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'linebreak-style', rule, valid: [ "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" options: ['unix'] , code: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n ### do stuff ### \r\n \r\n" options: ['windows'] , code: "b = 'b'" options: ['unix'] , code: "b = 'b'" options: ['windows'] ] invalid: [ code: "a = 'a'\r\n" output: "a = 'a'\n" errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\n" output: "a = 'a'\n" options: ['unix'] errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\n" output: "a = 'a'\r\n" options: ['windows'] errors: [ line: 1 column: 8 message: EXPECTED_CRLF_MSG ] , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\r\n ### do stuff ### \n \r\n" output: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" errors: [ line: 4 column: 18 message: EXPECTED_LF_MSG , line: 6 column: 3 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\nb = 'b'\r\n\nfoo = (params) ->\r\n \n ### do stuff ### \n \r\n" output: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n \r\n ### do stuff ### \r\n \r\n" options: ['windows'] errors: [ line: 3 column: 1 message: EXPECTED_CRLF_MSG , line: 5 column: 3 message: EXPECTED_CRLF_MSG , line: 6 column: 20 message: EXPECTED_CRLF_MSG ] ]
true
###* # @fileoverview No mixed linebreaks # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/linebreak-style' {RuleTester} = require 'eslint' path = require 'path' EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'." EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'." #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'linebreak-style', rule, valid: [ "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" options: ['unix'] , code: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n ### do stuff ### \r\n \r\n" options: ['windows'] , code: "b = 'b'" options: ['unix'] , code: "b = 'b'" options: ['windows'] ] invalid: [ code: "a = 'a'\r\n" output: "a = 'a'\n" errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\n" output: "a = 'a'\n" options: ['unix'] errors: [ line: 1 column: 8 message: EXPECTED_LF_MSG ] , code: "a = 'a'\n" output: "a = 'a'\r\n" options: ['windows'] errors: [ line: 1 column: 8 message: EXPECTED_CRLF_MSG ] , code: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\r\n ### do stuff ### \n \r\n" output: "a = 'a'\nb = 'b'\n\nfoo = (params) ->\n ### do stuff ### \n \n" errors: [ line: 4 column: 18 message: EXPECTED_LF_MSG , line: 6 column: 3 message: EXPECTED_LF_MSG ] , code: "a = 'a'\r\nb = 'b'\r\n\nfoo = (params) ->\r\n \n ### do stuff ### \n \r\n" output: "a = 'a'\r\nb = 'b'\r\n\r\nfoo = (params) ->\r\n \r\n ### do stuff ### \r\n \r\n" options: ['windows'] errors: [ line: 3 column: 1 message: EXPECTED_CRLF_MSG , line: 5 column: 3 message: EXPECTED_CRLF_MSG , line: 6 column: 20 message: EXPECTED_CRLF_MSG ] ]
[ { "context": "etConnect()\ndomain = \"slack-node\"\nwebhookToken = \"ROHgstANbsFAUA5dHHI5JONu\"\napiToken = \"xoxp-2307918714-2307918716-230791081", "end": 182, "score": 0.9987815022468567, "start": 158, "tag": "KEY", "value": "ROHgstANbsFAUA5dHHI5JONu" }, { "context": "ookToken = \"...
src/test/main.spec.test.coffee
edwardbc/slack-node-sdk
0
should = require "should" nock = require "nock" url = require "url" Slack = require "../index" nock.enableNetConnect() domain = "slack-node" webhookToken = "ROHgstANbsFAUA5dHHI5JONu" apiToken = "xoxp-2307918714-2307918716-2307910813-17cabf" webhookUri = "https://hooks.slack.com/services/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" describe 'slack new webhook test', -> this.timeout(50000) slack = new Slack() slack.setWebhook(webhookUri) it 'should create a slack object', (done) -> slack.should.be.an.Object done() it 'should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should send a correct response with emoji', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> if err then return done(err) response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> this.timeout 50000 slack = new Slack apiToken it 'should return a slack object', (done) -> slack.should.be.an.Object done() it "run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() it "run with Attachments", (done) -> payload = channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" attachments: '[{"pretext": "pre-hello", "text": "text-world"}]' slack.api 'chat.postMessage', payload, (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() # slack.api "users.list", (err, response) -> # response.should.be.ok.and.an.Object # done() describe "emoji test", -> slack = new Slack webhookToken, domain it 'emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it 'emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it 'emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Object obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done() describe "lack something", -> slack = new Slack webhookToken, domain it 'without callback', (done) -> method = "files.list" feedback = slack.api method feedback.should.be.an.Object feedback.should.equal(slack) feedback.should.not.be.null done() describe 'parse test', -> slack = new Slack webhookToken, domain # Something that returns XML slack.url = 'https://httpbin.org/xml' it 'does not crash if XML is returned', (done) -> slack.api "users.list", (err, response) -> err.message.should.containEql "Couldn't parse Slack API response" done() describe "retry test", -> this.timeout(50000) slack = null beforeEach -> slack = new Slack() slack.setWebhook(webhookUri) slack.timeout = 10 it "Should retry if a request to slack fails after a timeout", (done) -> webhookDetails = url.parse(webhookUri) mockWebhook = nock(webhookDetails.protocol + "//" + webhookDetails.host).post(webhookDetails.path).times(3).socketDelay(20).reply(204, '') slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> should.exist(err) should.not.exist(response) should.equal(mockWebhook.isDone(), true) done()
186706
should = require "should" nock = require "nock" url = require "url" Slack = require "../index" nock.enableNetConnect() domain = "slack-node" webhookToken = "<KEY>" apiToken = "<KEY>" webhookUri = "<KEY>" describe 'slack new webhook test', -> this.timeout(50000) slack = new Slack() slack.setWebhook(webhookUri) it 'should create a slack object', (done) -> slack.should.be.an.Object done() it 'should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should send a correct response with emoji', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> if err then return done(err) response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> this.timeout 50000 slack = new Slack apiToken it 'should return a slack object', (done) -> slack.should.be.an.Object done() it "run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() it "run with Attachments", (done) -> payload = channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" attachments: '[{"pretext": "pre-hello", "text": "text-world"}]' slack.api 'chat.postMessage', payload, (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() # slack.api "users.list", (err, response) -> # response.should.be.ok.and.an.Object # done() describe "emoji test", -> slack = new Slack webhookToken, domain it 'emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it 'emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it 'emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Object obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done() describe "lack something", -> slack = new Slack webhookToken, domain it 'without callback', (done) -> method = "files.list" feedback = slack.api method feedback.should.be.an.Object feedback.should.equal(slack) feedback.should.not.be.null done() describe 'parse test', -> slack = new Slack webhookToken, domain # Something that returns XML slack.url = 'https://httpbin.org/xml' it 'does not crash if XML is returned', (done) -> slack.api "users.list", (err, response) -> err.message.should.containEql "Couldn't parse Slack API response" done() describe "retry test", -> this.timeout(50000) slack = null beforeEach -> slack = new Slack() slack.setWebhook(webhookUri) slack.timeout = 10 it "Should retry if a request to slack fails after a timeout", (done) -> webhookDetails = url.parse(webhookUri) mockWebhook = nock(webhookDetails.protocol + "//" + webhookDetails.host).post(webhookDetails.path).times(3).socketDelay(20).reply(204, '') slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> should.exist(err) should.not.exist(response) should.equal(mockWebhook.isDone(), true) done()
true
should = require "should" nock = require "nock" url = require "url" Slack = require "../index" nock.enableNetConnect() domain = "slack-node" webhookToken = "PI:KEY:<KEY>END_PI" apiToken = "PI:KEY:<KEY>END_PI" webhookUri = "PI:KEY:<KEY>END_PI" describe 'slack new webhook test', -> this.timeout(50000) slack = new Slack() slack.setWebhook(webhookUri) it 'should create a slack object', (done) -> slack.should.be.an.Object done() it 'should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should send a correct response with emoji', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" , (err, response) -> if err then return done(err) response.should.be.ok.and.an.Object done() it 'should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> if err then return done(err) response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> this.timeout 50000 slack = new Slack apiToken it 'should return a slack object', (done) -> slack.should.be.an.Object done() it "run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() it "run with Attachments", (done) -> payload = channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." icon_emoji: ":ghost:" attachments: '[{"pretext": "pre-hello", "text": "text-world"}]' slack.api 'chat.postMessage', payload, (err, response) -> response.should.be.ok.and.an.Object response.should.have.property('ok').equal(true) response.should.not.have.property('error') done() # slack.api "users.list", (err, response) -> # response.should.be.ok.and.an.Object # done() describe "emoji test", -> slack = new Slack webhookToken, domain it 'emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it 'emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Object obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it 'emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Object obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done() describe "lack something", -> slack = new Slack webhookToken, domain it 'without callback', (done) -> method = "files.list" feedback = slack.api method feedback.should.be.an.Object feedback.should.equal(slack) feedback.should.not.be.null done() describe 'parse test', -> slack = new Slack webhookToken, domain # Something that returns XML slack.url = 'https://httpbin.org/xml' it 'does not crash if XML is returned', (done) -> slack.api "users.list", (err, response) -> err.message.should.containEql "Couldn't parse Slack API response" done() describe "retry test", -> this.timeout(50000) slack = null beforeEach -> slack = new Slack() slack.setWebhook(webhookUri) slack.timeout = 10 it "Should retry if a request to slack fails after a timeout", (done) -> webhookDetails = url.parse(webhookUri) mockWebhook = nock(webhookDetails.protocol + "//" + webhookDetails.host).post(webhookDetails.path).times(3).socketDelay(20).reply(204, '') slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> should.exist(err) should.not.exist(response) should.equal(mockWebhook.isDone(), true) done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992320537567139, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-child-process-double-pipe.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. is_windows = process.platform is "win32" common = require("../common") assert = require("assert") os = require("os") util = require("util") spawn = require("child_process").spawn # We're trying to reproduce: # $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ grep = undefined sed = undefined echo = undefined if is_windows grep = spawn("grep", [ "--binary" "o" ]) sed = spawn("sed", [ "--binary" "s/o/O/" ]) echo = spawn("cmd.exe", [ "/c" "echo" "hello&&" "echo" "node&&" "echo" "and&&" "echo" "world" ]) else grep = spawn("grep", ["o"]) sed = spawn("sed", ["s/o/O/"]) echo = spawn("echo", ["hello\nnode\nand\nworld\n"]) # # * grep and sed hang if the spawn function leaks file descriptors to child # * processes. # * This happens when calling pipe(2) and then forgetting to set the # * FD_CLOEXEC flag on the resulting file descriptors. # * # * This test checks child processes exit, meaning they don't hang like # * explained above. # # pipe echo | grep echo.stdout.on "data", (data) -> console.error "grep stdin write " + data.length echo.stdout.pause() unless grep.stdin.write(data) return grep.stdin.on "drain", (data) -> echo.stdout.resume() return # propagate end from echo to grep echo.stdout.on "end", (code) -> grep.stdin.end() return echo.on "exit", -> console.error "echo exit" return grep.on "exit", -> console.error "grep exit" return sed.on "exit", -> console.error "sed exit" return # pipe grep | sed grep.stdout.on "data", (data) -> console.error "grep stdout " + data.length grep.stdout.pause() unless sed.stdin.write(data) return sed.stdin.on "drain", (data) -> grep.stdout.resume() return # propagate end from grep to sed grep.stdout.on "end", (code) -> console.error "grep stdout end" sed.stdin.end() return result = "" # print sed's output sed.stdout.on "data", (data) -> result += data.toString("utf8", 0, data.length) util.print data return sed.stdout.on "end", (code) -> assert.equal result, "hellO" + os.EOL + "nOde" + os.EOL + "wOrld" + os.EOL return
176437
# 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. is_windows = process.platform is "win32" common = require("../common") assert = require("assert") os = require("os") util = require("util") spawn = require("child_process").spawn # We're trying to reproduce: # $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ grep = undefined sed = undefined echo = undefined if is_windows grep = spawn("grep", [ "--binary" "o" ]) sed = spawn("sed", [ "--binary" "s/o/O/" ]) echo = spawn("cmd.exe", [ "/c" "echo" "hello&&" "echo" "node&&" "echo" "and&&" "echo" "world" ]) else grep = spawn("grep", ["o"]) sed = spawn("sed", ["s/o/O/"]) echo = spawn("echo", ["hello\nnode\nand\nworld\n"]) # # * grep and sed hang if the spawn function leaks file descriptors to child # * processes. # * This happens when calling pipe(2) and then forgetting to set the # * FD_CLOEXEC flag on the resulting file descriptors. # * # * This test checks child processes exit, meaning they don't hang like # * explained above. # # pipe echo | grep echo.stdout.on "data", (data) -> console.error "grep stdin write " + data.length echo.stdout.pause() unless grep.stdin.write(data) return grep.stdin.on "drain", (data) -> echo.stdout.resume() return # propagate end from echo to grep echo.stdout.on "end", (code) -> grep.stdin.end() return echo.on "exit", -> console.error "echo exit" return grep.on "exit", -> console.error "grep exit" return sed.on "exit", -> console.error "sed exit" return # pipe grep | sed grep.stdout.on "data", (data) -> console.error "grep stdout " + data.length grep.stdout.pause() unless sed.stdin.write(data) return sed.stdin.on "drain", (data) -> grep.stdout.resume() return # propagate end from grep to sed grep.stdout.on "end", (code) -> console.error "grep stdout end" sed.stdin.end() return result = "" # print sed's output sed.stdout.on "data", (data) -> result += data.toString("utf8", 0, data.length) util.print data return sed.stdout.on "end", (code) -> assert.equal result, "hellO" + os.EOL + "nOde" + os.EOL + "wOrld" + os.EOL 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. is_windows = process.platform is "win32" common = require("../common") assert = require("assert") os = require("os") util = require("util") spawn = require("child_process").spawn # We're trying to reproduce: # $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ grep = undefined sed = undefined echo = undefined if is_windows grep = spawn("grep", [ "--binary" "o" ]) sed = spawn("sed", [ "--binary" "s/o/O/" ]) echo = spawn("cmd.exe", [ "/c" "echo" "hello&&" "echo" "node&&" "echo" "and&&" "echo" "world" ]) else grep = spawn("grep", ["o"]) sed = spawn("sed", ["s/o/O/"]) echo = spawn("echo", ["hello\nnode\nand\nworld\n"]) # # * grep and sed hang if the spawn function leaks file descriptors to child # * processes. # * This happens when calling pipe(2) and then forgetting to set the # * FD_CLOEXEC flag on the resulting file descriptors. # * # * This test checks child processes exit, meaning they don't hang like # * explained above. # # pipe echo | grep echo.stdout.on "data", (data) -> console.error "grep stdin write " + data.length echo.stdout.pause() unless grep.stdin.write(data) return grep.stdin.on "drain", (data) -> echo.stdout.resume() return # propagate end from echo to grep echo.stdout.on "end", (code) -> grep.stdin.end() return echo.on "exit", -> console.error "echo exit" return grep.on "exit", -> console.error "grep exit" return sed.on "exit", -> console.error "sed exit" return # pipe grep | sed grep.stdout.on "data", (data) -> console.error "grep stdout " + data.length grep.stdout.pause() unless sed.stdin.write(data) return sed.stdin.on "drain", (data) -> grep.stdout.resume() return # propagate end from grep to sed grep.stdout.on "end", (code) -> console.error "grep stdout end" sed.stdin.end() return result = "" # print sed's output sed.stdout.on "data", (data) -> result += data.toString("utf8", 0, data.length) util.print data return sed.stdout.on "end", (code) -> assert.equal result, "hellO" + os.EOL + "nOde" + os.EOL + "wOrld" + os.EOL return
[ { "context": "et'\n dataType: 'json'\n data:\n password: password\n email: email\n success: (data) -> set_fee", "end": 398, "score": 0.9989483952522278, "start": 390, "tag": "PASSWORD", "value": "password" } ]
lib/assets/javascripts/password_feedback.js.coffee
bluerail/password_feedback
1
#= require zxcvbn 'use strict' req = null show_feedback = (input, email, password, bar) -> req.abort() if req? if password is '' bar.html '' return show_feedback_client input, email, password, bar show_feedback_server = ((input, email, password, bar) -> req = jQuery.ajax url: '/users/password_score' type: 'get' dataType: 'json' data: password: password email: email success: (data) -> set_feedback bar, data.n, data.strength ).debounce 200 show_feedback_client = (input, email, password, bar) -> result = zxcvbn password, [email].concat(email.split(/[^\w]/)) if result.score is 0 set_feedback bar, 1, 'weak' else if result.score is 4 set_feedback bar, 3, 'strong' else set_feedback bar, 2, 'ok' set_feedback = (bar, n, strength) -> bar.find("span:lt(#{n})").attr 'class', "password-feedback-indicator password-feedback-#{strength}" bar.find("span:gt(#{n})").attr 'class', 'password-feedback-indicator' compare = (input, other) -> if input.val() is other.val() input.closest('.form-group').removeClass 'error has-error' input.parent().find('.help-block').remove() return input.closest('.form-group').addClass 'error has-error' help = input.parent().find '.help-block' if help.length help.html _('not the same as password') else input.after "<span class='help-block'>#{_('not the same as password')}</span>" $(document).on 'input', '.input.password_strength input', -> input = $(this) show_feedback( input, input.closest('form').find('input[type=email]')?.val()?.trim(), input.val(), input.closest('.password_strength').find('.password-feedback-bar')) input.closest('form').find('.input.password_confirmation input').trigger 'input' $(document).on 'input', '.input.password_confirmation input', -> compare $(this), $($(this).closest('form').find('input[type=password]').not(this) .toArray().filter((f) -> f.name.indexOf('[password]') >= 0)) $(document).on 'ready page:load', -> $('.password-feedback-help').popover placement: 'bottom' container: 'body' html: true content: _('password_help_popover')
150605
#= require zxcvbn 'use strict' req = null show_feedback = (input, email, password, bar) -> req.abort() if req? if password is '' bar.html '' return show_feedback_client input, email, password, bar show_feedback_server = ((input, email, password, bar) -> req = jQuery.ajax url: '/users/password_score' type: 'get' dataType: 'json' data: password: <PASSWORD> email: email success: (data) -> set_feedback bar, data.n, data.strength ).debounce 200 show_feedback_client = (input, email, password, bar) -> result = zxcvbn password, [email].concat(email.split(/[^\w]/)) if result.score is 0 set_feedback bar, 1, 'weak' else if result.score is 4 set_feedback bar, 3, 'strong' else set_feedback bar, 2, 'ok' set_feedback = (bar, n, strength) -> bar.find("span:lt(#{n})").attr 'class', "password-feedback-indicator password-feedback-#{strength}" bar.find("span:gt(#{n})").attr 'class', 'password-feedback-indicator' compare = (input, other) -> if input.val() is other.val() input.closest('.form-group').removeClass 'error has-error' input.parent().find('.help-block').remove() return input.closest('.form-group').addClass 'error has-error' help = input.parent().find '.help-block' if help.length help.html _('not the same as password') else input.after "<span class='help-block'>#{_('not the same as password')}</span>" $(document).on 'input', '.input.password_strength input', -> input = $(this) show_feedback( input, input.closest('form').find('input[type=email]')?.val()?.trim(), input.val(), input.closest('.password_strength').find('.password-feedback-bar')) input.closest('form').find('.input.password_confirmation input').trigger 'input' $(document).on 'input', '.input.password_confirmation input', -> compare $(this), $($(this).closest('form').find('input[type=password]').not(this) .toArray().filter((f) -> f.name.indexOf('[password]') >= 0)) $(document).on 'ready page:load', -> $('.password-feedback-help').popover placement: 'bottom' container: 'body' html: true content: _('password_help_popover')
true
#= require zxcvbn 'use strict' req = null show_feedback = (input, email, password, bar) -> req.abort() if req? if password is '' bar.html '' return show_feedback_client input, email, password, bar show_feedback_server = ((input, email, password, bar) -> req = jQuery.ajax url: '/users/password_score' type: 'get' dataType: 'json' data: password: PI:PASSWORD:<PASSWORD>END_PI email: email success: (data) -> set_feedback bar, data.n, data.strength ).debounce 200 show_feedback_client = (input, email, password, bar) -> result = zxcvbn password, [email].concat(email.split(/[^\w]/)) if result.score is 0 set_feedback bar, 1, 'weak' else if result.score is 4 set_feedback bar, 3, 'strong' else set_feedback bar, 2, 'ok' set_feedback = (bar, n, strength) -> bar.find("span:lt(#{n})").attr 'class', "password-feedback-indicator password-feedback-#{strength}" bar.find("span:gt(#{n})").attr 'class', 'password-feedback-indicator' compare = (input, other) -> if input.val() is other.val() input.closest('.form-group').removeClass 'error has-error' input.parent().find('.help-block').remove() return input.closest('.form-group').addClass 'error has-error' help = input.parent().find '.help-block' if help.length help.html _('not the same as password') else input.after "<span class='help-block'>#{_('not the same as password')}</span>" $(document).on 'input', '.input.password_strength input', -> input = $(this) show_feedback( input, input.closest('form').find('input[type=email]')?.val()?.trim(), input.val(), input.closest('.password_strength').find('.password-feedback-bar')) input.closest('form').find('.input.password_confirmation input').trigger 'input' $(document).on 'input', '.input.password_confirmation input', -> compare $(this), $($(this).closest('form').find('input[type=password]').not(this) .toArray().filter((f) -> f.name.indexOf('[password]') >= 0)) $(document).on 'ready page:load', -> $('.password-feedback-help').popover placement: 'bottom' container: 'body' html: true content: _('password_help_popover')
[ { "context": "emo = { endpoint: 'https://api.github.com', key: 'github', name: 'GitHub', description: 'fancy desc' }\n ", "end": 249, "score": 0.9910535216331482, "start": 243, "tag": "KEY", "value": "github" } ]
test/unit/controllers/demo_spec.coffee
rrampage/monitor
114
describe 'DemoService', -> beforeEach module('slug.services.demo') it 'creates new service', inject (DemoService, Service) -> spyOn(Service, 'save').and.callFake (service) -> myDemo = { endpoint: 'https://api.github.com', key: 'github', name: 'GitHub', description: 'fancy desc' } DemoService.create(myDemo) expect(Service.save).toHaveBeenCalled() expect(service.endpoints).toEqual([{code: 'github', url: 'https://api.github.com'}]) expect(service.name).toEqual('GitHub API') expect(service.description).toEqual('fancy desc') expect(service.demo).toEqual('github') describe 'DemoCall', -> beforeEach module('slug.services.demo') [$httpBackend] = [] beforeEach inject (_$httpBackend_) -> $httpBackend = _$httpBackend_ afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'calls http api', inject (DemoCall) -> example = { method: 'GET', url: 'example'} service = { _id: 3 } $httpBackend.expect('GET', '/api/services/3/call?method=GET&url=example').respond('') DemoCall.perform(service, example) $httpBackend.flush() describe 'DemoCallCtrl', -> beforeEach module('slug.services.demo') [scope, ctrl] = [] beforeEach inject ($rootScope, $controller) -> scope = $rootScope.$new() ctrl = $controller 'DemoCallCtrl', $scope: scope it 'performs http call', inject (DemoCall) -> expect(scope.perform).toBeDefined() scope.call = 'sample' scope.service = {_id: 3} spyOn(DemoCall, 'perform').and.callThrough() scope.perform() expect(DemoCall.perform).toHaveBeenCalledWith(scope.service, scope.call)
125047
describe 'DemoService', -> beforeEach module('slug.services.demo') it 'creates new service', inject (DemoService, Service) -> spyOn(Service, 'save').and.callFake (service) -> myDemo = { endpoint: 'https://api.github.com', key: '<KEY>', name: 'GitHub', description: 'fancy desc' } DemoService.create(myDemo) expect(Service.save).toHaveBeenCalled() expect(service.endpoints).toEqual([{code: 'github', url: 'https://api.github.com'}]) expect(service.name).toEqual('GitHub API') expect(service.description).toEqual('fancy desc') expect(service.demo).toEqual('github') describe 'DemoCall', -> beforeEach module('slug.services.demo') [$httpBackend] = [] beforeEach inject (_$httpBackend_) -> $httpBackend = _$httpBackend_ afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'calls http api', inject (DemoCall) -> example = { method: 'GET', url: 'example'} service = { _id: 3 } $httpBackend.expect('GET', '/api/services/3/call?method=GET&url=example').respond('') DemoCall.perform(service, example) $httpBackend.flush() describe 'DemoCallCtrl', -> beforeEach module('slug.services.demo') [scope, ctrl] = [] beforeEach inject ($rootScope, $controller) -> scope = $rootScope.$new() ctrl = $controller 'DemoCallCtrl', $scope: scope it 'performs http call', inject (DemoCall) -> expect(scope.perform).toBeDefined() scope.call = 'sample' scope.service = {_id: 3} spyOn(DemoCall, 'perform').and.callThrough() scope.perform() expect(DemoCall.perform).toHaveBeenCalledWith(scope.service, scope.call)
true
describe 'DemoService', -> beforeEach module('slug.services.demo') it 'creates new service', inject (DemoService, Service) -> spyOn(Service, 'save').and.callFake (service) -> myDemo = { endpoint: 'https://api.github.com', key: 'PI:KEY:<KEY>END_PI', name: 'GitHub', description: 'fancy desc' } DemoService.create(myDemo) expect(Service.save).toHaveBeenCalled() expect(service.endpoints).toEqual([{code: 'github', url: 'https://api.github.com'}]) expect(service.name).toEqual('GitHub API') expect(service.description).toEqual('fancy desc') expect(service.demo).toEqual('github') describe 'DemoCall', -> beforeEach module('slug.services.demo') [$httpBackend] = [] beforeEach inject (_$httpBackend_) -> $httpBackend = _$httpBackend_ afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'calls http api', inject (DemoCall) -> example = { method: 'GET', url: 'example'} service = { _id: 3 } $httpBackend.expect('GET', '/api/services/3/call?method=GET&url=example').respond('') DemoCall.perform(service, example) $httpBackend.flush() describe 'DemoCallCtrl', -> beforeEach module('slug.services.demo') [scope, ctrl] = [] beforeEach inject ($rootScope, $controller) -> scope = $rootScope.$new() ctrl = $controller 'DemoCallCtrl', $scope: scope it 'performs http call', inject (DemoCall) -> expect(scope.perform).toBeDefined() scope.call = 'sample' scope.service = {_id: 3} spyOn(DemoCall, 'perform').and.callThrough() scope.perform() expect(DemoCall.perform).toHaveBeenCalledWith(scope.service, scope.call)
[ { "context": "g: \"Prevailing Pung/Kong\",score: 1},\n \"Chanta\": {jpn: \"Chanta\",eng: \"Outs", "end": 1503, "score": 0.8775755167007446, "start": 1497, "tag": "NAME", "value": "Chanta" }, { "context": " \"Chanta\": {...
akagiScoring.coffee
Kuba663/Akagi-Bot
1
_ = require('lodash') gamePieces = require('./akagiTiles.coffee') yakuList = { "Riichi": {jpn: "Riichi",eng: "Riichi",score: 1}, "Ippatsu": {jpn: "Ippatsu",eng: "One Shot",score: 1}, "Daburu Riichi": {jpn: "Daburu Riichi",eng: "Double Riichi",score: 1}, "Menzen Tsumo": {jpn: "Menzen Tsumo",eng: "Fully Concealed Hand",score: 1}, "Pinfu": {jpn: "Pinfu",eng: "Pinfu",score: 1}, "Iipeikou": {jpn: "Iipeikou",eng: "Pure Double Chow",score: 1}, "Tanyao Chuu": {jpn: "Tanyao Chuu",eng: "All Simples",score: 1}, "San Shoku Doujin": {jpn: "San Shoku Doujin",eng: "Mixed Triple Chow",score: 1}, "Concealed San Shoku Doujin": {jpn: "Concealed San Shoku Doujin",eng: "Concealed Mixed Triple Chow",score: 2}, "Itsu": {jpn: "Itsu",eng: "Pure Straight",score: 1}, "Concealed Itsu": {jpn: "Concealed Itsu",eng: "Concealed Pure Straight",score: 2}, "Dragon Fanpai/Yakuhai": {jpn: "Dragon Fanpai/Yakuhai",eng: "Dragon Pung/Kong",score: 1}, "Seat Fanpai/Yakuhai": {jpn: "Seat Fanpai/Yakuhai",eng: "Seat Pung/Kong",score: 1}, "Prevailing Fanpai/Yakuhai": {jpn: "Prevailing Fanpai/Yakuhai",eng: "Prevailing Pung/Kong",score: 1}, "Chanta": {jpn: "Chanta",eng: "Outside Hand",score: 1}, "Concealed Chanta": {jpn: "Concealed Chanta",eng: "Concealed Outside Hand",score: 2}, "Rinshan Kaihou": {jpn: "Rinshan Kaihou",eng: "After a Kong",score: 1}, "Chan Kan": {jpn: "Chan Kan",eng: "Robbing a Kong",score: 1}, "Haitei": {jpn: "Haitei",eng: "Under the Sea",score: 1}, "Houtei": {jpn: "Houtei",eng: "Bottom of the Sea",score: 1}, "Chii Toitsu": {jpn: "Chii Toitsu",eng: "Seven Pairs",score: 2}, "San Shoku Dokou": {jpn: "San Shoku Dokou",eng: "Triple Pung",score: 2}, "San Ankou": {jpn: "San Ankou",eng: "Three Concealed Pungs",score: 2}, "San Kan Tsu": {jpn: "San Kan Tsu",eng: "Three Kongs",score: 2}, "Toitoi Hou": {jpn: "Toitoi Hou",eng: "All Pungs",score: 2}, "Honitsu": {jpn: "Honitsu",eng: "Half Flush",score: 2}, "Concealed Honitsu": {jpn: "Concealed Honitsu",eng: "Concealed Half Flush",score: 3}, "Shou Sangen": {jpn: "Shou Sangen",eng: "Little Three Dragons",score: 2}, "Honroutou": {jpn: "Honroutou",eng: "All Terminals and Honours",score: 2}, "Junchan": {jpn: "Junchan",eng: "Terminals in All Sets",score: 2}, "Concealed Junchan": {jpn: "Concealed Junchan",eng: "Concealed Terminals in All Sets",score: 3}, "Ryan Peikou": {jpn: "Ryan Peikou",eng: "Twice Pure Double Chow",score: 3}, "Chinitsu": {jpn: "Chinitsu",eng: "Full Flush",score: 5}, "Concealed Chinitsu": {jpn: "Concealed Chinitsu",eng: "Concealed Full Flush",score: 6}, "Renho": {jpn: "Renho",eng: "Blessing of Man",score: 5}, "Kokushi Musou": {jpn: "Kokushi Musou",eng: "Thirteen Orphans",score: "Y"}, "Chuuren Pooto": {jpn: "Chuuren Pooto",eng: "Nine Gates",score: "Y"}, "Tenho": {jpn: "Tenho",eng: "Blessing of Heaven",score: "Y"}, "Chiho": {jpn: "Chiho",eng: "Blessing of Earth",score: "Y"}, "Suu Ankou": {jpn: "Suu Ankou",eng: "Four Concealed Pungs",score: "Y"}, "Suu Kan Tsu": {jpn: "Suu Kan Tsu",eng: "Four Kongs",score: "Y"}, "Ryuu Iisou": {jpn: "Ryuu Iisou",eng: "All Green",score: "Y"}, "Chinrouto": {jpn: "Chinrouto",eng: "All Terminals",score: "Y"}, "Tsuu Iisou": {jpn: "Tsuu Iisou",eng: "All Honours",score: "Y"}, "Dai Sangen": {jpn: "Dai Sangen",eng: "Big Three Winds",score: "Y"}, "Shou Suushii": {jpn: "Shou Suushii",eng: "Little Four Winds",score: "Y"}, "Dai Suushii": {jpn: "Dai Suushii",eng: "Big Four Winds",score: "Y"} } #Class used to send data about game state into scorer class gameFlags constructor: (@playerWind, @roundWind, @flags = []) -> @riichi = "Riichi" in @flags @ippatsu = "Ippatsu" in @flags @daburuRiichi = "Daburu Riichi" in @flags @houtei = "Houtei" in @flags @haitei = "Haitei" in @flags @chanKan = "Chan Kan" in @flags @rinshanKaihou = "Rinshan Kaihou" in @flags @tenho = "Tenho" in @flags @chiho = "Chiho" in @flags @renho = "Renho" in @flags #Finds which tiles can be discarded from a hand in order that it will be tenpai after the discard. tenpaiWithout = (hand) -> tilesToDiscard = [] for tile in hand.uncalled() testHand = _.cloneDeep(hand) testHand.discard(tile.getTextName()) if(tenpaiWith(testHand).length > 0) tilesToDiscard.push(tile) return tilesToDiscard #Finds which tiles could turn a hand into a winning hand tenpaiWith = (hand) -> winningTiles = [] possibleTiles = [] possibleTiles.push(new gamePieces.Tile(x,y)) for x in ["pin","sou","wan"] for y in [1..9] possibleTiles.push(new gamePieces.Tile("dragon",x)) for x in ["red","green","white"] possibleTiles.push(new gamePieces.Tile("wind",x)) for x in ["east","south","west","north"] for tile in possibleTiles testHand = _.cloneDeep(hand) testHand.lastTileDrawn = tile testHand.contains.push(tile) testHand.draw(null,0) if(getPossibleHands(testHand).length > 0) if(_.filter(testHand.contains,(x)->_.isEqual(x,tile)).length < 5) winningTiles.push(tile) return winningTiles #Checks whether a hand is the thirteen orphans hand or not. thirteenOrphans = (hand,lastTile) -> testHand = hand.contains testHand.push(lastTile) return _.xorWith(testHand, gamePieces.allTerminalsAndHonorsGetter(), _.isEqual).length == 0 scoreMahjongHand = (hand, gameDataFlags, dora) -> #Takes a hand of mahajong tiles and finds the highest scoring way it can be interpreted, returning the score, and the melds which lead to that score possibleHands = getPossibleHands(hand) if possibleHands.length == 0 return([0, "Not a Scoring Hand"]) doras = getDora(hand,gameDataFlags.riichi,dora) doraPoints = doras[0] urDoraPoints = doras[1] scores = (getScore(getYaku(handPattern, gameDataFlags), doraPoints, urDoraPoints) for handPattern in possibleHands) #console.log(scores) maxScore = _.maxBy(scores, (x) -> x[0]) #maxLocation = _.indexOf(scores,maxScore) #console.log(maxScore) return(maxScore) getDora = (hand, riichi, doraSets) -> nextValue = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:1,"East":"South","South":"West","West":"North","North":"East","Red":"White","White":"Green","Green":"Red"} dora = doraSets[0] urDora = doraSets[1] doraPoints = 0 urDoraPoints = 0 for doraIndicator in dora for tile in hand.contains if(doraIndicator.suit == tile.suit && nextValue[doraIndicator.value] == tile.value) doraPoints += 1 if(riichi) for urDoraIndicator in urDora for tile in hand.contains if(urDoraIndicator.suit == tile.suit && nextValue[urDoraIndicator.value] == tile.value) urDoraPoints += 1 return [doraPoints, urDoraPoints] getPossibleHands = (hand) -> #Takes a hand of mahjong tiles and finds every possible way the hand could be interpreted to be a winning hand, returning each different meld combination possibleHands = [] possiblePatterns = [] allTerminalsAndHonors = gamePieces.allTerminalsAndHonorsGetter() handTiles = hand.contains if _.intersectionWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 13 && _.xorWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 0 drawLocation = _.findIndex(handTiles,(x)->_.isEqual(hand.lastTileDrawn,x)) if(drawLocation == 13 || !_.isEqual(handTiles[drawLocation],handTiles[drawLocation+1])) return(["thirteenorphans"]) #Normal 13 orphans else return(["thirteenorphans+"]) #13 way wait, 13 orphans if _.uniqWith(handTiles,_.isEqual).length == 7 pairGroup = _.chunk(handTiles, 2) if _.every(pairGroup, (x) -> gamePieces.isMeld(x) == "Pair") possiblePatterns.push(_.map(pairGroup,(x)-> return new gamePieces.Meld(x))) #Any hands other than pairs/13 orphans _normalHandFinder = (melds, remaining) => if(!remaining || remaining.length == 0) possiblePatterns.push(melds) return "Yep" else if(remaining.length == 1) return "Nope" pairRemaining = true for x in melds if(x.type == "Pair") pairRemaining = false if(!pairRemaining && remaining.length == 2) return "Nope" if(pairRemaining && _.isEqual(remaining[0],remaining[1])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1]])),remaining[2..]) if(remaining.length >= 3) if(_.isEqual(remaining[0],remaining[1]) && _.isEqual(remaining[1],remaining[2])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1],remaining[2]])),remaining[3..]) nextInRun = new gamePieces.Tile(remaining[0].suit,remaining[0].value+1) nextAt = _.findIndex(remaining,(x)->_.isEqual(nextInRun,x)) afterThat = new gamePieces.Tile(remaining[0].suit,remaining[0].value+2) afterAt = _.findIndex(remaining,(x)->_.isEqual(afterThat,x)) if(nextAt != -1 && afterAt != -1) pruned = remaining[0..] pruned.splice(nextAt,1) afterAt = _.findIndex(pruned,(x)->_.isEqual(afterThat,x)) pruned.splice(afterAt,1) pruned = pruned[1..] _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],nextInRun,afterThat])),pruned) _drawnTilePlacer = () => for pattern in possiblePatterns for meld, i in pattern if(meld.containsTile(hand.lastTileDrawn) && meld.takenFrom == "self") chosenOne = _.cloneDeep(meld) chosenOne.lastDrawnTile = _.clone(hand.lastTileDrawn) chosenOne.takenFrom = hand.lastTileFrom existingHand = _.cloneDeep(pattern) existingHand[i] = chosenOne possibleHands.push(existingHand) _normalHandFinder(hand.calledMelds,hand.uncalled()) _drawnTilePlacer() return possibleHands getYaku = (melds, gameDataFlags) -> #Takes a set of melds and returns the yaku that made up that score if(melds in ["thirteenorphans","thirteenorphans+"]) return({yaku:["Kokushi Musou"],fu:0,flags:gameDataFlags}) for meld in melds if meld.lastDrawnTile selfDraw = meld.takenFrom == "self" fuArray = _calculateFu(melds, selfDraw, gameDataFlags) fu = fuArray[0] meldFu = fuArray[1] isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false yakuModifiers = [] #I think it could be more useful to calc out all of the yaku names, #and then generate a score from that. Plus we could print them all for the player. #Romanji names used in the code, but output can use either romanji or english using translation lists up above. suitList = (meld.suit() for meld in melds) chowList = (meld for meld in melds when meld.type == "Chow") pungList = (meld for meld in melds when meld.type in ["Pung","Kong"]) kongList = (meld for meld in melds when meld.type == "Kong") concealedPungs = 0 #Used for San Ankou identicalChow = 0 #Used for Iipeikou and Ryan Peikou similarChow = {} #Used for San Shoku Doujin similarPung = {} #Used for San Shoku Dokou possibleStraight = {} #Used for Itsu for chow1, index1 in chowList if(chow1.value() in ["1 - 2 - 3","4 - 5 - 6","7 - 8 - 9"]) if chow1.suit() of possibleStraight possibleStraight[chow1.suit()].push(chow1.value()) else possibleStraight[chow1.suit()] = [chow1.value()] for chow2, index2 in chowList if(index1 != index2) if _.isEqual(chow1,chow2) identicalChow += 1 else if(chow1.value() == chow2.value()) if chow1.value() of similarChow similarChow[chow1.value()].push(chow1.suit()) else similarChow[chow1.value()] = [chow1.suit()] for pung in pungList if(pung.suit() in ["pin","sou","wan"]) if pung.value() of similarPung similarPung[pung.value()].push(pung.suit()) else similarPung[pung.value()] = [pung.suit()] if(pung.takenFrom == "self") concealedPungs += 1 #These should probably all be wrapped up into their own functions. if isConcealedHand if (gameDataFlags.riichi) # winning player has called riichi yakuModifiers.push("Riichi") if(gameDataFlags.ippatsu) yakuModifiers.push("Ippatsu") #Winning on first round after declaring riichi if(gameDataFlags.daburuRiichi) yakuModifiers.push("Daburu Riichi") #Calling riichi on first turn of game if selfDraw #Menzen Tsumo - Self draw on concaled hand yakuModifiers.push("Menzen Tsumo") #Pinfu - Concealed all chows hand with a valuless pair if(fu != 25 && meldFu == 0) yakuModifiers.push("Pinfu") #Iipeikou - Concealed hand with two completely identical chow. if identicalChow in [2,6] yakuModifiers.push("Iipeikou") #Ryan Peikou - Concealed hand with two sets of two identical chows if identicalChow in [4,12] yakuModifiers.push("Ryan Peikou") #Chii Toitsu - Concealed hand with 7 pairs if melds.length == 7 yakuModifiers.push("Chii Toitsu") #Renho - Blessing of Man, Win in first go round on discard if(gameDataFlags.renho) yakuModifiers.push("Renho") #Tanyao Chuu - All simples (no terminals/honors) if (_.every(melds, (x) -> !_meldContainsAtLeastOneTerminalOrHonor(x))) yakuModifiers.push("Tanyao Chuu") #Rinshan Kaihou - Mahjong declared on replacementTile from Kong if(gameDataFlags.rinshanKaihou) yakuModifiers.push("Rinshan Kaihou") #Chan Kan - Robbing the Kong, Mahjong when pung is extended to kong if(gameDataFlags.chanKan) yakuModifiers.push("Chan Kan") #Haitei - Winning off last drawn tile of wall if(gameDataFlags.haitei) yakuModifiers.push("Haitei") #Houtei - Winning off last tile discard in game if(gameDataFlags.houtei) yakuModifiers.push("Houtei") #San Shoku Doujin - Mixed Triple Chow for value,suit of similarChow if(_.uniq(suit).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed San Shoku Doujin") else yakuModifiers.push("San Shoku Doujin") #San Shoku Dokou - Triple Pung in different suits for value, suit of similarPung if(_.uniq(suit).length == 3) yakuModifiers.push("San Shoku Dokou") #San Kan Tsu - Three Kongs if(kongList.length == 3) yakuModifiers.push("San Kan Tsu") #San Ankou - 3 Concealed Pungs if(concealedPungs == 3) yakuModifiers.push("San Ankou") #Toitoi Hou - All pungs/kongs if(pungList.length == 4) yakuModifiers.push("Toitoi Hou") #Itsu - Pure Straight for suit,value of possibleStraight if(_.uniq(value).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed Itsu") else yakuModifiers.push("Itsu") #Fanpai/Yakuhai - Pung/kong of dragons, round wind, or player wind. for meld in pungList if meld.suit() == "dragon" yakuModifiers.push("Dragon Fanpai/Yakuhai") if meld.value() == gameDataFlags.playerWind.toLowerCase() yakuModifiers.push("Seat Fanpai/Yakuhai") if meld.value() == gameDataFlags.roundWind.toLowerCase() yakuModifiers.push("Prevailing Fanpai/Yakuhai") #Chanta - All sets contain terminals or honours, there are both terminals and honors in the hand, the pair is terminals or honours, and the hand contains at least one chow. if chowList.length > 0 && _.every(melds, _meldContainsAtLeastOneTerminalOrHonor) && _.some(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Honor") if(isConcealedHand) yakuModifiers.push("Concealed Chanta") else yakuModifiers.push("Chanta") #Shou Sangen - Little Three Dragons, two pungs/kongs and a pair of Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 2) if((suit for suit in suitList when suit == "dragon").length == 3) yakuModifiers.push("Shou Sangen") #Honroutou - All Terminals and Honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.xor(suitList,["dragon","wind"]).length > 0) if (meld for meld in melds when (meld.suit() in ["dragon","wind"] || meld.value() in [1,9])).length == melds.length yakuModifiers.push("Honroutou") #Junchan - Terminals in All Sets, but at least one Chow if(chowList.length > 0 && _.every(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Terminal")) if(isConcealedHand) yakuModifiers.push("Concealed Junchan") else yakuModifiers.push("Junchan") #Honitsu - Half Flush - One suit plus honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.uniq(_.difference(suitList,["dragon","wind"])).length == 1) if(isConcealedHand) yakuModifiers.push("Concealed Honitsu") else yakuModifiers.push("Honitsu") #Chinitsu - Full Flush - One Suit, no honors if(_.uniq(suitList).length == 1 and suitList[0] not in ["dragon", "wind"]) if(isConcealedHand) yakuModifiers.push("Concealed Chinitsu") else yakuModifiers.push("Chinitsu") #Yakuman if(isConcealedHand) #Kokushi Musou - 13 Orphans if(melds in ["thirteenorphans","thirteenorphans+"]) yakuModifiers.push("Kokushi Musou") #Chuuren Pooto - Nine Gates if("Concealed Chinitsu" in yakuModifiers) if(kongList.length == 0) valuePattern = _.flattenDeep((meld.tiles for meld in melds)) valuePattern = _.map(valuePattern, (x) -> x.value) stringPattern = _.join(valuePattern, "") if stringPattern in ["11112345678999","11122345678999","11123345678999","11123445678999","11123455678999","11123456678999","11123456778999","11123456788999","11123456789999"] yakuModifiers.push("Chuuren Pooto") #Tenho - Blessing of Heaven, mahjong on starting hand if(gameDataFlags.tenho) yakuModifiers.push("Tenho") #Chiho - Blessing of Earth, mahjong on first draw if(gameDataFlags.chiho) yakuModifiers.push("Chiho") #Suu Ankou - Four Concealed Pungs if(concealedPungs == 4) yakuModifiers.push("Suu Ankou") #Suu Kan Tsu - Four Kongs if(kongList.length == 4) yakuModifiers.push("Suu Kan Tsu") #Ryuu Iisou - All Green if(_.every(melds,_meldIsGreen)) yakuModifiers.push("Ryuu Iisou") #Chinrouto - All Terminals if(_.every(melds,(x) -> x.value() in [1,9])) yakuModifiers.push("Chinrouto") #Tsuu Iisou - All Honors if(_.every(melds,(x) -> x.suit() in ["dragon", "wind"])) yakuModifiers.push("Tsuu Iisou") #Dai Sangan - Big Three Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 3) yakuModifiers.push("Dai Sangen") #Shou Suushii - Little Four Winds if((suit for suit in suitList when suit == "wind").length == 4) if((pung for pung in pungList when pung.suit() == "wind").length == 3) yakuModifiers.push("Shou Suushii") #Dai Suushii - Big Four Winds if((pung for pung in pungList when pung.suit() == "wind").length == 4) yakuModifiers.push("Dai Suushii") return({yaku:yakuModifiers,fu:fu,flags:gameDataFlags,selfDraw:selfDraw}) _meldContainsAtLeastOneTerminalOrHonor = (meld) -> for tile in meld.tiles if tile.isHonor() return "Honor" else if tile.isTerminal() return "Terminal" return false _meldIsGreen = (meld) -> for tile in meld.tiles if !tile.isGreen() return false return true _meldContainsOnlyGivenTile = (meld, givenTile) -> allSameTile = true for tile in meld.tiles if tile != givenTile allSameTile = false break return allSameTile _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore _roundUpToClosestTen = (inScore) -> if (inScore%10)!=0 return (inScore//10+1)*10 else inScore _calculateFu = (melds, selfDraw, gameDataFlags) -> isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false baseFu = 0 if(melds.length == 7) baseFu = 25 else if(isConcealedHand && !selfDraw) baseFu = 30 else baseFu = 20 meldFu = 0 if(melds.length != 7) for meld in melds if(meld.type == "Pung") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 8 else meldFu += 4 else if(meld.takenFrom == "self") meldFu += 4 else meldFu += 2 if(meld.type == "Kong") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 32 else meldFu += 16 else if(meld.takenFrom == "self") meldFu += 16 else meldFu += 8 if(meld.type == "Pair") if(meld.suit() == "dragon") meldFu += 2 else if(meld.suit() == "wind") if(meld.value() == gameDataFlags.playerWind) meldFu += 2 if(meld.value() == gameDataFlags.roundWind) meldFu += 2 if(meld.lastDrawnTile) meldFu += 2 if(meld.type == "Chow") if(meld.lastDrawnTile) if(meld.lastDrawnTile.value*3 == meld.tiles[0].value+meld.tiles[1].value+meld.tiles[2].value) meldFu += 2 if(meld.value() == "1 - 2 - 3" && meld.lastDrawnTile.value == 3) meldFu += 2 if(meld.value() == "7 - 8 - 9" && meld.lastDrawnTile.value == 7) meldFu += 2 if(!(meldFu == 0 && isConcealedHand) && selfDraw) meldFu += 2 if(meldFu == 0 && !isConcealedHand) meldFu += 2 fu = baseFu + meldFu #console.log(fu) if(fu != 25) fu = _roundUpToClosestTen(fu) return [fu, meldFu] getScore = (values, dora, urDora) -> if(values.yaku.length == 0) return([0,["No Yaku"]]) #Score the yakuModifiers list yakuman = false yakuPoints = 0 printedYaku = [] for yaku in values.yaku #testing if(yaku not of yakuList) console.log(yaku) else if(yakuList[yaku].score == "Y") yakuman = true else if(yaku != "Renho") yakuPoints += yakuList[yaku].score if(yakuman) printedYaku = (yaku for yaku in values.yaku when yakuList[yaku].score == "Y") else if("Renho" in values.yaku) if(yakuPoints > 0 && yakuPoints + dora > 5) printedYaku = (yaku for yaku in values.yaku when yaku != "Renho") fan = yakuPoints + dora + urDora else printedYaku = ["Renho"] fan = 5 else printedYaku = values.yaku fan = yakuPoints + dora + urDora if "Renho" not in printedYaku && !yakuman if dora > 0 printedYaku.push("Dora: #{dora}") if urDora > 0 printedYaku.push("Ur Dora: #{urDora}") #Gives Base Score if yakuman baseScore = 8000 else if fan >= 5 if(fan == 5) baseScore = 2000 else if(fan <= 7) baseScore = 3000 else if(fan <= 10) baseScore = 4000 else baseScore = 5000 else #console.log(values.fu) baseScore = values.fu * Math.pow(2,2+fan) if baseScore > 2000 baseScore = 2000 return [baseScore,printedYaku] module.exports.scoreMahjongHand = scoreMahjongHand module.exports.getPossibleHands = getPossibleHands module.exports.gameFlags = gameFlags module.exports.tenpaiWith = tenpaiWith module.exports.tenpaiWithout = tenpaiWithout module.exports.thirteenOrphans = thirteenOrphans module.exports.yakuList = yakuList
119713
_ = require('lodash') gamePieces = require('./akagiTiles.coffee') yakuList = { "Riichi": {jpn: "Riichi",eng: "Riichi",score: 1}, "Ippatsu": {jpn: "Ippatsu",eng: "One Shot",score: 1}, "Daburu Riichi": {jpn: "Daburu Riichi",eng: "Double Riichi",score: 1}, "Menzen Tsumo": {jpn: "Menzen Tsumo",eng: "Fully Concealed Hand",score: 1}, "Pinfu": {jpn: "Pinfu",eng: "Pinfu",score: 1}, "Iipeikou": {jpn: "Iipeikou",eng: "Pure Double Chow",score: 1}, "Tanyao Chuu": {jpn: "Tanyao Chuu",eng: "All Simples",score: 1}, "San Shoku Doujin": {jpn: "San Shoku Doujin",eng: "Mixed Triple Chow",score: 1}, "Concealed San Shoku Doujin": {jpn: "Concealed San Shoku Doujin",eng: "Concealed Mixed Triple Chow",score: 2}, "Itsu": {jpn: "Itsu",eng: "Pure Straight",score: 1}, "Concealed Itsu": {jpn: "Concealed Itsu",eng: "Concealed Pure Straight",score: 2}, "Dragon Fanpai/Yakuhai": {jpn: "Dragon Fanpai/Yakuhai",eng: "Dragon Pung/Kong",score: 1}, "Seat Fanpai/Yakuhai": {jpn: "Seat Fanpai/Yakuhai",eng: "Seat Pung/Kong",score: 1}, "Prevailing Fanpai/Yakuhai": {jpn: "Prevailing Fanpai/Yakuhai",eng: "Prevailing Pung/Kong",score: 1}, "<NAME>": {jpn: "<NAME>",eng: "Outside Hand",score: 1}, "Concealed Chanta": {jpn: "Concealed Ch<NAME>",eng: "Concealed Outside Hand",score: 2}, "<NAME>": {jpn: "<NAME>",eng: "After a Kong",score: 1}, "<NAME>": {jpn: "<NAME>",eng: "Robbing a Kong",score: 1}, "<NAME>": {jpn: "Ha<NAME>",eng: "Under the Sea",score: 1}, "H<NAME>": {jpn: "H<NAME>",eng: "Bottom of the Sea",score: 1}, "<NAME>": {jpn: "<NAME>",eng: "Seven Pairs",score: 2}, "San Shoku Dokou": {jpn: "San Shoku Dokou",eng: "Triple Pung",score: 2}, "San Ankou": {jpn: "San Ankou",eng: "Three Concealed Pungs",score: 2}, "San Kan Tsu": {jpn: "San Kan Tsu",eng: "Three Kongs",score: 2}, "<NAME>ito<NAME>": {jpn: "To<NAME>",eng: "All Pungs",score: 2}, "Honitsu": {jpn: "Honitsu",eng: "Half Flush",score: 2}, "Concealed Honitsu": {jpn: "Concealed Honitsu",eng: "Concealed Half Flush",score: 3}, "Sh<NAME>": {jpn: "Sh<NAME>",eng: "Little Three Dragons",score: 2}, "Honroutou": {jpn: "Honroutou",eng: "All Terminals and Honours",score: 2}, "Junchan": {jpn: "Junchan",eng: "Terminals in All Sets",score: 2}, "Concealed Junchan": {jpn: "Concealed Junchan",eng: "Concealed Terminals in All Sets",score: 3}, "Ryan Peikou": {jpn: "Ryan Peikou",eng: "Twice Pure Double Chow",score: 3}, "Chinitsu": {jpn: "Chinitsu",eng: "Full Flush",score: 5}, "Concealed Chinitsu": {jpn: "Concealed Chinitsu",eng: "Concealed Full Flush",score: 6}, "Renho": {jpn: "Renho",eng: "Blessing of Man",score: 5}, "Kokush<NAME> Musou": {jpn: "K<NAME>ushi Musou",eng: "Thirteen Orphans",score: "Y"}, "<NAME>": {jpn: "Ch<NAME>",eng: "Nine Gates",score: "Y"}, "Tenho": {jpn: "Tenho",eng: "Blessing of Heaven",score: "Y"}, "Chiho": {jpn: "Chiho",eng: "Blessing of Earth",score: "Y"}, "Suu Ankou": {jpn: "Suu Ankou",eng: "Four Concealed Pungs",score: "Y"}, "Suu Kan Tsu": {jpn: "Suu Kan Tsu",eng: "Four Kongs",score: "Y"}, "Ryuu Iisou": {jpn: "Ryuu Iisou",eng: "All Green",score: "Y"}, "Chinrouto": {jpn: "Chinrouto",eng: "All Terminals",score: "Y"}, "Tsuu Iisou": {jpn: "Tsuu Iisou",eng: "All Honours",score: "Y"}, "Dai Sangen": {jpn: "Dai Sangen",eng: "Big Three Winds",score: "Y"}, "<NAME>": {jpn: "Shou Suushii",eng: "Little Four Winds",score: "Y"}, "Dai Suushii": {jpn: "Dai Suushii",eng: "Big Four Winds",score: "Y"} } #Class used to send data about game state into scorer class gameFlags constructor: (@playerWind, @roundWind, @flags = []) -> @riichi = "Riichi" in @flags @ippatsu = "Ippatsu" in @flags @daburuRiichi = "<NAME>" in @flags @houtei = "Houtei" in @flags @haitei = "Haitei" in @flags @chanKan = "Chan Kan" in @flags @rinshanKaihou = "R<NAME>" in @flags @tenho = "Tenho" in @flags @chiho = "Chiho" in @flags @renho = "Renho" in @flags #Finds which tiles can be discarded from a hand in order that it will be tenpai after the discard. tenpaiWithout = (hand) -> tilesToDiscard = [] for tile in hand.uncalled() testHand = _.cloneDeep(hand) testHand.discard(tile.getTextName()) if(tenpaiWith(testHand).length > 0) tilesToDiscard.push(tile) return tilesToDiscard #Finds which tiles could turn a hand into a winning hand tenpaiWith = (hand) -> winningTiles = [] possibleTiles = [] possibleTiles.push(new gamePieces.Tile(x,y)) for x in ["pin","sou","wan"] for y in [1..9] possibleTiles.push(new gamePieces.Tile("dragon",x)) for x in ["red","green","white"] possibleTiles.push(new gamePieces.Tile("wind",x)) for x in ["east","south","west","north"] for tile in possibleTiles testHand = _.cloneDeep(hand) testHand.lastTileDrawn = tile testHand.contains.push(tile) testHand.draw(null,0) if(getPossibleHands(testHand).length > 0) if(_.filter(testHand.contains,(x)->_.isEqual(x,tile)).length < 5) winningTiles.push(tile) return winningTiles #Checks whether a hand is the thirteen orphans hand or not. thirteenOrphans = (hand,lastTile) -> testHand = hand.contains testHand.push(lastTile) return _.xorWith(testHand, gamePieces.allTerminalsAndHonorsGetter(), _.isEqual).length == 0 scoreMahjongHand = (hand, gameDataFlags, dora) -> #Takes a hand of mahajong tiles and finds the highest scoring way it can be interpreted, returning the score, and the melds which lead to that score possibleHands = getPossibleHands(hand) if possibleHands.length == 0 return([0, "Not a Scoring Hand"]) doras = getDora(hand,gameDataFlags.riichi,dora) doraPoints = doras[0] urDoraPoints = doras[1] scores = (getScore(getYaku(handPattern, gameDataFlags), doraPoints, urDoraPoints) for handPattern in possibleHands) #console.log(scores) maxScore = _.maxBy(scores, (x) -> x[0]) #maxLocation = _.indexOf(scores,maxScore) #console.log(maxScore) return(maxScore) getDora = (hand, riichi, doraSets) -> nextValue = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:1,"East":"South","South":"West","West":"North","North":"East","Red":"White","White":"Green","Green":"Red"} dora = doraSets[0] urDora = doraSets[1] doraPoints = 0 urDoraPoints = 0 for doraIndicator in dora for tile in hand.contains if(doraIndicator.suit == tile.suit && nextValue[doraIndicator.value] == tile.value) doraPoints += 1 if(riichi) for urDoraIndicator in urDora for tile in hand.contains if(urDoraIndicator.suit == tile.suit && nextValue[urDoraIndicator.value] == tile.value) urDoraPoints += 1 return [doraPoints, urDoraPoints] getPossibleHands = (hand) -> #Takes a hand of mahjong tiles and finds every possible way the hand could be interpreted to be a winning hand, returning each different meld combination possibleHands = [] possiblePatterns = [] allTerminalsAndHonors = gamePieces.allTerminalsAndHonorsGetter() handTiles = hand.contains if _.intersectionWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 13 && _.xorWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 0 drawLocation = _.findIndex(handTiles,(x)->_.isEqual(hand.lastTileDrawn,x)) if(drawLocation == 13 || !_.isEqual(handTiles[drawLocation],handTiles[drawLocation+1])) return(["thirteenorphans"]) #Normal 13 orphans else return(["thirteenorphans+"]) #13 way wait, 13 orphans if _.uniqWith(handTiles,_.isEqual).length == 7 pairGroup = _.chunk(handTiles, 2) if _.every(pairGroup, (x) -> gamePieces.isMeld(x) == "Pair") possiblePatterns.push(_.map(pairGroup,(x)-> return new gamePieces.Meld(x))) #Any hands other than pairs/13 orphans _normalHandFinder = (melds, remaining) => if(!remaining || remaining.length == 0) possiblePatterns.push(melds) return "Yep" else if(remaining.length == 1) return "Nope" pairRemaining = true for x in melds if(x.type == "Pair") pairRemaining = false if(!pairRemaining && remaining.length == 2) return "Nope" if(pairRemaining && _.isEqual(remaining[0],remaining[1])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1]])),remaining[2..]) if(remaining.length >= 3) if(_.isEqual(remaining[0],remaining[1]) && _.isEqual(remaining[1],remaining[2])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1],remaining[2]])),remaining[3..]) nextInRun = new gamePieces.Tile(remaining[0].suit,remaining[0].value+1) nextAt = _.findIndex(remaining,(x)->_.isEqual(nextInRun,x)) afterThat = new gamePieces.Tile(remaining[0].suit,remaining[0].value+2) afterAt = _.findIndex(remaining,(x)->_.isEqual(afterThat,x)) if(nextAt != -1 && afterAt != -1) pruned = remaining[0..] pruned.splice(nextAt,1) afterAt = _.findIndex(pruned,(x)->_.isEqual(afterThat,x)) pruned.splice(afterAt,1) pruned = pruned[1..] _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],nextInRun,afterThat])),pruned) _drawnTilePlacer = () => for pattern in possiblePatterns for meld, i in pattern if(meld.containsTile(hand.lastTileDrawn) && meld.takenFrom == "self") chosenOne = _.cloneDeep(meld) chosenOne.lastDrawnTile = _.clone(hand.lastTileDrawn) chosenOne.takenFrom = hand.lastTileFrom existingHand = _.cloneDeep(pattern) existingHand[i] = chosenOne possibleHands.push(existingHand) _normalHandFinder(hand.calledMelds,hand.uncalled()) _drawnTilePlacer() return possibleHands getYaku = (melds, gameDataFlags) -> #Takes a set of melds and returns the yaku that made up that score if(melds in ["thirteenorphans","thirteenorphans+"]) return({yaku:["Kok<NAME>"],fu:0,flags:gameDataFlags}) for meld in melds if meld.lastDrawnTile selfDraw = meld.takenFrom == "self" fuArray = _calculateFu(melds, selfDraw, gameDataFlags) fu = fuArray[0] meldFu = fuArray[1] isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false yakuModifiers = [] #I think it could be more useful to calc out all of the yaku names, #and then generate a score from that. Plus we could print them all for the player. #Romanji names used in the code, but output can use either romanji or english using translation lists up above. suitList = (meld.suit() for meld in melds) chowList = (meld for meld in melds when meld.type == "Chow") pungList = (meld for meld in melds when meld.type in ["Pung","Kong"]) kongList = (meld for meld in melds when meld.type == "Kong") concealedPungs = 0 #Used for San Ankou identicalChow = 0 #Used for Iipeikou and Ryan Peikou similarChow = {} #Used for San Shoku Doujin similarPung = {} #Used for San Shoku Dokou possibleStraight = {} #Used for Itsu for chow1, index1 in chowList if(chow1.value() in ["1 - 2 - 3","4 - 5 - 6","7 - 8 - 9"]) if chow1.suit() of possibleStraight possibleStraight[chow1.suit()].push(chow1.value()) else possibleStraight[chow1.suit()] = [chow1.value()] for chow2, index2 in chowList if(index1 != index2) if _.isEqual(chow1,chow2) identicalChow += 1 else if(chow1.value() == chow2.value()) if chow1.value() of similarChow similarChow[chow1.value()].push(chow1.suit()) else similarChow[chow1.value()] = [chow1.suit()] for pung in pungList if(pung.suit() in ["pin","sou","wan"]) if pung.value() of similarPung similarPung[pung.value()].push(pung.suit()) else similarPung[pung.value()] = [pung.suit()] if(pung.takenFrom == "self") concealedPungs += 1 #These should probably all be wrapped up into their own functions. if isConcealedHand if (gameDataFlags.riichi) # winning player has called riichi yakuModifiers.push("Riichi") if(gameDataFlags.ippatsu) yakuModifiers.push("Ippatsu") #Winning on first round after declaring riichi if(gameDataFlags.daburuRiichi) yakuModifiers.push("Daburu Riichi") #Calling riichi on first turn of game if selfDraw #Menzen Tsumo - Self draw on concaled hand yakuModifiers.push("Menzen Tsumo") #Pinfu - Concealed all chows hand with a valuless pair if(fu != 25 && meldFu == 0) yakuModifiers.push("Pinfu") #Iipeikou - Concealed hand with two completely identical chow. if identicalChow in [2,6] yakuModifiers.push("Iipeikou") #Ryan Peikou - Concealed hand with two sets of two identical chows if identicalChow in [4,12] yakuModifiers.push("Ryan Peikou") #Chii Toitsu - Concealed hand with 7 pairs if melds.length == 7 yakuModifiers.push("Chii Toitsu") #Renho - Blessing of Man, Win in first go round on discard if(gameDataFlags.renho) yakuModifiers.push("Renho") #Tanyao Chuu - All simples (no terminals/honors) if (_.every(melds, (x) -> !_meldContainsAtLeastOneTerminalOrHonor(x))) yakuModifiers.push("Tanyao Chuu") #Rinshan Kaihou - Mahjong declared on replacementTile from Kong if(gameDataFlags.rinshanKaihou) yakuModifiers.push("Rinshan Kaihou") #Chan Kan - Robbing the Kong, Mahjong when pung is extended to kong if(gameDataFlags.chanKan) yakuModifiers.push("Chan Kan") #Haitei - Winning off last drawn tile of wall if(gameDataFlags.haitei) yakuModifiers.push("Haitei") #Houtei - Winning off last tile discard in game if(gameDataFlags.houtei) yakuModifiers.push("Houtei") #San Shoku Doujin - Mixed Triple Chow for value,suit of similarChow if(_.uniq(suit).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed San Shoku Doujin") else yakuModifiers.push("San Shoku Doujin") #San Shoku Dokou - Triple Pung in different suits for value, suit of similarPung if(_.uniq(suit).length == 3) yakuModifiers.push("San Shoku Dokou") #San Kan Tsu - Three Kongs if(kongList.length == 3) yakuModifiers.push("San Kan Tsu") #San Ankou - 3 Concealed Pungs if(concealedPungs == 3) yakuModifiers.push("San Ankou") #Toitoi Hou - All pungs/kongs if(pungList.length == 4) yakuModifiers.push("Toitoi Hou") #Itsu - Pure Straight for suit,value of possibleStraight if(_.uniq(value).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed Itsu") else yakuModifiers.push("Itsu") #Fanpai/Yakuhai - Pung/kong of dragons, round wind, or player wind. for meld in pungList if meld.suit() == "dragon" yakuModifiers.push("Dragon Fanpai/Yakuhai") if meld.value() == gameDataFlags.playerWind.toLowerCase() yakuModifiers.push("Seat Fanpai/Yakuhai") if meld.value() == gameDataFlags.roundWind.toLowerCase() yakuModifiers.push("Prevailing Fanpai/Yakuhai") #Chanta - All sets contain terminals or honours, there are both terminals and honors in the hand, the pair is terminals or honours, and the hand contains at least one chow. if chowList.length > 0 && _.every(melds, _meldContainsAtLeastOneTerminalOrHonor) && _.some(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Honor") if(isConcealedHand) yakuModifiers.push("Concealed Chanta") else yakuModifiers.push("Chanta") #<NAME> - Little Three Dragons, two pungs/kongs and a pair of Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 2) if((suit for suit in suitList when suit == "dragon").length == 3) yakuModifiers.push("Shou Sangen") #Honroutou - All Terminals and Honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.xor(suitList,["dragon","wind"]).length > 0) if (meld for meld in melds when (meld.suit() in ["dragon","wind"] || meld.value() in [1,9])).length == melds.length yakuModifiers.push("Honroutou") #Junchan - Terminals in All Sets, but at least one Chow if(chowList.length > 0 && _.every(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Terminal")) if(isConcealedHand) yakuModifiers.push("Concealed Junchan") else yakuModifiers.push("Junchan") #Honitsu - Half Flush - One suit plus honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.uniq(_.difference(suitList,["dragon","wind"])).length == 1) if(isConcealedHand) yakuModifiers.push("Concealed Honitsu") else yakuModifiers.push("Honitsu") #Chinitsu - Full Flush - One Suit, no honors if(_.uniq(suitList).length == 1 and suitList[0] not in ["dragon", "wind"]) if(isConcealedHand) yakuModifiers.push("Concealed Chinitsu") else yakuModifiers.push("Chinitsu") #Yakuman if(isConcealedHand) #<NAME> - 13 Orphans if(melds in ["thirteenorphans","thirteenorphans+"]) yakuModifiers.push("Kokushi Musou") #<NAME> - Nine Gates if("Concealed Chinitsu" in yakuModifiers) if(kongList.length == 0) valuePattern = _.flattenDeep((meld.tiles for meld in melds)) valuePattern = _.map(valuePattern, (x) -> x.value) stringPattern = _.join(valuePattern, "") if stringPattern in ["11112345678999","11122345678999","11123345678999","11123445678999","11123455678999","11123456678999","11123456778999","11123456788999","11123456789999"] yakuModifiers.push("Chuuren Pooto") #Tenho - Blessing of Heaven, mahjong on starting hand if(gameDataFlags.tenho) yakuModifiers.push("Tenho") #Chiho - Blessing of Earth, mahjong on first draw if(gameDataFlags.chiho) yakuModifiers.push("Chiho") #Suu Ankou - Four Concealed Pungs if(concealedPungs == 4) yakuModifiers.push("Suu Ankou") #Suu Kan Tsu - Four Kongs if(kongList.length == 4) yakuModifiers.push("Suu Kan Tsu") #Ryuu Iisou - All Green if(_.every(melds,_meldIsGreen)) yakuModifiers.push("Ryuu Iisou") #Chinrouto - All Terminals if(_.every(melds,(x) -> x.value() in [1,9])) yakuModifiers.push("Chinrouto") #Tsuu Iisou - All Honors if(_.every(melds,(x) -> x.suit() in ["dragon", "wind"])) yakuModifiers.push("Tsuu Iisou") #Dai Sangan - Big Three Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 3) yakuModifiers.push("Dai Sangen") #Shou Suushii - Little Four Winds if((suit for suit in suitList when suit == "wind").length == 4) if((pung for pung in pungList when pung.suit() == "wind").length == 3) yakuModifiers.push("Shou Suushii") #Dai Suushii - Big Four Winds if((pung for pung in pungList when pung.suit() == "wind").length == 4) yakuModifiers.push("Dai Suushii") return({yaku:yakuModifiers,fu:fu,flags:gameDataFlags,selfDraw:selfDraw}) _meldContainsAtLeastOneTerminalOrHonor = (meld) -> for tile in meld.tiles if tile.isHonor() return "Honor" else if tile.isTerminal() return "Terminal" return false _meldIsGreen = (meld) -> for tile in meld.tiles if !tile.isGreen() return false return true _meldContainsOnlyGivenTile = (meld, givenTile) -> allSameTile = true for tile in meld.tiles if tile != givenTile allSameTile = false break return allSameTile _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore _roundUpToClosestTen = (inScore) -> if (inScore%10)!=0 return (inScore//10+1)*10 else inScore _calculateFu = (melds, selfDraw, gameDataFlags) -> isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false baseFu = 0 if(melds.length == 7) baseFu = 25 else if(isConcealedHand && !selfDraw) baseFu = 30 else baseFu = 20 meldFu = 0 if(melds.length != 7) for meld in melds if(meld.type == "Pung") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 8 else meldFu += 4 else if(meld.takenFrom == "self") meldFu += 4 else meldFu += 2 if(meld.type == "Kong") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 32 else meldFu += 16 else if(meld.takenFrom == "self") meldFu += 16 else meldFu += 8 if(meld.type == "Pair") if(meld.suit() == "dragon") meldFu += 2 else if(meld.suit() == "wind") if(meld.value() == gameDataFlags.playerWind) meldFu += 2 if(meld.value() == gameDataFlags.roundWind) meldFu += 2 if(meld.lastDrawnTile) meldFu += 2 if(meld.type == "Chow") if(meld.lastDrawnTile) if(meld.lastDrawnTile.value*3 == meld.tiles[0].value+meld.tiles[1].value+meld.tiles[2].value) meldFu += 2 if(meld.value() == "1 - 2 - 3" && meld.lastDrawnTile.value == 3) meldFu += 2 if(meld.value() == "7 - 8 - 9" && meld.lastDrawnTile.value == 7) meldFu += 2 if(!(meldFu == 0 && isConcealedHand) && selfDraw) meldFu += 2 if(meldFu == 0 && !isConcealedHand) meldFu += 2 fu = baseFu + meldFu #console.log(fu) if(fu != 25) fu = _roundUpToClosestTen(fu) return [fu, meldFu] getScore = (values, dora, urDora) -> if(values.yaku.length == 0) return([0,["No Yaku"]]) #Score the yakuModifiers list yakuman = false yakuPoints = 0 printedYaku = [] for yaku in values.yaku #testing if(yaku not of yakuList) console.log(yaku) else if(yakuList[yaku].score == "Y") yakuman = true else if(yaku != "Renho") yakuPoints += yakuList[yaku].score if(yakuman) printedYaku = (yaku for yaku in values.yaku when yakuList[yaku].score == "Y") else if("Renho" in values.yaku) if(yakuPoints > 0 && yakuPoints + dora > 5) printedYaku = (yaku for yaku in values.yaku when yaku != "Renho") fan = yakuPoints + dora + urDora else printedYaku = ["Renho"] fan = 5 else printedYaku = values.yaku fan = yakuPoints + dora + urDora if "Renho" not in printedYaku && !yakuman if dora > 0 printedYaku.push("Dora: #{dora}") if urDora > 0 printedYaku.push("Ur Dora: #{urDora}") #Gives Base Score if yakuman baseScore = 8000 else if fan >= 5 if(fan == 5) baseScore = 2000 else if(fan <= 7) baseScore = 3000 else if(fan <= 10) baseScore = 4000 else baseScore = 5000 else #console.log(values.fu) baseScore = values.fu * Math.pow(2,2+fan) if baseScore > 2000 baseScore = 2000 return [baseScore,printedYaku] module.exports.scoreMahjongHand = scoreMahjongHand module.exports.getPossibleHands = getPossibleHands module.exports.gameFlags = gameFlags module.exports.tenpaiWith = tenpaiWith module.exports.tenpaiWithout = tenpaiWithout module.exports.thirteenOrphans = thirteenOrphans module.exports.yakuList = yakuList
true
_ = require('lodash') gamePieces = require('./akagiTiles.coffee') yakuList = { "Riichi": {jpn: "Riichi",eng: "Riichi",score: 1}, "Ippatsu": {jpn: "Ippatsu",eng: "One Shot",score: 1}, "Daburu Riichi": {jpn: "Daburu Riichi",eng: "Double Riichi",score: 1}, "Menzen Tsumo": {jpn: "Menzen Tsumo",eng: "Fully Concealed Hand",score: 1}, "Pinfu": {jpn: "Pinfu",eng: "Pinfu",score: 1}, "Iipeikou": {jpn: "Iipeikou",eng: "Pure Double Chow",score: 1}, "Tanyao Chuu": {jpn: "Tanyao Chuu",eng: "All Simples",score: 1}, "San Shoku Doujin": {jpn: "San Shoku Doujin",eng: "Mixed Triple Chow",score: 1}, "Concealed San Shoku Doujin": {jpn: "Concealed San Shoku Doujin",eng: "Concealed Mixed Triple Chow",score: 2}, "Itsu": {jpn: "Itsu",eng: "Pure Straight",score: 1}, "Concealed Itsu": {jpn: "Concealed Itsu",eng: "Concealed Pure Straight",score: 2}, "Dragon Fanpai/Yakuhai": {jpn: "Dragon Fanpai/Yakuhai",eng: "Dragon Pung/Kong",score: 1}, "Seat Fanpai/Yakuhai": {jpn: "Seat Fanpai/Yakuhai",eng: "Seat Pung/Kong",score: 1}, "Prevailing Fanpai/Yakuhai": {jpn: "Prevailing Fanpai/Yakuhai",eng: "Prevailing Pung/Kong",score: 1}, "PI:NAME:<NAME>END_PI": {jpn: "PI:NAME:<NAME>END_PI",eng: "Outside Hand",score: 1}, "Concealed Chanta": {jpn: "Concealed ChPI:NAME:<NAME>END_PI",eng: "Concealed Outside Hand",score: 2}, "PI:NAME:<NAME>END_PI": {jpn: "PI:NAME:<NAME>END_PI",eng: "After a Kong",score: 1}, "PI:NAME:<NAME>END_PI": {jpn: "PI:NAME:<NAME>END_PI",eng: "Robbing a Kong",score: 1}, "PI:NAME:<NAME>END_PI": {jpn: "HaPI:NAME:<NAME>END_PI",eng: "Under the Sea",score: 1}, "HPI:NAME:<NAME>END_PI": {jpn: "HPI:NAME:<NAME>END_PI",eng: "Bottom of the Sea",score: 1}, "PI:NAME:<NAME>END_PI": {jpn: "PI:NAME:<NAME>END_PI",eng: "Seven Pairs",score: 2}, "San Shoku Dokou": {jpn: "San Shoku Dokou",eng: "Triple Pung",score: 2}, "San Ankou": {jpn: "San Ankou",eng: "Three Concealed Pungs",score: 2}, "San Kan Tsu": {jpn: "San Kan Tsu",eng: "Three Kongs",score: 2}, "PI:NAME:<NAME>END_PIitoPI:NAME:<NAME>END_PI": {jpn: "ToPI:NAME:<NAME>END_PI",eng: "All Pungs",score: 2}, "Honitsu": {jpn: "Honitsu",eng: "Half Flush",score: 2}, "Concealed Honitsu": {jpn: "Concealed Honitsu",eng: "Concealed Half Flush",score: 3}, "ShPI:NAME:<NAME>END_PI": {jpn: "ShPI:NAME:<NAME>END_PI",eng: "Little Three Dragons",score: 2}, "Honroutou": {jpn: "Honroutou",eng: "All Terminals and Honours",score: 2}, "Junchan": {jpn: "Junchan",eng: "Terminals in All Sets",score: 2}, "Concealed Junchan": {jpn: "Concealed Junchan",eng: "Concealed Terminals in All Sets",score: 3}, "Ryan Peikou": {jpn: "Ryan Peikou",eng: "Twice Pure Double Chow",score: 3}, "Chinitsu": {jpn: "Chinitsu",eng: "Full Flush",score: 5}, "Concealed Chinitsu": {jpn: "Concealed Chinitsu",eng: "Concealed Full Flush",score: 6}, "Renho": {jpn: "Renho",eng: "Blessing of Man",score: 5}, "KokushPI:NAME:<NAME>END_PI Musou": {jpn: "KPI:NAME:<NAME>END_PIushi Musou",eng: "Thirteen Orphans",score: "Y"}, "PI:NAME:<NAME>END_PI": {jpn: "ChPI:NAME:<NAME>END_PI",eng: "Nine Gates",score: "Y"}, "Tenho": {jpn: "Tenho",eng: "Blessing of Heaven",score: "Y"}, "Chiho": {jpn: "Chiho",eng: "Blessing of Earth",score: "Y"}, "Suu Ankou": {jpn: "Suu Ankou",eng: "Four Concealed Pungs",score: "Y"}, "Suu Kan Tsu": {jpn: "Suu Kan Tsu",eng: "Four Kongs",score: "Y"}, "Ryuu Iisou": {jpn: "Ryuu Iisou",eng: "All Green",score: "Y"}, "Chinrouto": {jpn: "Chinrouto",eng: "All Terminals",score: "Y"}, "Tsuu Iisou": {jpn: "Tsuu Iisou",eng: "All Honours",score: "Y"}, "Dai Sangen": {jpn: "Dai Sangen",eng: "Big Three Winds",score: "Y"}, "PI:NAME:<NAME>END_PI": {jpn: "Shou Suushii",eng: "Little Four Winds",score: "Y"}, "Dai Suushii": {jpn: "Dai Suushii",eng: "Big Four Winds",score: "Y"} } #Class used to send data about game state into scorer class gameFlags constructor: (@playerWind, @roundWind, @flags = []) -> @riichi = "Riichi" in @flags @ippatsu = "Ippatsu" in @flags @daburuRiichi = "PI:NAME:<NAME>END_PI" in @flags @houtei = "Houtei" in @flags @haitei = "Haitei" in @flags @chanKan = "Chan Kan" in @flags @rinshanKaihou = "RPI:NAME:<NAME>END_PI" in @flags @tenho = "Tenho" in @flags @chiho = "Chiho" in @flags @renho = "Renho" in @flags #Finds which tiles can be discarded from a hand in order that it will be tenpai after the discard. tenpaiWithout = (hand) -> tilesToDiscard = [] for tile in hand.uncalled() testHand = _.cloneDeep(hand) testHand.discard(tile.getTextName()) if(tenpaiWith(testHand).length > 0) tilesToDiscard.push(tile) return tilesToDiscard #Finds which tiles could turn a hand into a winning hand tenpaiWith = (hand) -> winningTiles = [] possibleTiles = [] possibleTiles.push(new gamePieces.Tile(x,y)) for x in ["pin","sou","wan"] for y in [1..9] possibleTiles.push(new gamePieces.Tile("dragon",x)) for x in ["red","green","white"] possibleTiles.push(new gamePieces.Tile("wind",x)) for x in ["east","south","west","north"] for tile in possibleTiles testHand = _.cloneDeep(hand) testHand.lastTileDrawn = tile testHand.contains.push(tile) testHand.draw(null,0) if(getPossibleHands(testHand).length > 0) if(_.filter(testHand.contains,(x)->_.isEqual(x,tile)).length < 5) winningTiles.push(tile) return winningTiles #Checks whether a hand is the thirteen orphans hand or not. thirteenOrphans = (hand,lastTile) -> testHand = hand.contains testHand.push(lastTile) return _.xorWith(testHand, gamePieces.allTerminalsAndHonorsGetter(), _.isEqual).length == 0 scoreMahjongHand = (hand, gameDataFlags, dora) -> #Takes a hand of mahajong tiles and finds the highest scoring way it can be interpreted, returning the score, and the melds which lead to that score possibleHands = getPossibleHands(hand) if possibleHands.length == 0 return([0, "Not a Scoring Hand"]) doras = getDora(hand,gameDataFlags.riichi,dora) doraPoints = doras[0] urDoraPoints = doras[1] scores = (getScore(getYaku(handPattern, gameDataFlags), doraPoints, urDoraPoints) for handPattern in possibleHands) #console.log(scores) maxScore = _.maxBy(scores, (x) -> x[0]) #maxLocation = _.indexOf(scores,maxScore) #console.log(maxScore) return(maxScore) getDora = (hand, riichi, doraSets) -> nextValue = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:1,"East":"South","South":"West","West":"North","North":"East","Red":"White","White":"Green","Green":"Red"} dora = doraSets[0] urDora = doraSets[1] doraPoints = 0 urDoraPoints = 0 for doraIndicator in dora for tile in hand.contains if(doraIndicator.suit == tile.suit && nextValue[doraIndicator.value] == tile.value) doraPoints += 1 if(riichi) for urDoraIndicator in urDora for tile in hand.contains if(urDoraIndicator.suit == tile.suit && nextValue[urDoraIndicator.value] == tile.value) urDoraPoints += 1 return [doraPoints, urDoraPoints] getPossibleHands = (hand) -> #Takes a hand of mahjong tiles and finds every possible way the hand could be interpreted to be a winning hand, returning each different meld combination possibleHands = [] possiblePatterns = [] allTerminalsAndHonors = gamePieces.allTerminalsAndHonorsGetter() handTiles = hand.contains if _.intersectionWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 13 && _.xorWith(handTiles, allTerminalsAndHonors,_.isEqual).length == 0 drawLocation = _.findIndex(handTiles,(x)->_.isEqual(hand.lastTileDrawn,x)) if(drawLocation == 13 || !_.isEqual(handTiles[drawLocation],handTiles[drawLocation+1])) return(["thirteenorphans"]) #Normal 13 orphans else return(["thirteenorphans+"]) #13 way wait, 13 orphans if _.uniqWith(handTiles,_.isEqual).length == 7 pairGroup = _.chunk(handTiles, 2) if _.every(pairGroup, (x) -> gamePieces.isMeld(x) == "Pair") possiblePatterns.push(_.map(pairGroup,(x)-> return new gamePieces.Meld(x))) #Any hands other than pairs/13 orphans _normalHandFinder = (melds, remaining) => if(!remaining || remaining.length == 0) possiblePatterns.push(melds) return "Yep" else if(remaining.length == 1) return "Nope" pairRemaining = true for x in melds if(x.type == "Pair") pairRemaining = false if(!pairRemaining && remaining.length == 2) return "Nope" if(pairRemaining && _.isEqual(remaining[0],remaining[1])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1]])),remaining[2..]) if(remaining.length >= 3) if(_.isEqual(remaining[0],remaining[1]) && _.isEqual(remaining[1],remaining[2])) _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],remaining[1],remaining[2]])),remaining[3..]) nextInRun = new gamePieces.Tile(remaining[0].suit,remaining[0].value+1) nextAt = _.findIndex(remaining,(x)->_.isEqual(nextInRun,x)) afterThat = new gamePieces.Tile(remaining[0].suit,remaining[0].value+2) afterAt = _.findIndex(remaining,(x)->_.isEqual(afterThat,x)) if(nextAt != -1 && afterAt != -1) pruned = remaining[0..] pruned.splice(nextAt,1) afterAt = _.findIndex(pruned,(x)->_.isEqual(afterThat,x)) pruned.splice(afterAt,1) pruned = pruned[1..] _normalHandFinder(_.concat(melds,new gamePieces.Meld([remaining[0],nextInRun,afterThat])),pruned) _drawnTilePlacer = () => for pattern in possiblePatterns for meld, i in pattern if(meld.containsTile(hand.lastTileDrawn) && meld.takenFrom == "self") chosenOne = _.cloneDeep(meld) chosenOne.lastDrawnTile = _.clone(hand.lastTileDrawn) chosenOne.takenFrom = hand.lastTileFrom existingHand = _.cloneDeep(pattern) existingHand[i] = chosenOne possibleHands.push(existingHand) _normalHandFinder(hand.calledMelds,hand.uncalled()) _drawnTilePlacer() return possibleHands getYaku = (melds, gameDataFlags) -> #Takes a set of melds and returns the yaku that made up that score if(melds in ["thirteenorphans","thirteenorphans+"]) return({yaku:["KokPI:NAME:<NAME>END_PI"],fu:0,flags:gameDataFlags}) for meld in melds if meld.lastDrawnTile selfDraw = meld.takenFrom == "self" fuArray = _calculateFu(melds, selfDraw, gameDataFlags) fu = fuArray[0] meldFu = fuArray[1] isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false yakuModifiers = [] #I think it could be more useful to calc out all of the yaku names, #and then generate a score from that. Plus we could print them all for the player. #Romanji names used in the code, but output can use either romanji or english using translation lists up above. suitList = (meld.suit() for meld in melds) chowList = (meld for meld in melds when meld.type == "Chow") pungList = (meld for meld in melds when meld.type in ["Pung","Kong"]) kongList = (meld for meld in melds when meld.type == "Kong") concealedPungs = 0 #Used for San Ankou identicalChow = 0 #Used for Iipeikou and Ryan Peikou similarChow = {} #Used for San Shoku Doujin similarPung = {} #Used for San Shoku Dokou possibleStraight = {} #Used for Itsu for chow1, index1 in chowList if(chow1.value() in ["1 - 2 - 3","4 - 5 - 6","7 - 8 - 9"]) if chow1.suit() of possibleStraight possibleStraight[chow1.suit()].push(chow1.value()) else possibleStraight[chow1.suit()] = [chow1.value()] for chow2, index2 in chowList if(index1 != index2) if _.isEqual(chow1,chow2) identicalChow += 1 else if(chow1.value() == chow2.value()) if chow1.value() of similarChow similarChow[chow1.value()].push(chow1.suit()) else similarChow[chow1.value()] = [chow1.suit()] for pung in pungList if(pung.suit() in ["pin","sou","wan"]) if pung.value() of similarPung similarPung[pung.value()].push(pung.suit()) else similarPung[pung.value()] = [pung.suit()] if(pung.takenFrom == "self") concealedPungs += 1 #These should probably all be wrapped up into their own functions. if isConcealedHand if (gameDataFlags.riichi) # winning player has called riichi yakuModifiers.push("Riichi") if(gameDataFlags.ippatsu) yakuModifiers.push("Ippatsu") #Winning on first round after declaring riichi if(gameDataFlags.daburuRiichi) yakuModifiers.push("Daburu Riichi") #Calling riichi on first turn of game if selfDraw #Menzen Tsumo - Self draw on concaled hand yakuModifiers.push("Menzen Tsumo") #Pinfu - Concealed all chows hand with a valuless pair if(fu != 25 && meldFu == 0) yakuModifiers.push("Pinfu") #Iipeikou - Concealed hand with two completely identical chow. if identicalChow in [2,6] yakuModifiers.push("Iipeikou") #Ryan Peikou - Concealed hand with two sets of two identical chows if identicalChow in [4,12] yakuModifiers.push("Ryan Peikou") #Chii Toitsu - Concealed hand with 7 pairs if melds.length == 7 yakuModifiers.push("Chii Toitsu") #Renho - Blessing of Man, Win in first go round on discard if(gameDataFlags.renho) yakuModifiers.push("Renho") #Tanyao Chuu - All simples (no terminals/honors) if (_.every(melds, (x) -> !_meldContainsAtLeastOneTerminalOrHonor(x))) yakuModifiers.push("Tanyao Chuu") #Rinshan Kaihou - Mahjong declared on replacementTile from Kong if(gameDataFlags.rinshanKaihou) yakuModifiers.push("Rinshan Kaihou") #Chan Kan - Robbing the Kong, Mahjong when pung is extended to kong if(gameDataFlags.chanKan) yakuModifiers.push("Chan Kan") #Haitei - Winning off last drawn tile of wall if(gameDataFlags.haitei) yakuModifiers.push("Haitei") #Houtei - Winning off last tile discard in game if(gameDataFlags.houtei) yakuModifiers.push("Houtei") #San Shoku Doujin - Mixed Triple Chow for value,suit of similarChow if(_.uniq(suit).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed San Shoku Doujin") else yakuModifiers.push("San Shoku Doujin") #San Shoku Dokou - Triple Pung in different suits for value, suit of similarPung if(_.uniq(suit).length == 3) yakuModifiers.push("San Shoku Dokou") #San Kan Tsu - Three Kongs if(kongList.length == 3) yakuModifiers.push("San Kan Tsu") #San Ankou - 3 Concealed Pungs if(concealedPungs == 3) yakuModifiers.push("San Ankou") #Toitoi Hou - All pungs/kongs if(pungList.length == 4) yakuModifiers.push("Toitoi Hou") #Itsu - Pure Straight for suit,value of possibleStraight if(_.uniq(value).length == 3) if(isConcealedHand) yakuModifiers.push("Concealed Itsu") else yakuModifiers.push("Itsu") #Fanpai/Yakuhai - Pung/kong of dragons, round wind, or player wind. for meld in pungList if meld.suit() == "dragon" yakuModifiers.push("Dragon Fanpai/Yakuhai") if meld.value() == gameDataFlags.playerWind.toLowerCase() yakuModifiers.push("Seat Fanpai/Yakuhai") if meld.value() == gameDataFlags.roundWind.toLowerCase() yakuModifiers.push("Prevailing Fanpai/Yakuhai") #Chanta - All sets contain terminals or honours, there are both terminals and honors in the hand, the pair is terminals or honours, and the hand contains at least one chow. if chowList.length > 0 && _.every(melds, _meldContainsAtLeastOneTerminalOrHonor) && _.some(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Honor") if(isConcealedHand) yakuModifiers.push("Concealed Chanta") else yakuModifiers.push("Chanta") #PI:NAME:<NAME>END_PI - Little Three Dragons, two pungs/kongs and a pair of Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 2) if((suit for suit in suitList when suit == "dragon").length == 3) yakuModifiers.push("Shou Sangen") #Honroutou - All Terminals and Honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.xor(suitList,["dragon","wind"]).length > 0) if (meld for meld in melds when (meld.suit() in ["dragon","wind"] || meld.value() in [1,9])).length == melds.length yakuModifiers.push("Honroutou") #Junchan - Terminals in All Sets, but at least one Chow if(chowList.length > 0 && _.every(melds, (x)-> _meldContainsAtLeastOneTerminalOrHonor(x) == "Terminal")) if(isConcealedHand) yakuModifiers.push("Concealed Junchan") else yakuModifiers.push("Junchan") #Honitsu - Half Flush - One suit plus honors if(_.intersection(suitList,["dragon","wind"]).length > 0 && _.uniq(_.difference(suitList,["dragon","wind"])).length == 1) if(isConcealedHand) yakuModifiers.push("Concealed Honitsu") else yakuModifiers.push("Honitsu") #Chinitsu - Full Flush - One Suit, no honors if(_.uniq(suitList).length == 1 and suitList[0] not in ["dragon", "wind"]) if(isConcealedHand) yakuModifiers.push("Concealed Chinitsu") else yakuModifiers.push("Chinitsu") #Yakuman if(isConcealedHand) #PI:NAME:<NAME>END_PI - 13 Orphans if(melds in ["thirteenorphans","thirteenorphans+"]) yakuModifiers.push("Kokushi Musou") #PI:NAME:<NAME>END_PI - Nine Gates if("Concealed Chinitsu" in yakuModifiers) if(kongList.length == 0) valuePattern = _.flattenDeep((meld.tiles for meld in melds)) valuePattern = _.map(valuePattern, (x) -> x.value) stringPattern = _.join(valuePattern, "") if stringPattern in ["11112345678999","11122345678999","11123345678999","11123445678999","11123455678999","11123456678999","11123456778999","11123456788999","11123456789999"] yakuModifiers.push("Chuuren Pooto") #Tenho - Blessing of Heaven, mahjong on starting hand if(gameDataFlags.tenho) yakuModifiers.push("Tenho") #Chiho - Blessing of Earth, mahjong on first draw if(gameDataFlags.chiho) yakuModifiers.push("Chiho") #Suu Ankou - Four Concealed Pungs if(concealedPungs == 4) yakuModifiers.push("Suu Ankou") #Suu Kan Tsu - Four Kongs if(kongList.length == 4) yakuModifiers.push("Suu Kan Tsu") #Ryuu Iisou - All Green if(_.every(melds,_meldIsGreen)) yakuModifiers.push("Ryuu Iisou") #Chinrouto - All Terminals if(_.every(melds,(x) -> x.value() in [1,9])) yakuModifiers.push("Chinrouto") #Tsuu Iisou - All Honors if(_.every(melds,(x) -> x.suit() in ["dragon", "wind"])) yakuModifiers.push("Tsuu Iisou") #Dai Sangan - Big Three Dragons if((pung for pung in pungList when pung.suit()=="dragon").length == 3) yakuModifiers.push("Dai Sangen") #Shou Suushii - Little Four Winds if((suit for suit in suitList when suit == "wind").length == 4) if((pung for pung in pungList when pung.suit() == "wind").length == 3) yakuModifiers.push("Shou Suushii") #Dai Suushii - Big Four Winds if((pung for pung in pungList when pung.suit() == "wind").length == 4) yakuModifiers.push("Dai Suushii") return({yaku:yakuModifiers,fu:fu,flags:gameDataFlags,selfDraw:selfDraw}) _meldContainsAtLeastOneTerminalOrHonor = (meld) -> for tile in meld.tiles if tile.isHonor() return "Honor" else if tile.isTerminal() return "Terminal" return false _meldIsGreen = (meld) -> for tile in meld.tiles if !tile.isGreen() return false return true _meldContainsOnlyGivenTile = (meld, givenTile) -> allSameTile = true for tile in meld.tiles if tile != givenTile allSameTile = false break return allSameTile _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore _roundUpToClosestTen = (inScore) -> if (inScore%10)!=0 return (inScore//10+1)*10 else inScore _calculateFu = (melds, selfDraw, gameDataFlags) -> isConcealedHand = true for meld in melds if(!meld.lastDrawnTile && meld.takenFrom != "self") isConcealedHand = false baseFu = 0 if(melds.length == 7) baseFu = 25 else if(isConcealedHand && !selfDraw) baseFu = 30 else baseFu = 20 meldFu = 0 if(melds.length != 7) for meld in melds if(meld.type == "Pung") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 8 else meldFu += 4 else if(meld.takenFrom == "self") meldFu += 4 else meldFu += 2 if(meld.type == "Kong") if(meld.suit() in ["dragon","wind"] || meld.value() in [1,9]) if(meld.takenFrom == "self") meldFu += 32 else meldFu += 16 else if(meld.takenFrom == "self") meldFu += 16 else meldFu += 8 if(meld.type == "Pair") if(meld.suit() == "dragon") meldFu += 2 else if(meld.suit() == "wind") if(meld.value() == gameDataFlags.playerWind) meldFu += 2 if(meld.value() == gameDataFlags.roundWind) meldFu += 2 if(meld.lastDrawnTile) meldFu += 2 if(meld.type == "Chow") if(meld.lastDrawnTile) if(meld.lastDrawnTile.value*3 == meld.tiles[0].value+meld.tiles[1].value+meld.tiles[2].value) meldFu += 2 if(meld.value() == "1 - 2 - 3" && meld.lastDrawnTile.value == 3) meldFu += 2 if(meld.value() == "7 - 8 - 9" && meld.lastDrawnTile.value == 7) meldFu += 2 if(!(meldFu == 0 && isConcealedHand) && selfDraw) meldFu += 2 if(meldFu == 0 && !isConcealedHand) meldFu += 2 fu = baseFu + meldFu #console.log(fu) if(fu != 25) fu = _roundUpToClosestTen(fu) return [fu, meldFu] getScore = (values, dora, urDora) -> if(values.yaku.length == 0) return([0,["No Yaku"]]) #Score the yakuModifiers list yakuman = false yakuPoints = 0 printedYaku = [] for yaku in values.yaku #testing if(yaku not of yakuList) console.log(yaku) else if(yakuList[yaku].score == "Y") yakuman = true else if(yaku != "Renho") yakuPoints += yakuList[yaku].score if(yakuman) printedYaku = (yaku for yaku in values.yaku when yakuList[yaku].score == "Y") else if("Renho" in values.yaku) if(yakuPoints > 0 && yakuPoints + dora > 5) printedYaku = (yaku for yaku in values.yaku when yaku != "Renho") fan = yakuPoints + dora + urDora else printedYaku = ["Renho"] fan = 5 else printedYaku = values.yaku fan = yakuPoints + dora + urDora if "Renho" not in printedYaku && !yakuman if dora > 0 printedYaku.push("Dora: #{dora}") if urDora > 0 printedYaku.push("Ur Dora: #{urDora}") #Gives Base Score if yakuman baseScore = 8000 else if fan >= 5 if(fan == 5) baseScore = 2000 else if(fan <= 7) baseScore = 3000 else if(fan <= 10) baseScore = 4000 else baseScore = 5000 else #console.log(values.fu) baseScore = values.fu * Math.pow(2,2+fan) if baseScore > 2000 baseScore = 2000 return [baseScore,printedYaku] module.exports.scoreMahjongHand = scoreMahjongHand module.exports.getPossibleHands = getPossibleHands module.exports.gameFlags = gameFlags module.exports.tenpaiWith = tenpaiWith module.exports.tenpaiWithout = tenpaiWithout module.exports.thirteenOrphans = thirteenOrphans module.exports.yakuList = yakuList
[ { "context": "{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};'\nCONNECTION_ST", "end": 431, "score": 0.7481077313423157, "start": 421, "tag": "PASSWORD", "value": "#{password" }, { "context": "tance}};Database={#{database}};Uid={#{user}...
node_modules/sails-sqlserver/node_modules/mssql/src/msnodesql.coffee
siaomingjeng/konga-test
0
{Pool} = require 'generic-pool' msnodesql = require 'msnodesql' util = require 'util' {TYPES, declare} = require('./datatypes') UDT = require('./udt').PARSERS ISOLATION_LEVEL = require('./isolationlevel') DECLARATIONS = require('./datatypes').DECLARATIONS EMPTY_BUFFER = new Buffer(0) CONNECTION_STRING_PORT = 'Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};' CONNECTION_STRING_NAMED_INSTANCE = 'Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};' ### @ignore ### castParameter = (value, type) -> unless value? if type is TYPES.Binary or type is TYPES.VarBinary or type is TYPES.Image # msnodesql has some problems with NULL values in those types, so we need to replace it with empty buffer return EMPTY_BUFFER return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.size type: DECLARATIONS[column.sqlType] if column.udtType? out[column.name].udt = name: column.udtType if DECLARATIONS[column.udtType] out[column.name].type = DECLARATIONS[column.udtType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### @ignore ### valueCorrection = (value, metadata) -> if metadata.sqlType is 'time' and value? value.setFullYear(1970) value else if metadata.sqlType is 'udt' and value? if UDT[metadata.udtType] UDT[metadata.udtType] value else value else value ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class MsnodesqlConnection extends Connection pool: null connect: (config, callback) -> defaultConnectionString = CONNECTION_STRING_PORT if config.options.instanceName? defaultConnectionString = CONNECTION_STRING_NAMED_INSTANCE cfg = connectionString: config.connectionString ? defaultConnectionString cfg.connectionString = cfg.connectionString.replace new RegExp('#{([^}]*)}', 'g'), (p) -> key = p.substr(2, p.length - 3) if key is 'instance' return config.options.instanceName else if key is 'trusted' return if config.options.trustedConnection then 'Yes' else 'No' else return config[key] ? '' cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => msnodesql.open cfg.connectionString, (err, c) => if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? destroy: (c) -> c?.close() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class MsnodesqlTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)};begin tran;", callback commit: (callback) -> @request().query 'commit tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @request().query 'rollback tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class MsnodesqlRequest extends Request batch: (batch, callback) -> MsnodesqlRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null row = null columns = null recordset = null recordsets = [] started = Date.now() handleOutput = false # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters) sets = ("set @#{param.name}=?" for name, param of @parameters when param.io is 1) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{sets.join ';'};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err req = connection.queryRaw command, (castParameter(param.value, param.type) for name, param of @parameters when param.io is 1) if @verbose and not @nested then @_log "---------- response -----------" req.on 'meta', (metadata) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = null columns = metadata recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata) if @stream unless recordset.columns["___return___"]? @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'row', (rownumber) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = {} unless @stream recordset.push row req.on 'column', (idx, data, more) => data = valueCorrection(data, columns[idx]) exi = row[columns[idx].name] if exi? if exi instanceof Array exi.push data else row[columns[idx].name] = [exi, data] else row[columns[idx].name] = data req.once 'error', (err) => e = RequestError err if (/^\[Microsoft\]\[SQL Server Native Client 11\.0\]\[SQL Server\](.*)$/).exec err.message e.message = RegExp.$1 e.number = err.code e.code = 'EREQUEST' if @verbose and not @nested elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection callback? e req.once 'done', => unless @nested if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection if @stream callback null, if @nested then row else null else callback? null, if @multiple or @nested then recordsets else recordsets[0] else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=?" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) MsnodesqlRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> false # Request canceling is not implemented by msnodesql driver. return { Connection: MsnodesqlConnection Transaction: MsnodesqlTransaction Request: MsnodesqlRequest fix: -> # there is nothing to fix in this driver }
34246
{Pool} = require 'generic-pool' msnodesql = require 'msnodesql' util = require 'util' {TYPES, declare} = require('./datatypes') UDT = require('./udt').PARSERS ISOLATION_LEVEL = require('./isolationlevel') DECLARATIONS = require('./datatypes').DECLARATIONS EMPTY_BUFFER = new Buffer(0) CONNECTION_STRING_PORT = 'Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={<PASSWORD>}};Trusted_Connection={#{trusted}};' CONNECTION_STRING_NAMED_INSTANCE = 'Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={<PASSWORD>}};Trusted_Connection={#{trusted}};' ### @ignore ### castParameter = (value, type) -> unless value? if type is TYPES.Binary or type is TYPES.VarBinary or type is TYPES.Image # msnodesql has some problems with NULL values in those types, so we need to replace it with empty buffer return EMPTY_BUFFER return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.size type: DECLARATIONS[column.sqlType] if column.udtType? out[column.name].udt = name: column.udtType if DECLARATIONS[column.udtType] out[column.name].type = DECLARATIONS[column.udtType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### @ignore ### valueCorrection = (value, metadata) -> if metadata.sqlType is 'time' and value? value.setFullYear(1970) value else if metadata.sqlType is 'udt' and value? if UDT[metadata.udtType] UDT[metadata.udtType] value else value else value ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class MsnodesqlConnection extends Connection pool: null connect: (config, callback) -> defaultConnectionString = CONNECTION_STRING_PORT if config.options.instanceName? defaultConnectionString = CONNECTION_STRING_NAMED_INSTANCE cfg = connectionString: config.connectionString ? defaultConnectionString cfg.connectionString = cfg.connectionString.replace new RegExp('#{([^}]*)}', 'g'), (p) -> key = p.substr(2, p.length - 3) if key is 'instance' return config.options.instanceName else if key is 'trusted' return if config.options.trustedConnection then 'Yes' else 'No' else return config[key] ? '' cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => msnodesql.open cfg.connectionString, (err, c) => if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? destroy: (c) -> c?.close() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class MsnodesqlTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)};begin tran;", callback commit: (callback) -> @request().query 'commit tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @request().query 'rollback tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class MsnodesqlRequest extends Request batch: (batch, callback) -> MsnodesqlRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null row = null columns = null recordset = null recordsets = [] started = Date.now() handleOutput = false # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters) sets = ("set @#{param.name}=?" for name, param of @parameters when param.io is 1) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{sets.join ';'};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err req = connection.queryRaw command, (castParameter(param.value, param.type) for name, param of @parameters when param.io is 1) if @verbose and not @nested then @_log "---------- response -----------" req.on 'meta', (metadata) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = null columns = metadata recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata) if @stream unless recordset.columns["___return___"]? @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'row', (rownumber) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = {} unless @stream recordset.push row req.on 'column', (idx, data, more) => data = valueCorrection(data, columns[idx]) exi = row[columns[idx].name] if exi? if exi instanceof Array exi.push data else row[columns[idx].name] = [exi, data] else row[columns[idx].name] = data req.once 'error', (err) => e = RequestError err if (/^\[Microsoft\]\[SQL Server Native Client 11\.0\]\[SQL Server\](.*)$/).exec err.message e.message = RegExp.$1 e.number = err.code e.code = 'EREQUEST' if @verbose and not @nested elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection callback? e req.once 'done', => unless @nested if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection if @stream callback null, if @nested then row else null else callback? null, if @multiple or @nested then recordsets else recordsets[0] else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=?" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) MsnodesqlRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> false # Request canceling is not implemented by msnodesql driver. return { Connection: MsnodesqlConnection Transaction: MsnodesqlTransaction Request: MsnodesqlRequest fix: -> # there is nothing to fix in this driver }
true
{Pool} = require 'generic-pool' msnodesql = require 'msnodesql' util = require 'util' {TYPES, declare} = require('./datatypes') UDT = require('./udt').PARSERS ISOLATION_LEVEL = require('./isolationlevel') DECLARATIONS = require('./datatypes').DECLARATIONS EMPTY_BUFFER = new Buffer(0) CONNECTION_STRING_PORT = 'Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={PI:PASSWORD:<PASSWORD>END_PI}};Trusted_Connection={#{trusted}};' CONNECTION_STRING_NAMED_INSTANCE = 'Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={PI:PASSWORD:<PASSWORD>END_PI}};Trusted_Connection={#{trusted}};' ### @ignore ### castParameter = (value, type) -> unless value? if type is TYPES.Binary or type is TYPES.VarBinary or type is TYPES.Image # msnodesql has some problems with NULL values in those types, so we need to replace it with empty buffer return EMPTY_BUFFER return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.size type: DECLARATIONS[column.sqlType] if column.udtType? out[column.name].udt = name: column.udtType if DECLARATIONS[column.udtType] out[column.name].type = DECLARATIONS[column.udtType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### @ignore ### valueCorrection = (value, metadata) -> if metadata.sqlType is 'time' and value? value.setFullYear(1970) value else if metadata.sqlType is 'udt' and value? if UDT[metadata.udtType] UDT[metadata.udtType] value else value else value ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class MsnodesqlConnection extends Connection pool: null connect: (config, callback) -> defaultConnectionString = CONNECTION_STRING_PORT if config.options.instanceName? defaultConnectionString = CONNECTION_STRING_NAMED_INSTANCE cfg = connectionString: config.connectionString ? defaultConnectionString cfg.connectionString = cfg.connectionString.replace new RegExp('#{([^}]*)}', 'g'), (p) -> key = p.substr(2, p.length - 3) if key is 'instance' return config.options.instanceName else if key is 'trusted' return if config.options.trustedConnection then 'Yes' else 'No' else return config[key] ? '' cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => msnodesql.open cfg.connectionString, (err, c) => if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? destroy: (c) -> c?.close() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class MsnodesqlTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)};begin tran;", callback commit: (callback) -> @request().query 'commit tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @request().query 'rollback tran', (err) => @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class MsnodesqlRequest extends Request batch: (batch, callback) -> MsnodesqlRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null row = null columns = null recordset = null recordsets = [] started = Date.now() handleOutput = false # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters) sets = ("set @#{param.name}=?" for name, param of @parameters when param.io is 1) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{sets.join ';'};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err req = connection.queryRaw command, (castParameter(param.value, param.type) for name, param of @parameters when param.io is 1) if @verbose and not @nested then @_log "---------- response -----------" req.on 'meta', (metadata) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = null columns = metadata recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata) if @stream unless recordset.columns["___return___"]? @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'row', (rownumber) => if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row row = {} unless @stream recordset.push row req.on 'column', (idx, data, more) => data = valueCorrection(data, columns[idx]) exi = row[columns[idx].name] if exi? if exi instanceof Array exi.push data else row[columns[idx].name] = [exi, data] else row[columns[idx].name] = data req.once 'error', (err) => e = RequestError err if (/^\[Microsoft\]\[SQL Server Native Client 11\.0\]\[SQL Server\](.*)$/).exec err.message e.message = RegExp.$1 e.number = err.code e.code = 'EREQUEST' if @verbose and not @nested elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection callback? e req.once 'done', => unless @nested if row if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" @_release connection if @stream callback null, if @nested then row else null else callback? null, if @multiple or @nested then recordsets else recordsets[0] else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=?" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) MsnodesqlRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> false # Request canceling is not implemented by msnodesql driver. return { Connection: MsnodesqlConnection Transaction: MsnodesqlTransaction Request: MsnodesqlRequest fix: -> # there is nothing to fix in this driver }
[ { "context": "t\n model: models.a\n event: \"sample@chain.chain\"\n handler: -> ok(true, \"got sample@cha", "end": 6251, "score": 0.9968719482421875, "start": 6233, "tag": "EMAIL", "value": "sample@chain.chain" }, { "context": "chain.chain\"\n ...
test/chaining.coffee
ronen/backbone-chaining
1
$(document).ready -> unless window.console window.console = {} names = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd' ] for name in names window.console[name] = -> window.models = models = {} collections = {} noEvents = (other) -> ok(_.all(_.compact _.flatten([models, collections, other]), (sender) -> return false if sender._eventChains return false unless _.isEmpty(_.omit(sender._events, 'all')) # ignore 'all' events, created by collection true ), "all events and chains removed") testEvent = (options) -> options.model.on options.event, options.handler, options.context options.trigger() if options.update options.update() options.trigger() options.model.off options.event noEvents() QUnit.module "Backbone.Chaining", setup: -> models.a = new Backbone.Model name: "a" models.b = new Backbone.Model name: "b" models.c = new Backbone.Model name: "c" models.item0 = new Backbone.Model name: "item0" models.item1 = new Backbone.Model name: "item1" models.sub0 = new Backbone.Model name: "sub0" models.sub1 = new Backbone.Model name: "sub1" models.agent = new Backbone.Model name: "agent" collections.p = new Backbone.Collection [models.item0, models.item1] models.a.set 'chain', models.b models.b.set 'chain', models.c models.item0.set 'sub', models.sub0 models.item1.set 'sub', models.sub1 models.a.set 'coll', collections.p QUnit.test "get with null attribute", -> equal models.a.get(null), null QUnit.test "get without chain", 1, -> equal models.a.get('name'), 'a' QUnit.test "get malformed chain -- missing tail", 1, -> throws (-> models.a.get 'chain.'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced left bracket", 1, -> throws (-> models.a.get 'chain]here'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced bracket", 1, -> throws (-> models.a.get 'chain[here'), /malformed chain/ QUnit.test "get malformed chain -- missing dot", 1, -> throws (-> models.a.get 'chain[2]x'), /malformed chain/ QUnit.test "get malformed chain -- missing tail after bracket", 1, -> throws (-> models.a.get 'chain[2].'), /malformed chain/ QUnit.test "get single chain", 1, -> equal models.a.get('chain.name'), 'b' QUnit.test "get double chain", 1, -> equal models.a.get('chain.chain.name'), 'c' QUnit.test "get chain with collection index", 3, -> equal models.a.get('coll[0]'), models.item0, "index 0" equal models.a.get('coll[1]'), models.item1, "index 1" equal models.a.get('coll[#]'), models.item1, "index 1" QUnit.test "get chain with collection index chain", 3, -> equal models.a.get('coll[0].sub.name'), 'sub0', "index 0" equal models.a.get('coll[1].sub.name'), 'sub1', "index 1" equal models.a.get('coll[#].sub.name'), 'sub1', "index 1" QUnit.test "get chain with collection star", 1, -> deepEqual models.a.get('coll[*]'), [models.item0, models.item1] QUnit.test "get chain with collection star chained", 1, -> deepEqual models.a.get('coll[*].sub.name'), ['sub0', 'sub1'] QUnit.test "get broken single chain", 1, -> models.a.set 'chain', null equal models.a.get('chain.name'), undefined QUnit.test "get broken double chain", 1, -> models.b.set 'chain', null equal models.a.get('chain.chain.name'), undefined QUnit.test "get broken collection index chain", 1, -> models.a.set 'coll', null equal models.a.get('coll[0].sub.name'), undefined QUnit.test "get invalid collection index chain", 1, -> equal models.a.get('coll[2].sub.name'), undefined QUnit.test "set without chain", 1, -> models.a.set 'attr', 'val' equal models.a.get('attr'), 'val' QUnit.test "set malformed chain -- no attribute", 1, -> throws (-> models.a.set 'chain.', 'val'), /malformed chain/ QUnit.test "set single chain", 1, -> models.a.set 'chain.attr', 'val' equal models.b.get('attr'), 'val' QUnit.test "set double chain", 1, -> models.a.set 'chain.chain.attr', 'val' equal models.c.get('attr'), 'val' QUnit.test "set chain with collection index", 1, -> models.a.set 'coll[0].sub.attr', 'val' equal models.sub0.get('attr'), 'val' QUnit.test "set chain with collection last index", 1, -> models.a.set 'coll[#].sub.attr', 'val' equal models.sub1.get('attr'), 'val' QUnit.test "set chain with collection star", 2, -> models.a.set 'coll[*].sub.attr', 'val' equal models.sub0.get('attr'), 'val' equal models.sub1.get('attr'), 'val' QUnit.test "event malformed chain -- missing attr", 1, -> throws (-> models.a.on "name@"), /malformed chain/ QUnit.test "event malformed chain -- too many atsigns", 1, -> throws (-> models.a.on "name@here@there"), /malformed chain/ QUnit.test "event without chain", 2, -> testEvent model: models.a event: "sample" handler: -> ok(true, "got sample") trigger: -> models.a.trigger "sample" QUnit.test "event chain", 3, -> testEvent model: models.a event: "sample@chain" handler: -> ok(true, "got sample@chain") equal @, models.a trigger: -> models.b.trigger "sample" QUnit.test "event chain context", 2, -> testEvent model: models.a context: {ctx: "test"} event: "sample@chain" handler: -> equal @ctx, "test" trigger: -> models.b.trigger "sample" QUnit.test "event double chain", 2, -> testEvent model: models.a event: "sample@chain.chain" handler: -> ok(true, "got sample@chain@chain") trigger: -> models.c.trigger "sample" QUnit.test "mix chains and nonchain", 4, -> testEvent model: models.a event: "nonchain single@chain double@chain.chain" handler: -> ok(true, "got event") trigger: -> models.a.trigger "nonchain" models.b.trigger "single" models.c.trigger "double" QUnit.test "event map", 7, -> testEvent model: models.a event: nonchain: -> ok(true, "got nonchain event") "single@chain": -> ok(true, "got single event") "double@chain.chain": -> ok(true, "got double event") "nonchain-mixed single-mixed@chain double-mixed@chain.chain": -> ok(true, "got mixed event") trigger: -> models.a.trigger "nonchain" models.a.trigger "nonchain-mixed" models.b.trigger "single" models.b.trigger "single-mixed" models.c.trigger "double" models.c.trigger "double-mixed" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[0].sub" handler: (val) -> equal(val, "yes", "got sample@coll[0].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "no" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[#].sub" handler: (val) -> equal(val, "yes", "got sample@coll[#].sub") trigger: -> models.sub0.trigger "sample", "no" models.sub1.trigger "sample", "yes" QUnit.test "event chain with collection star", 3, -> testEvent model: models.a event: "sample@coll[*].sub" handler: (val) -> equal(val, "yes", "got sample@coll[*].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "yes" QUnit.test "event pass-through collection", 3, -> container = new Backbone.Collection [models.a] testEvent model: container event: "add@coll" handler: -> ok(true, "got add@coll") equal @, container, "context" trigger: -> models.a.get('coll').add new Backbone.Model name: "added" QUnit.test "change event chain", 4, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change@chain" handler: (model, options) -> equal model, models.b equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event chain", 5, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain" handler: (model, value, options) -> equal model, models.b equal value, 'new' equal model.previous('attr'), 'previous' equal model.get('attr'), 'new' trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "update event chain -- break chain", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> models.item0.set 'sub', null trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- remove from collection", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> collections.p.remove(models.item0) trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- make chain: add field", 1, -> models.a.on "sample@coll[*].sub.extra.chain", -> ok(true, "got sample@coll[*].sub.extra.chain") models.sub1.set 'extra', models.b models.c.trigger "sample" QUnit.test "update event chain -- make chain: add element", 1, -> models.a.on "sample@coll[2].sub", -> ok(true, "got sample@coll[*].sub.extra.chain") sub2 = new Backbone.Model name: "sub2" collections.p.add new Backbone.Model name: "item2", sub: sub2 sub2.trigger "sample" QUnit.test "update event chain -- change root", 2, -> newTail = new Backbone.Model name: "newTail" newHead = new Backbone.Model name: "newHead", chain: newTail models.a.on "sample@chain.chain", (expected) -> equal expected, 'yes' models.b.trigger "sample", "no" models.c.trigger "sample", "yes" newHead.trigger "sample", "no" newTail.trigger "sample", "no" models.b.trigger "sample", "no" models.a.set "chain", newHead models.c.trigger "sample", "no" newHead.trigger "sample", "no" newTail.trigger "sample", "yes" QUnit.test "remove chain -- event name", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "event1@chain", cb models.a.on "event2@chain", cb models.b.trigger "event1", "yes" models.b.trigger "event2", "yes" models.a.off "event1@chain" models.b.trigger "event1", "no" models.b.trigger "event2", "yes" QUnit.test "remove chain -- attr", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "sample@chain", cb models.a.on "sample@coll", cb models.b.trigger "sample", "yes" collections.p.trigger "sample", "yes" models.a.off "sample@chain" models.b.trigger "sample", "no" collections.p.trigger "sample", "yes" QUnit.test "remove chain -- callback", 3, -> cb1 = (expected) -> ok(true) cb2ok = true cb2 = (expected) -> ok(cb2ok) models.a.on "sample@chain", cb1 models.a.on "sample@chain", cb2 models.b.trigger "sample" # both callbacks models.a.off null, cb2 cb2ok = false models.b.trigger "sample" # only cb1 QUnit.test "remove chain -- context", 3, -> ctx1 = { ok: true } ctx2 = { ok: true} cb = -> ok @ok models.a.on "sample@chain", cb, ctx1 models.a.on "sample@chain", cb, ctx2 models.b.trigger "sample" # both callbacks models.a.off null, null, ctx2 ctx2.ok = false models.b.trigger "sample" # only ctx1 callback listenToChain = (listener, events=["sample"]) -> chainedEvents = _.map(events, (evt) -> "#{evt}@chain.chain").join(' ') listener.listenTo models.a, chainedEvents, -> ok(true, "got sample@chain.chain") _.each events, (evt) -> models.c.trigger evt listener.stopListening() noEvents(listener) QUnit.test "listenTo chain", 2, -> listenToChain models.item0 QUnit.test "listenTo multiple events", 4, -> listenToChain models.item0, ["first", "second", "third"] QUnit.test "backbone listenTo chain", 2, -> listenToChain Backbone QUnit.test "generic listener listenTo", 2, -> listenToChain new class _.extend @::, Backbone.Events _.each { model: Backbone.Model collection: Backbone.Collection view: Backbone.View router: Backbone.Router history: Backbone.History }, (klass, name) -> QUnit.test "#{name} listenTo chain", 2, -> listenToChain new klass QUnit.test "listenTo chain stopListening to model", 2, -> models.agent.listenTo models.a, "sample@chain.chain", -> ok(true, "got sample@chain.chain") models.c.trigger "sample" # handled models.agent.stopListening models.a models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain, stopListening to event", 2, -> models.agent.listenTo models.a, "sample@chain.chain", -> ok(true, "got sample@chain.chain") models.c.trigger "sample" # handled models.agent.stopListening models.a, "sample@chain.chain" models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain stopListening to other event", 3, -> models.agent.listenTo models.a, "sample@chain.chain", -> ok(true, "got sample@chain.chain") models.c.trigger "sample" # handled models.agent.stopListening models.a, "other@chain.chain" models.c.trigger "sample" # handled models.agent.stopListening() noEvents()
75779
$(document).ready -> unless window.console window.console = {} names = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd' ] for name in names window.console[name] = -> window.models = models = {} collections = {} noEvents = (other) -> ok(_.all(_.compact _.flatten([models, collections, other]), (sender) -> return false if sender._eventChains return false unless _.isEmpty(_.omit(sender._events, 'all')) # ignore 'all' events, created by collection true ), "all events and chains removed") testEvent = (options) -> options.model.on options.event, options.handler, options.context options.trigger() if options.update options.update() options.trigger() options.model.off options.event noEvents() QUnit.module "Backbone.Chaining", setup: -> models.a = new Backbone.Model name: "a" models.b = new Backbone.Model name: "b" models.c = new Backbone.Model name: "c" models.item0 = new Backbone.Model name: "item0" models.item1 = new Backbone.Model name: "item1" models.sub0 = new Backbone.Model name: "sub0" models.sub1 = new Backbone.Model name: "sub1" models.agent = new Backbone.Model name: "agent" collections.p = new Backbone.Collection [models.item0, models.item1] models.a.set 'chain', models.b models.b.set 'chain', models.c models.item0.set 'sub', models.sub0 models.item1.set 'sub', models.sub1 models.a.set 'coll', collections.p QUnit.test "get with null attribute", -> equal models.a.get(null), null QUnit.test "get without chain", 1, -> equal models.a.get('name'), 'a' QUnit.test "get malformed chain -- missing tail", 1, -> throws (-> models.a.get 'chain.'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced left bracket", 1, -> throws (-> models.a.get 'chain]here'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced bracket", 1, -> throws (-> models.a.get 'chain[here'), /malformed chain/ QUnit.test "get malformed chain -- missing dot", 1, -> throws (-> models.a.get 'chain[2]x'), /malformed chain/ QUnit.test "get malformed chain -- missing tail after bracket", 1, -> throws (-> models.a.get 'chain[2].'), /malformed chain/ QUnit.test "get single chain", 1, -> equal models.a.get('chain.name'), 'b' QUnit.test "get double chain", 1, -> equal models.a.get('chain.chain.name'), 'c' QUnit.test "get chain with collection index", 3, -> equal models.a.get('coll[0]'), models.item0, "index 0" equal models.a.get('coll[1]'), models.item1, "index 1" equal models.a.get('coll[#]'), models.item1, "index 1" QUnit.test "get chain with collection index chain", 3, -> equal models.a.get('coll[0].sub.name'), 'sub0', "index 0" equal models.a.get('coll[1].sub.name'), 'sub1', "index 1" equal models.a.get('coll[#].sub.name'), 'sub1', "index 1" QUnit.test "get chain with collection star", 1, -> deepEqual models.a.get('coll[*]'), [models.item0, models.item1] QUnit.test "get chain with collection star chained", 1, -> deepEqual models.a.get('coll[*].sub.name'), ['sub0', 'sub1'] QUnit.test "get broken single chain", 1, -> models.a.set 'chain', null equal models.a.get('chain.name'), undefined QUnit.test "get broken double chain", 1, -> models.b.set 'chain', null equal models.a.get('chain.chain.name'), undefined QUnit.test "get broken collection index chain", 1, -> models.a.set 'coll', null equal models.a.get('coll[0].sub.name'), undefined QUnit.test "get invalid collection index chain", 1, -> equal models.a.get('coll[2].sub.name'), undefined QUnit.test "set without chain", 1, -> models.a.set 'attr', 'val' equal models.a.get('attr'), 'val' QUnit.test "set malformed chain -- no attribute", 1, -> throws (-> models.a.set 'chain.', 'val'), /malformed chain/ QUnit.test "set single chain", 1, -> models.a.set 'chain.attr', 'val' equal models.b.get('attr'), 'val' QUnit.test "set double chain", 1, -> models.a.set 'chain.chain.attr', 'val' equal models.c.get('attr'), 'val' QUnit.test "set chain with collection index", 1, -> models.a.set 'coll[0].sub.attr', 'val' equal models.sub0.get('attr'), 'val' QUnit.test "set chain with collection last index", 1, -> models.a.set 'coll[#].sub.attr', 'val' equal models.sub1.get('attr'), 'val' QUnit.test "set chain with collection star", 2, -> models.a.set 'coll[*].sub.attr', 'val' equal models.sub0.get('attr'), 'val' equal models.sub1.get('attr'), 'val' QUnit.test "event malformed chain -- missing attr", 1, -> throws (-> models.a.on "name@"), /malformed chain/ QUnit.test "event malformed chain -- too many atsigns", 1, -> throws (-> models.a.on "name@here@there"), /malformed chain/ QUnit.test "event without chain", 2, -> testEvent model: models.a event: "sample" handler: -> ok(true, "got sample") trigger: -> models.a.trigger "sample" QUnit.test "event chain", 3, -> testEvent model: models.a event: "sample@chain" handler: -> ok(true, "got sample@chain") equal @, models.a trigger: -> models.b.trigger "sample" QUnit.test "event chain context", 2, -> testEvent model: models.a context: {ctx: "test"} event: "sample@chain" handler: -> equal @ctx, "test" trigger: -> models.b.trigger "sample" QUnit.test "event double chain", 2, -> testEvent model: models.a event: "<EMAIL>" handler: -> ok(true, "got <EMAIL>") trigger: -> models.c.trigger "sample" QUnit.test "mix chains and nonchain", 4, -> testEvent model: models.a event: "nonchain single@chain <EMAIL>" handler: -> ok(true, "got event") trigger: -> models.a.trigger "nonchain" models.b.trigger "single" models.c.trigger "double" QUnit.test "event map", 7, -> testEvent model: models.a event: nonchain: -> ok(true, "got nonchain event") "single@chain": -> ok(true, "got single event") "<EMAIL>": -> ok(true, "got double event") "nonchain-mixed <EMAIL>-<EMAIL>@<EMAIL> <EMAIL>": -> ok(true, "got mixed event") trigger: -> models.a.trigger "nonchain" models.a.trigger "nonchain-mixed" models.b.trigger "single" models.b.trigger "single-mixed" models.c.trigger "double" models.c.trigger "double-mixed" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[0].sub" handler: (val) -> equal(val, "yes", "got sample@coll[0].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "no" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[#].sub" handler: (val) -> equal(val, "yes", "got sample@coll[#].sub") trigger: -> models.sub0.trigger "sample", "no" models.sub1.trigger "sample", "yes" QUnit.test "event chain with collection star", 3, -> testEvent model: models.a event: "sample@coll[*].sub" handler: (val) -> equal(val, "yes", "got sample@coll[*].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "yes" QUnit.test "event pass-through collection", 3, -> container = new Backbone.Collection [models.a] testEvent model: container event: "add@coll" handler: -> ok(true, "got add@coll") equal @, container, "context" trigger: -> models.a.get('coll').add new Backbone.Model name: "added" QUnit.test "change event chain", 4, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change@chain" handler: (model, options) -> equal model, models.b equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event chain", 5, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain" handler: (model, value, options) -> equal model, models.b equal value, 'new' equal model.previous('attr'), 'previous' equal model.get('attr'), 'new' trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "update event chain -- break chain", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> models.item0.set 'sub', null trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- remove from collection", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> collections.p.remove(models.item0) trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- make chain: add field", 1, -> models.a.on "sample@coll[*].sub.extra.chain", -> ok(true, "got sample@coll[*].sub.extra.chain") models.sub1.set 'extra', models.b models.c.trigger "sample" QUnit.test "update event chain -- make chain: add element", 1, -> models.a.on "sample@coll[2].sub", -> ok(true, "got sample@coll[*].sub.extra.chain") sub2 = new Backbone.Model name: "sub2" collections.p.add new Backbone.Model name: "item2", sub: sub2 sub2.trigger "sample" QUnit.test "update event chain -- change root", 2, -> newTail = new Backbone.Model name: "newTail" newHead = new Backbone.Model name: "newHead", chain: newTail models.a.on "<EMAIL>", (expected) -> equal expected, 'yes' models.b.trigger "sample", "no" models.c.trigger "sample", "yes" newHead.trigger "sample", "no" newTail.trigger "sample", "no" models.b.trigger "sample", "no" models.a.set "chain", newHead models.c.trigger "sample", "no" newHead.trigger "sample", "no" newTail.trigger "sample", "yes" QUnit.test "remove chain -- event name", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "event1@chain", cb models.a.on "event2@chain", cb models.b.trigger "event1", "yes" models.b.trigger "event2", "yes" models.a.off "event1@chain" models.b.trigger "event1", "no" models.b.trigger "event2", "yes" QUnit.test "remove chain -- attr", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "sample@chain", cb models.a.on "sample@coll", cb models.b.trigger "sample", "yes" collections.p.trigger "sample", "yes" models.a.off "sample@chain" models.b.trigger "sample", "no" collections.p.trigger "sample", "yes" QUnit.test "remove chain -- callback", 3, -> cb1 = (expected) -> ok(true) cb2ok = true cb2 = (expected) -> ok(cb2ok) models.a.on "sample@chain", cb1 models.a.on "sample@chain", cb2 models.b.trigger "sample" # both callbacks models.a.off null, cb2 cb2ok = false models.b.trigger "sample" # only cb1 QUnit.test "remove chain -- context", 3, -> ctx1 = { ok: true } ctx2 = { ok: true} cb = -> ok @ok models.a.on "sample@chain", cb, ctx1 models.a.on "sample@chain", cb, ctx2 models.b.trigger "sample" # both callbacks models.a.off null, null, ctx2 ctx2.ok = false models.b.trigger "sample" # only ctx1 callback listenToChain = (listener, events=["sample"]) -> chainedEvents = _.map(events, (evt) -> "#{evt}<EMAIL>").join(' ') listener.listenTo models.a, chainedEvents, -> ok(true, "got <EMAIL>") _.each events, (evt) -> models.c.trigger evt listener.stopListening() noEvents(listener) QUnit.test "listenTo chain", 2, -> listenToChain models.item0 QUnit.test "listenTo multiple events", 4, -> listenToChain models.item0, ["first", "second", "third"] QUnit.test "backbone listenTo chain", 2, -> listenToChain Backbone QUnit.test "generic listener listenTo", 2, -> listenToChain new class _.extend @::, Backbone.Events _.each { model: Backbone.Model collection: Backbone.Collection view: Backbone.View router: Backbone.Router history: Backbone.History }, (klass, name) -> QUnit.test "#{name} listenTo chain", 2, -> listenToChain new klass QUnit.test "listenTo chain stopListening to model", 2, -> models.agent.listenTo models.a, "<EMAIL>", -> ok(true, "got <EMAIL>") models.c.trigger "sample" # handled models.agent.stopListening models.a models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain, stopListening to event", 2, -> models.agent.listenTo models.a, "<EMAIL>", -> ok(true, "got <EMAIL>") models.c.trigger "sample" # handled models.agent.stopListening models.a, "<EMAIL>" models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain stopListening to other event", 3, -> models.agent.listenTo models.a, "<EMAIL>", -> ok(true, "got <EMAIL>") models.c.trigger "sample" # handled models.agent.stopListening models.a, "<EMAIL>" models.c.trigger "sample" # handled models.agent.stopListening() noEvents()
true
$(document).ready -> unless window.console window.console = {} names = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd' ] for name in names window.console[name] = -> window.models = models = {} collections = {} noEvents = (other) -> ok(_.all(_.compact _.flatten([models, collections, other]), (sender) -> return false if sender._eventChains return false unless _.isEmpty(_.omit(sender._events, 'all')) # ignore 'all' events, created by collection true ), "all events and chains removed") testEvent = (options) -> options.model.on options.event, options.handler, options.context options.trigger() if options.update options.update() options.trigger() options.model.off options.event noEvents() QUnit.module "Backbone.Chaining", setup: -> models.a = new Backbone.Model name: "a" models.b = new Backbone.Model name: "b" models.c = new Backbone.Model name: "c" models.item0 = new Backbone.Model name: "item0" models.item1 = new Backbone.Model name: "item1" models.sub0 = new Backbone.Model name: "sub0" models.sub1 = new Backbone.Model name: "sub1" models.agent = new Backbone.Model name: "agent" collections.p = new Backbone.Collection [models.item0, models.item1] models.a.set 'chain', models.b models.b.set 'chain', models.c models.item0.set 'sub', models.sub0 models.item1.set 'sub', models.sub1 models.a.set 'coll', collections.p QUnit.test "get with null attribute", -> equal models.a.get(null), null QUnit.test "get without chain", 1, -> equal models.a.get('name'), 'a' QUnit.test "get malformed chain -- missing tail", 1, -> throws (-> models.a.get 'chain.'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced left bracket", 1, -> throws (-> models.a.get 'chain]here'), /malformed chain/ QUnit.test "get malformed chain -- unbalanced bracket", 1, -> throws (-> models.a.get 'chain[here'), /malformed chain/ QUnit.test "get malformed chain -- missing dot", 1, -> throws (-> models.a.get 'chain[2]x'), /malformed chain/ QUnit.test "get malformed chain -- missing tail after bracket", 1, -> throws (-> models.a.get 'chain[2].'), /malformed chain/ QUnit.test "get single chain", 1, -> equal models.a.get('chain.name'), 'b' QUnit.test "get double chain", 1, -> equal models.a.get('chain.chain.name'), 'c' QUnit.test "get chain with collection index", 3, -> equal models.a.get('coll[0]'), models.item0, "index 0" equal models.a.get('coll[1]'), models.item1, "index 1" equal models.a.get('coll[#]'), models.item1, "index 1" QUnit.test "get chain with collection index chain", 3, -> equal models.a.get('coll[0].sub.name'), 'sub0', "index 0" equal models.a.get('coll[1].sub.name'), 'sub1', "index 1" equal models.a.get('coll[#].sub.name'), 'sub1', "index 1" QUnit.test "get chain with collection star", 1, -> deepEqual models.a.get('coll[*]'), [models.item0, models.item1] QUnit.test "get chain with collection star chained", 1, -> deepEqual models.a.get('coll[*].sub.name'), ['sub0', 'sub1'] QUnit.test "get broken single chain", 1, -> models.a.set 'chain', null equal models.a.get('chain.name'), undefined QUnit.test "get broken double chain", 1, -> models.b.set 'chain', null equal models.a.get('chain.chain.name'), undefined QUnit.test "get broken collection index chain", 1, -> models.a.set 'coll', null equal models.a.get('coll[0].sub.name'), undefined QUnit.test "get invalid collection index chain", 1, -> equal models.a.get('coll[2].sub.name'), undefined QUnit.test "set without chain", 1, -> models.a.set 'attr', 'val' equal models.a.get('attr'), 'val' QUnit.test "set malformed chain -- no attribute", 1, -> throws (-> models.a.set 'chain.', 'val'), /malformed chain/ QUnit.test "set single chain", 1, -> models.a.set 'chain.attr', 'val' equal models.b.get('attr'), 'val' QUnit.test "set double chain", 1, -> models.a.set 'chain.chain.attr', 'val' equal models.c.get('attr'), 'val' QUnit.test "set chain with collection index", 1, -> models.a.set 'coll[0].sub.attr', 'val' equal models.sub0.get('attr'), 'val' QUnit.test "set chain with collection last index", 1, -> models.a.set 'coll[#].sub.attr', 'val' equal models.sub1.get('attr'), 'val' QUnit.test "set chain with collection star", 2, -> models.a.set 'coll[*].sub.attr', 'val' equal models.sub0.get('attr'), 'val' equal models.sub1.get('attr'), 'val' QUnit.test "event malformed chain -- missing attr", 1, -> throws (-> models.a.on "name@"), /malformed chain/ QUnit.test "event malformed chain -- too many atsigns", 1, -> throws (-> models.a.on "name@here@there"), /malformed chain/ QUnit.test "event without chain", 2, -> testEvent model: models.a event: "sample" handler: -> ok(true, "got sample") trigger: -> models.a.trigger "sample" QUnit.test "event chain", 3, -> testEvent model: models.a event: "sample@chain" handler: -> ok(true, "got sample@chain") equal @, models.a trigger: -> models.b.trigger "sample" QUnit.test "event chain context", 2, -> testEvent model: models.a context: {ctx: "test"} event: "sample@chain" handler: -> equal @ctx, "test" trigger: -> models.b.trigger "sample" QUnit.test "event double chain", 2, -> testEvent model: models.a event: "PI:EMAIL:<EMAIL>END_PI" handler: -> ok(true, "got PI:EMAIL:<EMAIL>END_PI") trigger: -> models.c.trigger "sample" QUnit.test "mix chains and nonchain", 4, -> testEvent model: models.a event: "nonchain single@chain PI:EMAIL:<EMAIL>END_PI" handler: -> ok(true, "got event") trigger: -> models.a.trigger "nonchain" models.b.trigger "single" models.c.trigger "double" QUnit.test "event map", 7, -> testEvent model: models.a event: nonchain: -> ok(true, "got nonchain event") "single@chain": -> ok(true, "got single event") "PI:EMAIL:<EMAIL>END_PI": -> ok(true, "got double event") "nonchain-mixed PI:EMAIL:<EMAIL>END_PI-PI:EMAIL:<EMAIL>END_PI@PI:EMAIL:<EMAIL>END_PI PI:EMAIL:<EMAIL>END_PI": -> ok(true, "got mixed event") trigger: -> models.a.trigger "nonchain" models.a.trigger "nonchain-mixed" models.b.trigger "single" models.b.trigger "single-mixed" models.c.trigger "double" models.c.trigger "double-mixed" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[0].sub" handler: (val) -> equal(val, "yes", "got sample@coll[0].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "no" QUnit.test "event chain with collection index", 2, -> testEvent model: models.a event: "sample@coll[#].sub" handler: (val) -> equal(val, "yes", "got sample@coll[#].sub") trigger: -> models.sub0.trigger "sample", "no" models.sub1.trigger "sample", "yes" QUnit.test "event chain with collection star", 3, -> testEvent model: models.a event: "sample@coll[*].sub" handler: (val) -> equal(val, "yes", "got sample@coll[*].sub") trigger: -> models.sub0.trigger "sample", "yes" models.sub1.trigger "sample", "yes" QUnit.test "event pass-through collection", 3, -> container = new Backbone.Collection [models.a] testEvent model: container event: "add@coll" handler: -> ok(true, "got add@coll") equal @, container, "context" trigger: -> models.a.get('coll').add new Backbone.Model name: "added" QUnit.test "change event chain", 4, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change@chain" handler: (model, options) -> equal model, models.b equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event chain", 5, -> models.b.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain" handler: (model, value, options) -> equal model, models.b equal value, 'new' equal model.previous('attr'), 'previous' equal model.get('attr'), 'new' trigger: -> models.b.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "change:attr event double chain", 5, -> models.c.set 'attr', 'previous' testEvent model: models.a event: "change:attr@chain.chain" handler: (model, value, options) -> equal model, models.c equal value, 'new' equal(model.previous('attr'), 'previous') equal(model.get('attr'), 'new') trigger: -> models.c.set 'attr', 'new' QUnit.test "update event chain -- break chain", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> models.item0.set 'sub', null trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- remove from collection", 4, -> testEvent model: models.a event: "sample@coll[*].sub" handler: -> ok(true, "got sample@coll[*].sub") update: -> collections.p.remove(models.item0) trigger: -> models.sub0.trigger "sample" models.sub1.trigger "sample" QUnit.test "update event chain -- make chain: add field", 1, -> models.a.on "sample@coll[*].sub.extra.chain", -> ok(true, "got sample@coll[*].sub.extra.chain") models.sub1.set 'extra', models.b models.c.trigger "sample" QUnit.test "update event chain -- make chain: add element", 1, -> models.a.on "sample@coll[2].sub", -> ok(true, "got sample@coll[*].sub.extra.chain") sub2 = new Backbone.Model name: "sub2" collections.p.add new Backbone.Model name: "item2", sub: sub2 sub2.trigger "sample" QUnit.test "update event chain -- change root", 2, -> newTail = new Backbone.Model name: "newTail" newHead = new Backbone.Model name: "newHead", chain: newTail models.a.on "PI:EMAIL:<EMAIL>END_PI", (expected) -> equal expected, 'yes' models.b.trigger "sample", "no" models.c.trigger "sample", "yes" newHead.trigger "sample", "no" newTail.trigger "sample", "no" models.b.trigger "sample", "no" models.a.set "chain", newHead models.c.trigger "sample", "no" newHead.trigger "sample", "no" newTail.trigger "sample", "yes" QUnit.test "remove chain -- event name", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "event1@chain", cb models.a.on "event2@chain", cb models.b.trigger "event1", "yes" models.b.trigger "event2", "yes" models.a.off "event1@chain" models.b.trigger "event1", "no" models.b.trigger "event2", "yes" QUnit.test "remove chain -- attr", 3, -> cb = (expected) -> equal expected, 'yes' models.a.on "sample@chain", cb models.a.on "sample@coll", cb models.b.trigger "sample", "yes" collections.p.trigger "sample", "yes" models.a.off "sample@chain" models.b.trigger "sample", "no" collections.p.trigger "sample", "yes" QUnit.test "remove chain -- callback", 3, -> cb1 = (expected) -> ok(true) cb2ok = true cb2 = (expected) -> ok(cb2ok) models.a.on "sample@chain", cb1 models.a.on "sample@chain", cb2 models.b.trigger "sample" # both callbacks models.a.off null, cb2 cb2ok = false models.b.trigger "sample" # only cb1 QUnit.test "remove chain -- context", 3, -> ctx1 = { ok: true } ctx2 = { ok: true} cb = -> ok @ok models.a.on "sample@chain", cb, ctx1 models.a.on "sample@chain", cb, ctx2 models.b.trigger "sample" # both callbacks models.a.off null, null, ctx2 ctx2.ok = false models.b.trigger "sample" # only ctx1 callback listenToChain = (listener, events=["sample"]) -> chainedEvents = _.map(events, (evt) -> "#{evt}PI:EMAIL:<EMAIL>END_PI").join(' ') listener.listenTo models.a, chainedEvents, -> ok(true, "got PI:EMAIL:<EMAIL>END_PI") _.each events, (evt) -> models.c.trigger evt listener.stopListening() noEvents(listener) QUnit.test "listenTo chain", 2, -> listenToChain models.item0 QUnit.test "listenTo multiple events", 4, -> listenToChain models.item0, ["first", "second", "third"] QUnit.test "backbone listenTo chain", 2, -> listenToChain Backbone QUnit.test "generic listener listenTo", 2, -> listenToChain new class _.extend @::, Backbone.Events _.each { model: Backbone.Model collection: Backbone.Collection view: Backbone.View router: Backbone.Router history: Backbone.History }, (klass, name) -> QUnit.test "#{name} listenTo chain", 2, -> listenToChain new klass QUnit.test "listenTo chain stopListening to model", 2, -> models.agent.listenTo models.a, "PI:EMAIL:<EMAIL>END_PI", -> ok(true, "got PI:EMAIL:<EMAIL>END_PI") models.c.trigger "sample" # handled models.agent.stopListening models.a models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain, stopListening to event", 2, -> models.agent.listenTo models.a, "PI:EMAIL:<EMAIL>END_PI", -> ok(true, "got PI:EMAIL:<EMAIL>END_PI") models.c.trigger "sample" # handled models.agent.stopListening models.a, "PI:EMAIL:<EMAIL>END_PI" models.c.trigger "sample" # not handled noEvents() QUnit.test "listenTo chain stopListening to other event", 3, -> models.agent.listenTo models.a, "PI:EMAIL:<EMAIL>END_PI", -> ok(true, "got PI:EMAIL:<EMAIL>END_PI") models.c.trigger "sample" # handled models.agent.stopListening models.a, "PI:EMAIL:<EMAIL>END_PI" models.c.trigger "sample" # handled models.agent.stopListening() noEvents()
[ { "context": "arch: (text, rid, limit) ->\n\t\t###\n\t\t\ttext = 'from:rodrigo mention:gabriel chat'\n\t\t###\n\n\t\tresult =\n\t\t\tmessag", "end": 82, "score": 0.8924514651298523, "start": 75, "tag": "USERNAME", "value": "rodrigo" }, { "context": ", limit) ->\n\t\t###\n\t\t\ttext =...
server/methods/messageSearch.coffee
org100h1/Rocket.Panda
0
Meteor.methods messageSearch: (text, rid, limit) -> ### text = 'from:rodrigo mention:gabriel chat' ### result = messages: [] users: [] channels: [] query = {} options = sort: ts: -1 limit: limit or 20 # Query for senders from = [] text = text.replace /from:([a-z0-9.-_]+)/ig, (match, username, index) -> from.push username return '' if from.length > 0 query['u.username'] = $regex: from.join('|') $options: 'i' # Query for mentions mention = [] text = text.replace /mention:([a-z0-9.-_]+)/ig, (match, username, index) -> mention.push username return '' if mention.length > 0 query['mentions.username'] = $regex: mention.join('|') $options: 'i' # Query in message text text = text.trim().replace(/\s\s/g, ' ') if text isnt '' # Regex search if /^\/.+\/[imxs]*$/.test text r = text.split('/') query.msg = $regex: r[1] $options: r[2] else if RocketChat.settings.get 'Message_AlwaysSearchRegExp' query.msg = $regex: text $options: 'i' else query.$text = $search: text options.fields = score: $meta: "textScore" # options.sort = # score: # $meta: 'textScore' if Object.keys(query).length > 0 query.t = { $ne: 'rm' } # hide removed messages (userful when searching for user messages) query._hidden = { $ne: true } # don't return _hidden messages # Filter by room if rid? query.rid = rid try if Meteor.call('canAccessRoom', rid, this.userId) isnt false result.messages = RocketChat.models.Messages.find(query, options).fetch() # make sure we don't return more than limit results # limit -= result.messages?.length # ### # # USERS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # username: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # username: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.users = Meteor.users.find(query, options).fetch() # ### # # CHANNELS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # t: 'c' # name: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # name: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.channels = ChatRoom.find(query, options).fetch() return result
84707
Meteor.methods messageSearch: (text, rid, limit) -> ### text = 'from:rodrigo mention:<NAME> chat' ### result = messages: [] users: [] channels: [] query = {} options = sort: ts: -1 limit: limit or 20 # Query for senders from = [] text = text.replace /from:([a-z0-9.-_]+)/ig, (match, username, index) -> from.push username return '' if from.length > 0 query['u.username'] = $regex: from.join('|') $options: 'i' # Query for mentions mention = [] text = text.replace /mention:([a-z0-9.-_]+)/ig, (match, username, index) -> mention.push username return '' if mention.length > 0 query['mentions.username'] = $regex: mention.join('|') $options: 'i' # Query in message text text = text.trim().replace(/\s\s/g, ' ') if text isnt '' # Regex search if /^\/.+\/[imxs]*$/.test text r = text.split('/') query.msg = $regex: r[1] $options: r[2] else if RocketChat.settings.get 'Message_AlwaysSearchRegExp' query.msg = $regex: text $options: 'i' else query.$text = $search: text options.fields = score: $meta: "textScore" # options.sort = # score: # $meta: 'textScore' if Object.keys(query).length > 0 query.t = { $ne: 'rm' } # hide removed messages (userful when searching for user messages) query._hidden = { $ne: true } # don't return _hidden messages # Filter by room if rid? query.rid = rid try if Meteor.call('canAccessRoom', rid, this.userId) isnt false result.messages = RocketChat.models.Messages.find(query, options).fetch() # make sure we don't return more than limit results # limit -= result.messages?.length # ### # # USERS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # username: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # username: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.users = Meteor.users.find(query, options).fetch() # ### # # CHANNELS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # t: 'c' # name: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # name: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.channels = ChatRoom.find(query, options).fetch() return result
true
Meteor.methods messageSearch: (text, rid, limit) -> ### text = 'from:rodrigo mention:PI:NAME:<NAME>END_PI chat' ### result = messages: [] users: [] channels: [] query = {} options = sort: ts: -1 limit: limit or 20 # Query for senders from = [] text = text.replace /from:([a-z0-9.-_]+)/ig, (match, username, index) -> from.push username return '' if from.length > 0 query['u.username'] = $regex: from.join('|') $options: 'i' # Query for mentions mention = [] text = text.replace /mention:([a-z0-9.-_]+)/ig, (match, username, index) -> mention.push username return '' if mention.length > 0 query['mentions.username'] = $regex: mention.join('|') $options: 'i' # Query in message text text = text.trim().replace(/\s\s/g, ' ') if text isnt '' # Regex search if /^\/.+\/[imxs]*$/.test text r = text.split('/') query.msg = $regex: r[1] $options: r[2] else if RocketChat.settings.get 'Message_AlwaysSearchRegExp' query.msg = $regex: text $options: 'i' else query.$text = $search: text options.fields = score: $meta: "textScore" # options.sort = # score: # $meta: 'textScore' if Object.keys(query).length > 0 query.t = { $ne: 'rm' } # hide removed messages (userful when searching for user messages) query._hidden = { $ne: true } # don't return _hidden messages # Filter by room if rid? query.rid = rid try if Meteor.call('canAccessRoom', rid, this.userId) isnt false result.messages = RocketChat.models.Messages.find(query, options).fetch() # make sure we don't return more than limit results # limit -= result.messages?.length # ### # # USERS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # username: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # username: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.users = Meteor.users.find(query, options).fetch() # ### # # CHANNELS # ### # if from.length is 0 and mention.length is 0 and text isnt '' # query = # t: 'c' # name: # $regex: text # $options: 'i' # options = # limit: 5 # sort: # name: 1 # fields: # username: 1 # name: 1 # status: 1 # utcOffset: 1 # result.channels = ChatRoom.find(query, options).fetch() return result
[ { "context": "to flag uses of backticks (embedded JS).\n# @author Julian Rosse\n###\n'use strict'\n\nmodule.exports =\n meta:\n do", "end": 91, "score": 0.9998577237129211, "start": 79, "tag": "NAME", "value": "Julian Rosse" } ]
src/rules/no-backticks.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview A rule to flag uses of backticks (embedded JS). # @author Julian Rosse ### 'use strict' module.exports = meta: docs: description: 'disallow backticks' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/max-lines-per-function' schema: [] create: (context) -> #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- PassthroughLiteral: (node) -> context.report { node message: "Don't use backticks" }
80266
###* # @fileoverview A rule to flag uses of backticks (embedded JS). # @author <NAME> ### 'use strict' module.exports = meta: docs: description: 'disallow backticks' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/max-lines-per-function' schema: [] create: (context) -> #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- PassthroughLiteral: (node) -> context.report { node message: "Don't use backticks" }
true
###* # @fileoverview A rule to flag uses of backticks (embedded JS). # @author PI:NAME:<NAME>END_PI ### 'use strict' module.exports = meta: docs: description: 'disallow backticks' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/max-lines-per-function' schema: [] create: (context) -> #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- PassthroughLiteral: (node) -> context.report { node message: "Don't use backticks" }
[ { "context": "shortName: 'snippy'\ndescription: 'snippy'\nbaseUrl: 'https://wtwf", "end": 14, "score": 0.5676376223564148, "start": 12, "tag": "NAME", "value": "sn" }, { "context": "shortName: 'snippy'\ndescription: 'snippy'\nbaseUrl: 'https://wtwf.com", "end": 18, "score": 0...
branding.wtwf/snippy_config.cson
arkarkark/snippy
0
shortName: 'snippy' description: 'snippy' baseUrl: 'https://wtwf.com/' developer: 'ark'
84388
shortName: '<NAME>ippy' description: 'snippy' baseUrl: 'https://wtwf.com/' developer: 'ark'
true
shortName: 'PI:NAME:<NAME>END_PIippy' description: 'snippy' baseUrl: 'https://wtwf.com/' developer: 'ark'
[ { "context": " \"feed\"\n link: url\n picture: image\n name: title\n description: desc\n\n FB.ui obj, callback\n re", "end": 192, "score": 0.9364708662033081, "start": 187, "tag": "NAME", "value": "title" } ]
app/assets/javascripts/social.js.coffee
saisjournal/bcjournal
1
############### # Facebook JS # ############### postToFeed = (title, desc, url, image) -> callback = (response) -> obj = method: "feed" link: url picture: image name: title description: desc FB.ui obj, callback return window.fbAsyncInit = -> FB.init appId: "385604281606707" xfbml: true version: "v2.2" return ((d, s, id) -> js = undefined fjs = d.getElementsByTagName(s)[0] return if d.getElementById(id) js = d.createElement(s) js.id = id js.src = "//connect.facebook.net/en_US/sdk.js" fjs.parentNode.insertBefore js, fjs return ) document, "script", "facebook-jssdk" # social listeners $ -> $(".fbshare").on 'click', (e) -> e.preventDefault() window.open('https://www.facebook.com/sharer/sharer.php?u=' + location.href, 'sharer', 'width=626,height=436'); $(".tweet-this").on 'click', (e) -> e.preventDefault() window.open(this.href, 'sharer', 'width=626,height=436')
107188
############### # Facebook JS # ############### postToFeed = (title, desc, url, image) -> callback = (response) -> obj = method: "feed" link: url picture: image name: <NAME> description: desc FB.ui obj, callback return window.fbAsyncInit = -> FB.init appId: "385604281606707" xfbml: true version: "v2.2" return ((d, s, id) -> js = undefined fjs = d.getElementsByTagName(s)[0] return if d.getElementById(id) js = d.createElement(s) js.id = id js.src = "//connect.facebook.net/en_US/sdk.js" fjs.parentNode.insertBefore js, fjs return ) document, "script", "facebook-jssdk" # social listeners $ -> $(".fbshare").on 'click', (e) -> e.preventDefault() window.open('https://www.facebook.com/sharer/sharer.php?u=' + location.href, 'sharer', 'width=626,height=436'); $(".tweet-this").on 'click', (e) -> e.preventDefault() window.open(this.href, 'sharer', 'width=626,height=436')
true
############### # Facebook JS # ############### postToFeed = (title, desc, url, image) -> callback = (response) -> obj = method: "feed" link: url picture: image name: PI:NAME:<NAME>END_PI description: desc FB.ui obj, callback return window.fbAsyncInit = -> FB.init appId: "385604281606707" xfbml: true version: "v2.2" return ((d, s, id) -> js = undefined fjs = d.getElementsByTagName(s)[0] return if d.getElementById(id) js = d.createElement(s) js.id = id js.src = "//connect.facebook.net/en_US/sdk.js" fjs.parentNode.insertBefore js, fjs return ) document, "script", "facebook-jssdk" # social listeners $ -> $(".fbshare").on 'click', (e) -> e.preventDefault() window.open('https://www.facebook.com/sharer/sharer.php?u=' + location.href, 'sharer', 'width=626,height=436'); $(".tweet-this").on 'click', (e) -> e.preventDefault() window.open(this.href, 'sharer', 'width=626,height=436')
[ { "context": "m to keep out the dirt.\n '''\n\n scientificName: 'Mellivora capensis'\n mainImage: 'assets/fieldguide-content/mammals/", "end": 641, "score": 0.9998716711997986, "start": 623, "tag": "NAME", "value": "Mellivora capensis" } ]
app/lib/field-guide-content/honey_badger.coffee
zooniverse/wildcam-gorongosa-facebook
7
module.exports = description: ''' The honey badger is part of the weasel family, related to skunks, otters, ferrets, and other badgers. Honey badgers are muscular and compact, with a thick skull, well-developed neck and shoulders, and strong forelegs armed with bearlike claws. The honey badger’s coloration is striking with coarse jet-black fur covering its lower body and contrasting white or gray fur covering the upper body. They have powerful jaws and loose skin that is nearly a quarter of an inch thick. They have internal ears that can be closed, allowing them to keep out the dirt. ''' scientificName: 'Mellivora capensis' mainImage: 'assets/fieldguide-content/mammals/honey_badger/badger-feature.png' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: 'Length: 60-75 cm' }, { label: 'Height' value: '23-28 cm ' }, { label: 'Weight' value: '8-16 kg ' }, { label: 'Lifespan' value: 'Up to 24 years' }, { label: 'Gestation' value: '6 months' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'This species lives in a wide variety of habitat types. They can be found in moist savannas, semideserts, and montane forests.' }, { title: 'Diet' content: 'Bee larvae and honey; also rodents, birds, reptiles, amphibians, fish, insects, fruit, and carrion.' }, { title: 'Predators' content: 'Humans' }, { title: 'Behavior' content: ''' Honey badgers are solitary, nomadic, and notoriously aggressive. They occupy a large range and move around daily to forage. In general, females have a smaller home range (126 sq km) compared to males (151 sq km). Home ranges of individuals overlap, and males may be observed meeting after foraging and exchanging grunts while sniffing each other and rolling in the earth. They regularly and liberally apply scent markings to crevices, holes, and the bases of trees. Males will become aggressive if another male attempts to intrude into their marked burrow or if their mate is threatened. Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill. ''' }, { title: 'Breeding' content: ''' After a gestation period of six months, honey badgers will give birth to one to four young at a time. Females give birth in a chamber or burrow that they line with grass or leaves. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Honey badgers can trot long distances, as far as 35 km (22 miles), in a night.</li> <li>Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/honey_badger/honey-badger-map.jpg"/>' }]
155179
module.exports = description: ''' The honey badger is part of the weasel family, related to skunks, otters, ferrets, and other badgers. Honey badgers are muscular and compact, with a thick skull, well-developed neck and shoulders, and strong forelegs armed with bearlike claws. The honey badger’s coloration is striking with coarse jet-black fur covering its lower body and contrasting white or gray fur covering the upper body. They have powerful jaws and loose skin that is nearly a quarter of an inch thick. They have internal ears that can be closed, allowing them to keep out the dirt. ''' scientificName: '<NAME>' mainImage: 'assets/fieldguide-content/mammals/honey_badger/badger-feature.png' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: 'Length: 60-75 cm' }, { label: 'Height' value: '23-28 cm ' }, { label: 'Weight' value: '8-16 kg ' }, { label: 'Lifespan' value: 'Up to 24 years' }, { label: 'Gestation' value: '6 months' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'This species lives in a wide variety of habitat types. They can be found in moist savannas, semideserts, and montane forests.' }, { title: 'Diet' content: 'Bee larvae and honey; also rodents, birds, reptiles, amphibians, fish, insects, fruit, and carrion.' }, { title: 'Predators' content: 'Humans' }, { title: 'Behavior' content: ''' Honey badgers are solitary, nomadic, and notoriously aggressive. They occupy a large range and move around daily to forage. In general, females have a smaller home range (126 sq km) compared to males (151 sq km). Home ranges of individuals overlap, and males may be observed meeting after foraging and exchanging grunts while sniffing each other and rolling in the earth. They regularly and liberally apply scent markings to crevices, holes, and the bases of trees. Males will become aggressive if another male attempts to intrude into their marked burrow or if their mate is threatened. Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill. ''' }, { title: 'Breeding' content: ''' After a gestation period of six months, honey badgers will give birth to one to four young at a time. Females give birth in a chamber or burrow that they line with grass or leaves. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Honey badgers can trot long distances, as far as 35 km (22 miles), in a night.</li> <li>Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/honey_badger/honey-badger-map.jpg"/>' }]
true
module.exports = description: ''' The honey badger is part of the weasel family, related to skunks, otters, ferrets, and other badgers. Honey badgers are muscular and compact, with a thick skull, well-developed neck and shoulders, and strong forelegs armed with bearlike claws. The honey badger’s coloration is striking with coarse jet-black fur covering its lower body and contrasting white or gray fur covering the upper body. They have powerful jaws and loose skin that is nearly a quarter of an inch thick. They have internal ears that can be closed, allowing them to keep out the dirt. ''' scientificName: 'PI:NAME:<NAME>END_PI' mainImage: 'assets/fieldguide-content/mammals/honey_badger/badger-feature.png' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: 'Length: 60-75 cm' }, { label: 'Height' value: '23-28 cm ' }, { label: 'Weight' value: '8-16 kg ' }, { label: 'Lifespan' value: 'Up to 24 years' }, { label: 'Gestation' value: '6 months' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'This species lives in a wide variety of habitat types. They can be found in moist savannas, semideserts, and montane forests.' }, { title: 'Diet' content: 'Bee larvae and honey; also rodents, birds, reptiles, amphibians, fish, insects, fruit, and carrion.' }, { title: 'Predators' content: 'Humans' }, { title: 'Behavior' content: ''' Honey badgers are solitary, nomadic, and notoriously aggressive. They occupy a large range and move around daily to forage. In general, females have a smaller home range (126 sq km) compared to males (151 sq km). Home ranges of individuals overlap, and males may be observed meeting after foraging and exchanging grunts while sniffing each other and rolling in the earth. They regularly and liberally apply scent markings to crevices, holes, and the bases of trees. Males will become aggressive if another male attempts to intrude into their marked burrow or if their mate is threatened. Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill. ''' }, { title: 'Breeding' content: ''' After a gestation period of six months, honey badgers will give birth to one to four young at a time. Females give birth in a chamber or burrow that they line with grass or leaves. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Honey badgers can trot long distances, as far as 35 km (22 miles), in a night.</li> <li>Honey badgers are known to have a mutualistic relationship with the small bird known as the greater honeyguide (Indicator indicator). This bird will lead the honey badger to beehives and is able to feed after the honey badger has had its fill.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/honey_badger/honey-badger-map.jpg"/>' }]
[ { "context": "ue.coffee: Github issue class\n#\n# Copyright © 2013 Josh Priestley. All rights reserved\n#\n\n# Initiate class\nclass Is", "end": 72, "score": 0.999646782875061, "start": 58, "tag": "NAME", "value": "Josh Priestley" }, { "context": ") ->\n\n # List comments on an issu...
src/octonode/issue.coffee
troupe/octonode
0
# # issue.coffee: Github issue class # # Copyright © 2013 Josh Priestley. All rights reserved # # Initiate class class Issue constructor: (@repo, @number, @client) -> # List comments on an issue # '/repos/pksunkara/hub/issues/37/comments' GET comments: (cb) -> @client.get "/repos/" + @repo + "/issues/" + @number + "/comments", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b # Export module module.exports = Issue
168224
# # issue.coffee: Github issue class # # Copyright © 2013 <NAME>. All rights reserved # # Initiate class class Issue constructor: (@repo, @number, @client) -> # List comments on an issue # '/repos/pksunkara/hub/issues/37/comments' GET comments: (cb) -> @client.get "/repos/" + @repo + "/issues/" + @number + "/comments", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b # Export module module.exports = Issue
true
# # issue.coffee: Github issue class # # Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved # # Initiate class class Issue constructor: (@repo, @number, @client) -> # List comments on an issue # '/repos/pksunkara/hub/issues/37/comments' GET comments: (cb) -> @client.get "/repos/" + @repo + "/issues/" + @number + "/comments", (err, s, b) -> return cb(err) if err if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b # Export module module.exports = Issue
[ { "context": "pp_secret = process.env.FACEBOOK_APP_SECRET || '67f736184742334282b5a38d35694023'\n\n initMongo: ->\n mon", "end": 577, "score": 0.5496439337730408, "start": 571, "tag": "KEY", "value": "f73618" }, { "context": "et = process.env.FACEBOOK_APP_SECRET || '67f7361847423...
src/config.coffee
robertothais/plop-web
0
mongoose = require 'mongoose' redis = require 'redis' socketRedis = require 'socket.io/node_modules/redis' url = require 'url' http = require 'http' class Config constructor: -> @environment = process.env.NODE_ENV || 'development' this.initErrors() this.initMongo() this.initRedis() this.initFacebook() this.initGlobalAgent() this.socketConfig() initFacebook: -> @facebook = {} @facebook.app_id = process.env.FACEBOOK_APP_ID || '302946899759152' @facebook.app_secret = process.env.FACEBOOK_APP_SECRET || '67f736184742334282b5a38d35694023' initMongo: -> mongoose.connect process.env.MONGO_URL || 'mongodb://localhost/plop' initRedis: -> newClient = (socket=false) -> constructor = if socket then socketRedis else redis if process.env.REDIS_URL? redisUrl = url.parse process.env.REDIS_URL client = constructor.createClient redisUrl.port, redisUrl.hostname client.on 'error', process.reportError client.auth redisUrl.auth.split(":")[1] client else client = redis.createClient() client.on 'error', process.reportError client @redis = session: newClient() @redis.socket = {} for key in [ 'pub', 'sub', 'store' ] @redis.socket[key] = newClient true initErrors: -> unless @environment is 'development' @airbrake = require('airbrake').createClient 'ec998fc8de1c2584705784a07d381171' @airbrake.serviceHost = 'errbit.plop.pe' @airbrake.timeout = 60 * 1000 @airbrake.handleExceptions() process.reportError = (err) => console.error err if @airbrake @airbrake.notify err console.error 'Sent to Errbit' initGlobalAgent: -> http.globalAgent.maxSockets = Infinity socketConfig: -> @socket = {} @socket.logLevel = if @environment == 'development' then 3 else 1 global.config = new Config
84460
mongoose = require 'mongoose' redis = require 'redis' socketRedis = require 'socket.io/node_modules/redis' url = require 'url' http = require 'http' class Config constructor: -> @environment = process.env.NODE_ENV || 'development' this.initErrors() this.initMongo() this.initRedis() this.initFacebook() this.initGlobalAgent() this.socketConfig() initFacebook: -> @facebook = {} @facebook.app_id = process.env.FACEBOOK_APP_ID || '302946899759152' @facebook.app_secret = process.env.FACEBOOK_APP_SECRET || '67<KEY>4<KEY>' initMongo: -> mongoose.connect process.env.MONGO_URL || 'mongodb://localhost/plop' initRedis: -> newClient = (socket=false) -> constructor = if socket then socketRedis else redis if process.env.REDIS_URL? redisUrl = url.parse process.env.REDIS_URL client = constructor.createClient redisUrl.port, redisUrl.hostname client.on 'error', process.reportError client.auth redisUrl.auth.split(":")[1] client else client = redis.createClient() client.on 'error', process.reportError client @redis = session: newClient() @redis.socket = {} for key in [ 'pub', 'sub', 'store' ] @redis.socket[key] = newClient true initErrors: -> unless @environment is 'development' @airbrake = require('airbrake').createClient 'ec998fc8de1c2584705784a07d381171' @airbrake.serviceHost = 'errbit.plop.pe' @airbrake.timeout = 60 * 1000 @airbrake.handleExceptions() process.reportError = (err) => console.error err if @airbrake @airbrake.notify err console.error 'Sent to Errbit' initGlobalAgent: -> http.globalAgent.maxSockets = Infinity socketConfig: -> @socket = {} @socket.logLevel = if @environment == 'development' then 3 else 1 global.config = new Config
true
mongoose = require 'mongoose' redis = require 'redis' socketRedis = require 'socket.io/node_modules/redis' url = require 'url' http = require 'http' class Config constructor: -> @environment = process.env.NODE_ENV || 'development' this.initErrors() this.initMongo() this.initRedis() this.initFacebook() this.initGlobalAgent() this.socketConfig() initFacebook: -> @facebook = {} @facebook.app_id = process.env.FACEBOOK_APP_ID || '302946899759152' @facebook.app_secret = process.env.FACEBOOK_APP_SECRET || '67PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI' initMongo: -> mongoose.connect process.env.MONGO_URL || 'mongodb://localhost/plop' initRedis: -> newClient = (socket=false) -> constructor = if socket then socketRedis else redis if process.env.REDIS_URL? redisUrl = url.parse process.env.REDIS_URL client = constructor.createClient redisUrl.port, redisUrl.hostname client.on 'error', process.reportError client.auth redisUrl.auth.split(":")[1] client else client = redis.createClient() client.on 'error', process.reportError client @redis = session: newClient() @redis.socket = {} for key in [ 'pub', 'sub', 'store' ] @redis.socket[key] = newClient true initErrors: -> unless @environment is 'development' @airbrake = require('airbrake').createClient 'ec998fc8de1c2584705784a07d381171' @airbrake.serviceHost = 'errbit.plop.pe' @airbrake.timeout = 60 * 1000 @airbrake.handleExceptions() process.reportError = (err) => console.error err if @airbrake @airbrake.notify err console.error 'Sent to Errbit' initGlobalAgent: -> http.globalAgent.maxSockets = Infinity socketConfig: -> @socket = {} @socket.logLevel = if @environment == 'development' then 3 else 1 global.config = new Config